------------------------------------------------------------------------------
-- ADVANTAGE 2018.6.4.4000
-- Functions, Views, Stored Procedures
-- 2018-05-15
------------------------------------------------------------------------------

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetActor]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetActor]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetActualMargin]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetActualMargin]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCostPlusMargin]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetCostPlusMargin]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetEffectiveDate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetEffectiveDate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetEffectivePrice]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetEffectivePrice]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetGrossContribution]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetGrossContribution]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetGrossMargin]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetGrossMargin]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AB_Account_Is_Sub_Control]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AB_Account_Is_Sub_Control]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AB_BFWD_GL_Account]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AB_BFWD_GL_Account]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AB_Get_Ending_GL_Period]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AB_Get_Ending_GL_Period]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AB_SUM_GL_Account_Transactions]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AB_SUM_GL_Account_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Ageing_Grouped_All_Customers]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Ageing_Grouped_All_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Ageing_Non_Grouped]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Ageing_Non_Grouped]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Ageing_Non_Grouped_All_Customers]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Ageing_Non_Grouped_All_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Ageing_Values]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Ageing_Values]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Balance]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Balance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Balance_As_At_Date]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Balance_As_At_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Message]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Message]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Message_Span_Period]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Message_Span_Period]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Outstanding_Transactions]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Outstanding_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Sales]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Unallocated_Journals]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Unallocated_Journals]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Unallocated_Payments]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Unallocated_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Has_Unallocated_Refunds]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Has_Unallocated_Refunds]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Overdue_Amount]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Overdue_Amount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Period_Procedure_Ageing]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Period_Procedure_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Period_Procedure_Ageing_Non_Grouped]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Period_Procedure_Ageing_Non_Grouped]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Period_Procedure_Ageing_Values]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Period_Procedure_Ageing_Values]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Statements_Ageing_Non_Grouped]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Statements_Ageing_Non_Grouped]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Statements_Ageing_Values]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Statements_Ageing_Values]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Statements_Transactions]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Statements_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Total_Ageing]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Total_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Customer_Total_Ageing_No_InterCo]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Customer_Total_Ageing_No_InterCo]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Get_Customer_Rating]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Get_Customer_Rating]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Get_Customer_Status]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Get_Customer_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Get_Last_Payment_Amount]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Get_Last_Payment_Amount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Get_Last_Payment_Date]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Get_Last_Payment_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AC_Get_Last_Sale_Date]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AC_Get_Last_Sale_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AF_Exists_Factory_JobNo]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AF_Exists_Factory_JobNo]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_BFWD_Supplier_Date_Balance]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_BFWD_Supplier_Date_Balance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_BFWD_Supplier_Period_Balance]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_BFWD_Supplier_Period_Balance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Get_Qty_On_Order]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Get_Qty_On_Order]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Product_Has_Orders]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Product_Has_Orders]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_SUM_GL_Supplier_Payment_Amount]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_SUM_GL_Supplier_Payment_Amount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Ageing_Grouped_ALL_Suppliers]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Ageing_Grouped_ALL_Suppliers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Ageing_Non_Grouped]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Ageing_Non_Grouped]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Ageing_Values]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Ageing_Values]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Balance]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Balance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Captured_Ageing_SUM_All]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Captured_Ageing_SUM_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_DocDate_Ageing_SUM_All]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_DocDate_Ageing_SUM_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Has_Outstanding_Transactions]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Has_Outstanding_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Period_Ageing]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Period_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Period_Ageing_All]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Period_Ageing_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Period_Ageing_SUM_All]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Period_Ageing_SUM_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Period_Ageing_Values]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Period_Ageing_Values]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Period_Procedure_Ageing_Non_Grouped]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Period_Procedure_Ageing_Non_Grouped]
GO

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

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Procedure_Ageing_SUM_All]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Procedure_Ageing_SUM_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Procedure_Period_Ageing]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Procedure_Period_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Total_Ageing]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Total_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AO_Supplier_Total_Ageing_No_InterCo]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Total_Ageing_No_InterCo]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_BFWD_Inventory_On_Hand]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_BFWD_Inventory_On_Hand]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_CFWD_Inventory_On_Hand]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_CFWD_Inventory_On_Hand]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Consignment_Stock_Qty]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Consignment_Stock_Qty]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Consignment_Stock_Returned]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Consignment_Stock_Returned]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Consignment_Stock_Sold]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Consignment_Stock_Sold]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Discount_Price]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Discount_Price]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Last_Purchase_Date]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Last_Purchase_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Last_Purchase_Qty]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Last_Purchase_Qty]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Last_Sale_Date]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Last_Sale_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Product_Bin_Job_Reserved]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Product_Bin_Job_Reserved]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Product_Bin_Qty]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Product_Bin_Qty]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Product_Cost]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Product_Cost]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Products_Out_On_Consignment]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Products_Out_On_Consignment]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Sales_Promotion_Price]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Sales_Promotion_Price]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Get_Sales_Promotion_Product_ID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Get_Sales_Promotion_Product_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Product_Has_Movement]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Product_Has_Movement]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Product_Has_Movement_Period]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Product_Has_Movement_Period]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Products_Job_Reserved]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Products_Job_Reserved]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Products_Quoted]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Products_Quoted]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Products_Sales_Order_Reserved]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Products_Sales_Order_Reserved]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_Reserved]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Job_Reserved]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_Reserved_Bin]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Job_Reserved_Bin]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_SO_Reserved_NO_BO]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_NO_BO]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Qty_ADJ]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Qty_ADJ]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Qty_GRV]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Qty_GRV]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_SUM_Product_Qty_SALE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_SUM_Product_Qty_SALE]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Sales_Promotion_Top_20_Perc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Sales_Promotion_Top_20_Perc]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Top100Perc_Products_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Top100Perc_Products_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Top20Perc_Products_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Top20Perc_Products_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AP_Top50Perc_Products_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AP_Top50Perc_Products_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Calc_Act_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Calc_Act_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Calc_Act_Sales_Value]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Calc_Act_Sales_Value]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Calc_Std_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Calc_Std_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Calc_Std_Sales_Value]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Calc_Std_Sales_Value]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Get_Day_Number]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Get_Day_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Get_Hour_Number]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Get_Hour_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Get_MonthYear_Number]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Get_MonthYear_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Get_Month_Number]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Get_Month_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Get_YearMonth_Number]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Get_YearMonth_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Product_Has_Sales]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Product_Has_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Product_Has_Sales_Transactions]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Product_Has_Sales_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top100Perc_Customers_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top100Perc_Customers_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top100Perc_Customers_GP_Extended]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top100Perc_Customers_GP_Extended]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top100Perc_Customers_GP_Mail_Merge]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top100Perc_Customers_GP_Mail_Merge]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top100Perc_Sales_Tran_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top100Perc_Sales_Tran_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top100Perc_Sales_Tran_Value]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top100Perc_Sales_Tran_Value]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top20Perc_Customers_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top20Perc_Customers_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top20Perc_Customers_GP_Extended]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top20Perc_Customers_GP_Extended]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top20Perc_Customers_GP_Mail_Merge]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top20Perc_Customers_GP_Mail_Merge]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top20Perc_Sales_Tran_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top20Perc_Sales_Tran_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top20Perc_Sales_Tran_Value]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top20Perc_Sales_Tran_Value]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top50Perc_Customers_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top50Perc_Customers_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top50Perc_Customers_GP_Extended]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top50Perc_Customers_GP_Extended]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top50Perc_Customers_GP_Mail_Merge]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top50Perc_Customers_GP_Mail_Merge]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top50Perc_Sales_Tran_GP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top50Perc_Sales_Tran_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Top50Perc_Sales_Tran_Value]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Top50Perc_Sales_Tran_Value]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AS_Users_Supervisor_Password_Check]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AS_Users_Supervisor_Password_Check]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AT_Get_Actor]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AT_Get_Actor]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Amount_of_Date_Between]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Amount_of_Date_Between]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Amount_of_Period]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Amount_of_Period]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Amount_of_Period_Between]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Amount_of_Period_Between]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Comment_Single]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Comment_Single]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Comments]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Comments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Exists_Customer_Reference]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Exists_Customer_Reference]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Exists_Product_Code]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Exists_Product_Code]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Exists_SO_Customer_Reference]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Exists_SO_Customer_Reference]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Exists_Supplier_Invoice]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Exists_Supplier_Invoice]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Exists_User_Name]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Exists_User_Name]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Get_Allocation_Status]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Get_Allocation_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Get_YearID_From_Year]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Get_YearID_From_Year]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Get_Year_From_YearID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Get_Year_From_YearID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Months]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Months]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Ping_Remote_DataSource]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Ping_Remote_DataSource]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Split_String_To_Words]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Split_String_To_Words]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_AW_Years]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AW_Years]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_Caption_From_TableName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_Caption_From_TableName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_Customer_Has_Transaction]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_Customer_Has_Transaction]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_GetDate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_GetDate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_Get_Default_Company_ID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_Get_Default_Company_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_ProductDiscountsPerCustomer]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_ProductDiscountsPerCustomer]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_Supplier_Has_Transaction]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_Supplier_Has_Transaction]
GO

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Banking_Payment_Methods_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Banking_Payment_Methods_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Banking_Payments_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Banking_Payments_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Banking_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Banking_Post]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Banking_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Banking_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_CSales_Submission_INS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_CSales_Submission_INS]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_CSales_Submission_INS_SEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_CSales_Submission_INS_SEL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_CSales_Submission_REW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_CSales_Submission_REW]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_CSales_Submission_REW_SEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_CSales_Submission_REW_SEL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Cash_Up]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Cash_Up]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Cash_Up_Cashiers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Cash_Up_Cashiers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Cash_Up_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Cash_Up_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Cash_Up_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Cash_Up_Post]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Cash_Up_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Cash_Up_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Cashup_Up_Lookups_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Cashup_Up_Lookups_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Daily_GRV_VMI]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Daily_GRV_VMI]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Daily_Sales_Loyalty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Daily_Sales_Loyalty]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Daily_Stock_VMI]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Daily_Stock_VMI]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Day_End]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Day_End]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Day_End_Sales_Split_Types]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Day_End_Sales_Split_Types]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Day_End_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Day_End_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Day_End_Summary_Cashier_SEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Day_End_Summary_Cashier_SEL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Day_End_Summary_SEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Day_End_Summary_SEL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Delete_Day_End]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Delete_Day_End]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Delete_Sales_Order_Item]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Delete_Sales_Order_Item]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Delete_Sales_Order_Product]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Delete_Sales_Order_Product]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Document_Deactivate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Document_Deactivate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Drop_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Drop_Enterprise_Customer_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Drop_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Drop_Enterprise_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Drop_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Drop_Enterprise_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Drop_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Drop_Enterprise_Sales_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Edit_Transaction_References_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Edit_Transaction_References_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Enterprise_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Enterprise_Sales_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Enterprise_Sales_Search_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Enterprise_Sales_Search_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Filter_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Filter_Enterprise_Customer_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Filter_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Filter_Enterprise_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Get_Commission_Category]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Get_Commission_Category]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Get_Commission_Category_Per_Group]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Get_Commission_Category_Per_Group]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Get_Group_Per_Commission_Category]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Get_Group_Per_Commission_Category]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Get_Post_Code_Shipping_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Get_Post_Code_Shipping_Rate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Get_Transaction_No_From_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Get_Transaction_No_From_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Commission_Categories_Groups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Commission_Categories_Groups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Discount_Categories_Groups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Discount_Categories_Groups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Enterprise_Customer_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Enterprise_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Enterprise_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Enterprise_Sales_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Markup_Categories_Groups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Markup_Categories_Groups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Sales_Order_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Sales_Order_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Insert_Transaction_Sources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Insert_Transaction_Sources]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Jobcard_Audit_Invoices]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Jobcard_Audit_Invoices]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Jobcard_Audit_Jobcards]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Jobcard_Audit_Jobcards]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Jobcard_Audit_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Jobcard_Audit_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Jobcard_Audit_Transaction_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Jobcard_Audit_Transaction_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Jobcard_Audit_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Jobcard_Audit_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Lookup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Lookup]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Add_BO_To_SO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Add_BO_To_SO]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_CBilling_Detail_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_CBilling_Detail_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Cash_Up]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Cash_Up]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Cashier_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Cashier_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Comments_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Comments_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_CustomerID_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_CustomerID_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_CustomerRef_AssetNo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_CustomerRef_AssetNo]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Customer_Discounts_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Customer_Discounts_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Customer_Insert_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Customer_Insert_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Customer_Transactions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Customer_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Customers_InvDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Customers_InvDel]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Customers_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Customers_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Day_End]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Day_End]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Latest_Transactions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Latest_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Login]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Login]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Lookups_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Lookups_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Open_Jobcards]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Open_Jobcards]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Payment_Methods_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Payment_Methods_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Products_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Products_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_RPT_Invoice_Print]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_RPT_Invoice_Print]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_RPT_Payment_Print]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_RPT_Payment_Print]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_RPT_Sales_Order_Print]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_RPT_Sales_Order_Print]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Report_Transaction_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Report_Transaction_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_Companies_Per_User]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_Companies_Per_User]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_Contract_Prices]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_Contract_Prices]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_CostPlus_Prices]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_CostPlus_Prices]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_IsSupervisor]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_IsSupervisor]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_IsTillPayout]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_IsTillPayout]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_Promotion_Price_Terms]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_Promotion_Price_Terms]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_Tills_Per_User]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_Tills_Per_User]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_User_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_User_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Select_Users]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Select_Users]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_TillPayout_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_TillPayout_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_TillPayout_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_TillPayout_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Detail_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Detail_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Detail_Insert_SO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Detail_Insert_SO]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Details_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Details_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Details_Select_Absolute]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Details_Select_Absolute]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Select_Filtered]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Select_Filtered]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Document_Select_One]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Document_Select_One]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Number_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Number_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Payment_Detail_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Payment_Detail_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Payment_Details_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Payment_Details_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Payment_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Payment_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Transaction_Payment_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Transaction_Payment_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_POS_Update_Delivery_Address]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_POS_Update_Delivery_Address]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Payment_Unallocate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Payment_Unallocate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Reverse_Payment_Component_Count]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Reverse_Payment_Component_Count]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_SO_Products_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_SO_Products_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Sales_Analyst_TranDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Sales_Analyst_TranDetails]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Sales_Analyst_TranHeaders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Sales_Analyst_TranHeaders]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Sales_Order_No_CHK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Sales_Order_No_CHK]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Sales_Order_No_Stock_CHK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Sales_Order_No_Stock_CHK]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Customer_Asset_Hist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Customer_Asset_Hist]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Customer_Sales_Order_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Customer_Sales_Order_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Delivery_Address_Hist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Delivery_Address_Hist]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Email_Marketing_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Email_Marketing_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Email_Marketing_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Email_Marketing_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Email_Marketing_Product_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Email_Marketing_Product_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Email_Marketing_Products]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Email_Marketing_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Email_Marketing_Prospects]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Email_Marketing_Prospects]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_FirstLast_CBilling_Transaction_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_FirstLast_CBilling_Transaction_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_FirstLast_Sale_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_FirstLast_Sale_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_FirstLast_Transaction_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_FirstLast_Transaction_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_IsLevyController]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_IsLevyController]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_IsRecordsManager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_IsRecordsManager]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Mail_Merge_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Mail_Merge_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Mail_Merge_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Mail_Merge_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Mail_Merge_Product_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Mail_Merge_Product_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Mail_Merge_Products]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Mail_Merge_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Mail_Merge_Prospects]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Mail_Merge_Prospects]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Sales_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Sales_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Sales_Order_Back_Orders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Sales_Order_Back_Orders]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Sales_Order_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Sales_Order_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Select_Zero_Cost_Transactions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Select_Zero_Cost_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Account_Balance_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Account_Balance_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Account_Balance_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Account_Balance_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Day_End_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Day_End_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Day_End_Headers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Day_End_Headers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Sales_Order_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Sales_Order_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Sales_Order_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Sales_Order_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Chrono_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Chrono_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Chrono_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Chrono_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_History_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_History_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_History_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_History_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Search_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Search_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Search_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Search_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment2]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Header]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Header]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Shipping_Product_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Shipping_Product_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Detail_Consignment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Detail_Consignment]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Detail_Consignment_Check]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Detail_Consignment_Check]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Detail_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Detail_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Detail_Insert_Cons]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Detail_Insert_Cons]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Detail_Insert_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Detail_Insert_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Details_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Details_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Header_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Header_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Header_Insert_Cons]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Header_Insert_Cons]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Header_Insert_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Header_Insert_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Header_Payment_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Header_Payment_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Headers_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Headers_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Headers_Unallocated_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Headers_Unallocated_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Invoice_Cons]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Invoice_Cons]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Payment_Allocate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Payment_Allocate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Payment_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Payment_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Payment_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Payment_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Payments_IPay_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Payments_IPay_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Payments_IPay_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Payments_IPay_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Payments_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Payments_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Status_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Status_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transaction_Transaction_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transaction_Transaction_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transactions_Address_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transactions_Address_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transactions_Address_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transactions_Address_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transactions_Address_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transactions_Address_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Transactions_Xref]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Transactions_Xref]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Update_Email_Marketing_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Update_Email_Marketing_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Update_Mail_Merge_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Update_Mail_Merge_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Update_Transaction_Activity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Update_Transaction_Activity]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Update_Zero_Cost_Transaction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Update_Zero_Cost_Transaction]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AS_Zero_Sales_Order_Item_Qty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AS_Zero_Sales_Order_Item_Qty]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Delete_Task]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Delete_Task]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Insert_Subject_Specific_Task]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Insert_Subject_Specific_Task]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Insert_Update_Task]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Insert_Update_Task]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Login]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Login]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Select_Lookups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Select_Lookups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Select_Subject_Specific_Tasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Select_Subject_Specific_Tasks]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Select_Task]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Select_Task]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Select_Tasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Select_Tasks]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Select_Tasks_New]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Select_Tasks_New]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AT_Update_Task]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AT_Update_Task]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_8800]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_8800]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9900]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9900]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9910]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9910]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9920]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9920]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9930]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9930]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9940]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9940]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9950]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9950]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9960]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9960]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9970]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9970]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9980]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9980]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9990]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9990]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9991]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9991]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_9992]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_9992]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Check_Accountant_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Check_Accountant_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Check_Product_Bin_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Check_Product_Bin_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Check_Supervisor_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Check_Supervisor_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Check_Till_Supervisor_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Check_Till_Supervisor_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Clear_Site_Manager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Clear_Site_Manager]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Comments_Insert_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Comments_Insert_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Comments_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Comments_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Company_Info]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Company_Info]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Currency_Formula]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Currency_Formula]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Delete_Cashier_Till]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Delete_Cashier_Till]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Delete_Last_Period_Procedure]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Delete_Last_Period_Procedure]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Delete_Marquee_Message]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Delete_Marquee_Message]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Delete_Year_End_Procedure]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Delete_Year_End_Procedure]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Formula]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Formula]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Generic_IF_EXISTS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Generic_IF_EXISTS]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Accounting_Period_From_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Accounting_Period_From_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Company_Email_Address]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Company_Email_Address]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Company_Message_Settings]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Company_Message_Settings]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Company_Name]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Company_Name]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_DBServer_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_DBServer_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Default_CompanyID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Default_CompanyID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Inflections]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Inflections]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Initial_Catalog_Version]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Initial_Catalog_Version]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Inventory_Valuation_Method]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Inventory_Valuation_Method]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Is_DB_WAN_Application_Enabled]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Is_DB_WAN_Application_Enabled]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Last_Day_End_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Last_Day_End_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Last_Period_Procedure_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Last_Period_Procedure_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Last_Period_Procedure_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Last_Period_Procedure_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Last_Period_Procedure_Period]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Last_Period_Procedure_Period]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Last_Period_Procedure_Year_End_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Last_Period_Procedure_Year_End_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Last_Period_Procedure_Year_End_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Last_Period_Procedure_Year_End_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Local_Franchise_Number]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Local_Franchise_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Local_Host_Network_Identifier]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Local_Host_Network_Identifier]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Local_Host_Node_Name]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Local_Host_Node_Name]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Local_Host_Remote_Access_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Local_Host_Remote_Access_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Message]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Message]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Message_Severity_Setting]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Message_Severity_Setting]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Module]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Module]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Motivational_Count]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Motivational_Count]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Motivational_Message]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Motivational_Message]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Next_SCM_File_Number]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Next_SCM_File_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Next_Transaction_Number]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Next_Transaction_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Period_Procedure_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Period_Procedure_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Period_Procedure_Period]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Period_Procedure_Period]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Prev_Period_Procedure_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Prev_Period_Procedure_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Remote_Access_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Remote_Access_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_SP_Account_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_SP_Account_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_SP_Web_Password]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_SP_Web_Password]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_SQL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_SQL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_SQL_Server_Properties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_SQL_Server_Properties]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Single_Value]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Single_Value]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_TakeOnPhase_Setting]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_TakeOnPhase_Setting]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Tax_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Tax_Rate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Tax_Rate_From_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Tax_Rate_From_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Terms_Conditions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Terms_Conditions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Trade_Style]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Trade_Style]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Training_Count]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Training_Count]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Training_Message]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Training_Message]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Transaction_Allocation_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Transaction_Allocation_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_User_Email_Address]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_User_Email_Address]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Get_Value_From_Generic_Table]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Get_Value_From_Generic_Table]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Insert_Apps_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Insert_Apps_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Insert_Or_Update_Terms]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Insert_Or_Update_Terms]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Insert_Remote_Access]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Insert_Remote_Access]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Insert_Site_Manager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Insert_Site_Manager]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Insert_Users_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Insert_Users_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Lookup_Editor_Data_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Lookup_Editor_Data_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Lookup_Editor_Lookups_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Lookup_Editor_Lookups_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Lookup_Table_Names_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Lookup_Table_Names_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Modules_Applications_Per_User_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Modules_Applications_Per_User_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Modules_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Modules_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Month_Ends_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Month_Ends_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Next_Transaction_Number]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Next_Transaction_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Options_Insert_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Options_Insert_Update]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Options_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Options_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Options_Select_W]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Options_Select_W]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Period_Is_Pre_Month_End]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Period_Is_Pre_Month_End]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Period_Procedure_Periods_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Period_Procedure_Periods_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Period_Procedures_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Period_Procedures_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Ping_Remote_DataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Ping_Remote_DataSource]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Put_Next_SCM_File_Number]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Put_Next_SCM_File_Number]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Remove_Apps_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Remove_Apps_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Remove_Users_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Remove_Users_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Reset_GL_Transaction_Activity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Reset_GL_Transaction_Activity]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_SQL_Builder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_SQL_Builder]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Applications_Per_User]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Applications_Per_User]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Apps_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Apps_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Apps_Per_User]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Apps_Per_User]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Companies_Per_User]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Companies_Per_User]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Companies_PickList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Companies_PickList]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Company_Banks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Company_Banks]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Company_Catalog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Company_Catalog]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Company_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Company_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Company_Network_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Company_Network_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Default_Country]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Default_Country]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Email_Manager_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Email_Manager_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Formula_Lookups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Formula_Lookups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Formulas]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Formulas]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Last_7_Period_Procedures]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Last_7_Period_Procedures]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Marquee_Messages]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Marquee_Messages]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Modules_Per_User]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Modules_Per_User]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Month_From_MonthID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Month_From_MonthID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Non_Apps_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Non_Apps_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Non_Users_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Non_Users_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Options_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Options_Log]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Period_Procedure_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Period_Procedure_Date]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Period_Procedure_List]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Period_Procedure_List]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Period_Procedures]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Period_Procedures]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Period_Procedures_Deleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Period_Procedures_Deleted]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Remote_Access]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Remote_Access]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Remote_Access_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Remote_Access_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Remote_Access_PickList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Remote_Access_PickList]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Remote_Sites]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Remote_Sites]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Remote_Sites_IP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Remote_Sites_IP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Reports_Library]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Reports_Library]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Roles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Roles]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Top_Remote_Access_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Top_Remote_Access_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Top_User_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Top_User_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Training_Messages]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Training_Messages]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Accountant_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Accountant_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_CRM_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_CRM_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Catalog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Catalog]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Catalog_PickList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Catalog_PickList]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Controller_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Controller_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_DBAdmin_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_DBAdmin_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_DataExport_Status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_DataExport_Status]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Default_Bin]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Default_Bin]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Lups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Lups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Rights]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Rights]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_User_Roles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_User_Roles]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Users]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Users]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Users_Per_Role]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Users_Per_Role]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Users_W]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Users_W]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_YearID_From_Year]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_YearID_From_Year]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Year_End_Procedure_List]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Year_End_Procedure_List]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Select_Year_From_YearID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Select_Year_From_YearID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Set_SP_Account_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Set_SP_Account_ID]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Set_SP_Web_Password]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Set_SP_Web_Password]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_TableIsFullTextEnabled]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_TableIsFullTextEnabled]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_TableRowsCount_Cursor]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_TableRowsCount_Cursor]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Tills_Per_User_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Tills_Per_User_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Transaction_Detail_Described]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Transaction_Detail_Described]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Transaction_Header_Described]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Transaction_Header_Described]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Transaction_Numbers_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Transaction_Numbers_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_Transaction_Types_Select]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_Transaction_Types_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_AW_User_Companies_Subset]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_AW_User_Companies_Subset]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_Current_AS_Transaction_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_Current_AS_Transaction_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_Current_AS_Transaction_Headers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_Current_AS_Transaction_Headers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_Current_AS_Transaction_Headers_SUM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_Current_AS_Transaction_Headers_SUM]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_POS_Login]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_POS_Login]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_POS_Select_Login_Tills]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_POS_Select_Login_Tills]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_POS_Select_Login_Users]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_POS_Select_Login_Users]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Annual_Budget]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Annual_Budget]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Balance_Sheet]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Balance_Sheet_Comparative]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Balance_Sheet_Comparative]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Bank_Recon]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Bank_Recon]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Chart_Of_Accounts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Chart_Of_Accounts]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Enterprise_Balance_Sheet]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Enterprise_Income_Statement]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Enterprise_Management_Accounts]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Enterprise_Trial_Balance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_GL_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_GL_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_GL_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_GL_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_GL_Listing_BFWD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_GL_Listing_BFWD]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_GL_TranType_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_GL_TranType_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_GL_Transactions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_GL_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_General_Journal_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_General_Journal_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_General_Journals]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_General_Journals]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_General_Journals_Report]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_General_Journals_Report]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Income_Statement]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Income_Statement]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Income_Statement_Comparative]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Income_Statement_Comparative]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Man_Acc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Man_Acc]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Man_Acc_Control]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Man_Acc_Control]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Management_Account_Groups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Management_Account_Groups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Management_Accounts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Management_Accounts]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Recurring_Journals]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Recurring_Journals]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Trial_Balance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Trial_Balance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_Trial_Balance_Movement]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_Trial_Balance_Movement]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AB_VAT_Report]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AB_VAT_Report]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Contract_Pricing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Contract_Pricing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Age_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Age_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Age_Analysis_Filter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Age_Analysis_Filter]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Age_Analysis_Rep]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Age_Analysis_Rep]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Ageing_Temp]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Bin_Exceptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Bin_Exceptions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Cash_Terms_Exceeded]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Cash_Terms_Exceeded]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Consignment_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Consignment_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Credit_Limit_Exceeded]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Credit_Limit_Exceeded]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Credit_Terms_Exceeded]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Credit_Terms_Exceeded]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_History]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_History]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_History_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_History_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Journals_GL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Journals_GL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Journals_GL_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Journals_GL_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Labels]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Labels]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Ledger]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Ledger]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Listing2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Listing2]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Lists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Lists]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Partly_Allocated_Payments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Partly_Allocated_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Payment_Allocations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Payment_Allocations]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Payments_Received]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Payments_Received]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Performance_Stats]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Performance_Stats]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Statement_Allocations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Statement_Allocations]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Statement_Payments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Statement_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Statements]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Statements]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Statements_Email]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Statements_Email]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Statements_Temp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Statements_Temp]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Customer_Transaction_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Customer_Transaction_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Enterprise_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Enterprise_Customer_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Inactive_Customers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Inactive_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Nedbank_Invoice_Discounting]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Nedbank_Invoice_Discounting]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Payment_Allocations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Payment_Allocations]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Prospect_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Prospect_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Sales_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Sales_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_TopCustomer_Pareto]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_TopCustomer_Pareto]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_TranType_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_TranType_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Transactions_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Transactions_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AC_Unallocated_Payments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AC_Unallocated_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AF_Casing_Credit_Inventory_GL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AF_Casing_Credit_Inventory_GL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AF_Casing_Stock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AF_Casing_Stock]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AF_Casing_vs_Stock_Product]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AF_Casing_vs_Stock_Product]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AF_Outstanding_Jobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AF_Outstanding_Jobs]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AF_Uninvoiced_Jobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AF_Uninvoiced_Jobs]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AF_Unused_Job_Tickets]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AF_Unused_Job_Tickets]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Account_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Account_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Age_Analysis_Historical]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Age_Analysis_Historical]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Consignment_Journal_CR1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Consignment_Journal_CR1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Supplier]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Supplier]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Consignment_Journal_CR1_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Consignment_Journal_CR1_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Consignment_Journal_CR3]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Consignment_Journal_CR3]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Department_Purchases]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Department_Purchases]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Enterprise_Supplier_Ageing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Enterprise_Supplier_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Outstanding_Orders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Outstanding_Orders]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Procurement_Manager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Procurement_Manager]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Product_Purchase_Price_Variance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Product_Purchase_Price_Variance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Product_Purchases]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Product_Purchases]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Product_Suppliers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Product_Suppliers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR1_GRV]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR1_GRV]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Supplier]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Supplier]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR1_Splits]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR1_Splits]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR1_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR1_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_CR3]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_CR3]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_Non_GRV]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_Non_GRV]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_Non_GRV_Splits]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_Non_GRV_Splits]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Purchases_Journal_Non_GRV_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Purchases_Journal_Non_GRV_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Remittance_Ageing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Remittance_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Remittance_Transactions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Remittance_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Accounts_Temp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Accounts_Temp]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Age_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Age_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Journals_GL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Journals_GL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Journals_GL_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Journals_GL_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Ledger]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Ledger]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Payments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Payments_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Payments_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Payments_GL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Payments_GL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Payments_GL_Control_Amount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Payments_GL_Control_Amount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Products]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Purchases_Journal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Purchases_Journal]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Purchases_Journal_CR1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Purchases_Journal_CR1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Purchases_Temp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Purchases_Temp]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Remittance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Remittance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Remittance_Summary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Remittance_Summary]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Supplier_Remittances_Temp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Supplier_Remittances_Temp]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AO_Transactions_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AO_Transactions_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Barcode_Labels]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Barcode_Labels]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Barcode_Labels_Print]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Barcode_Labels_Print]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Bin_Allocation_History]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Bin_Allocation_History]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Cardex_Print]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Cardex_Print]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Consignment_Valuation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Consignment_Valuation]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Disabled_Products]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Disabled_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Slow_Moving_Stock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Slow_Moving_Stock]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Stock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Stock]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Stock_Filter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Stock_Filter]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Stock_MSL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Stock_MSL]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Stock_Replenish]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Stock_Replenish]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Stock_Replenish_Max]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Stock_Replenish_Max]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Enterprise_Stock_Valuation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Enterprise_Stock_Valuation]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Gross_Profit_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Gross_Profit_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Adjustments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Adjustments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Replenish]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Replenish]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Replenish_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Replenish_Analysis2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis2]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Stock_Take]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Stock_Take]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Stock_Take_Filtered]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Stock_Take_Filtered]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Valuation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Valuation]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Inventory_Valuation_Movement]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Inventory_Valuation_Movement]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Levy_Inventory_Valuation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Levy_Inventory_Valuation]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Nursery_Labels]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Nursery_Labels]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Order_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Order_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Product_Consignment_Customer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Product_Consignment_Customer]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Product_Price_List]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Product_Price_List]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Product_Price_List_VAT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Product_Price_List_VAT]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Sales_Promotions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Sales_Promotions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Slow_Moving_Inventory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Slow_Moving_Inventory]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Stock_Bins]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Stock_Bins]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Stock_Reconcilliation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Stock_Reconcilliation]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Surplus_Inventory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Surplus_Inventory]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Topseller_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Topseller_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AP_Topseller_Pareto]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AP_Topseller_Pareto]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_100Perc_GP_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_100Perc_GP_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_CBilling_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_CBilling_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_CashUp_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_CashUp_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_CashUp_Cashiers_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_CashUp_Cashiers_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Customer_Sales_Filter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Customer_Sales_Filter]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Cashier_Jobcards]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Cashier_Jobcards]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Cashier_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Cashier_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Customer_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Customer_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Customer_Type_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Customer_Type_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Export_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Export_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Floor_Rep_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Floor_Rep_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Performance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Performance]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Product_Sales_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Product_Sales_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Rep_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Rep_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_DayEnd_Zero_VAT_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_DayEnd_Zero_VAT_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Day_End]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Day_End]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Day_End_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Day_End_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Day_End_Till_Payouts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Day_End_Till_Payouts]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Enterprise_Customer_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Enterprise_GP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Enterprise_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Enterprise_Sales_All]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_GP_Audit_Trail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_GP_Audit_Trail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Low_Profit_Sales]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Low_Profit_Sales]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Open_Jobcard_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Open_Jobcard_Detail]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Open_Jobcards]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Open_Jobcards]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Rep_Sales_Filter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Rep_Sales_Filter]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Analysis]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Analysis_Month]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Analysis_Month]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Analysis_Year]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Analysis_Year]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Products]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Profit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Profit]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Profit_Products]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Profit_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Promotions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Promotions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Transaction_Listing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Transaction_Listing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Sales_Transaction_Listing_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Sales_Transaction_Listing_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transaction_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transaction_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transaction_Headers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transaction_Headers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transaction_Headers_Cash_Up]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transaction_Headers_Cash_Up]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transaction_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transaction_Payments_Cash_Up]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transaction_Payments_Cash_Up]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transactions_XREF]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transactions_XREF]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Transactions_Xref_Sources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Transactions_Xref_Sources]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_AS_Uninvoiced_Jobcards]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_AS_Uninvoiced_Jobcards]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_RPT_Customer_Delivery_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_RPT_Customer_Delivery_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_Sys_AC_Status_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_Sys_AC_Status_Get]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_Sys_AC_Status_Insert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_Sys_AC_Status_Insert]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_Sys_AC_Status_Mark]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_Sys_AC_Status_Mark]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AP_Product_Links]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AP_Product_Links]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_POS_Products]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_POS_Products]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_POS_Products_Gross_Contribution]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_POS_Products_Gross_Contribution]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_POS_Products_Top_20_Perc]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_POS_Products_Top_20_Perc]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AB_Cash_Book_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AS_Transactions_Transaction_Details]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AS_Transactions_Transaction_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_GL_Accounts]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_GL_Accounts]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AC_Suppliers]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AC_Suppliers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AO_Transactions]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AO_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AP_Stock_Month_End]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AP_Stock_Month_End]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AST]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AST]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_POS_Customers_Select]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_POS_Customers_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_POS_Transaction_Headers_Select]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_POS_Transaction_Headers_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_POS_Transaction_Headers_Select_Absolute]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_POS_Transaction_Headers_Select_Absolute]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Payments_Select]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Payments_Select]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transaction_Details]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transaction_Details]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transaction_Details_Full]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transaction_Details_Full]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transaction_Headers]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transaction_Headers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transaction_Payment_Allocations]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transaction_Payment_Allocations]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transaction_Payments]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transactions]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transactions]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Transactions_View]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Transactions_View]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Users_Roles]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Users_Roles]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AW_Transaction_Detail_Described]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AW_Transaction_Detail_Described]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AW_Transaction_Header_Described]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AW_Transaction_Header_Described]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AO_Supplier_List]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AO_Supplier_List]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AS_Sales_Analyst]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AS_Sales_Analyst]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AS_Transaction_Headers]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AS_Transaction_Headers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_Customer_Statements]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_Customer_Statements]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AC_Customers]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AC_Customers]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_ASTD]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_ASTD]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Banks_Cards_Union]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Banks_Cards_Union]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AS_Cash_Ups_Active]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AS_Cash_Ups_Active]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AT_Tasks]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AT_Tasks]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_AW_Banks_Cards_Union]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_AW_Banks_Cards_Union]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AC_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AC_Customer_Ageing]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AC_Customer_List]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AC_Customer_List]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_RPT_AC_Customer_Statements]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_RPT_AC_Customer_Statements]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[vw_SYS_AT_Filters]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_SYS_AT_Filters]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE FUNCTION GetActor (@ActorID int)
RETURNS varchar(50)
AS
BEGIN
	DECLARE @ActorName varchar(50)
	IF @ActorID > 0 
		SET @ActorName = (SELECT firstname + ' ' + Surname as actor
		FROM AW_Users
		WHERE AW_Users_ID = @ActorID)
	
	ELSE
	IF @ActorID <= 0
		SET @ActorName = (SELECT [Description] as Actor 
		FROM Sys_AT_Actor_Types
		WHERE Sys_AT_Actor_Types_ID = @ActorID)
	
	RETURN (@ActorName)
		
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.GetActualMargin
--Functionality :Calculates ACTUAL MARGIN % for one Product using DISCOUNT %
--Parameters    :
--Date          :2007/12/01
--Authors       :TB
--Mods          :
--2004.3.8      :08/04/08 - Modified final (@Return) GP% based on NETT SELLING price
--              :           (@Price - @DiscPerc) instead of Retail (@Price) - TV
-------------------------------------------------------------------------------

CREATE        FUNCTION dbo.GetActualMargin
	(
		@Price1Effective datetime,
    	@Price1 float,
    	@Price2Effective datetime,
    	@Price2 float,
    	@Date DateTime,    
    	@Cost float,
        @DiscPerc float
	)

RETURNS float

AS

    BEGIN
    
        DECLARE @Price float,
                @Discount float,
                @Return float
    
    
        IF @Price1Effective is null
            SET @Price1Effective = '1900/01/01'
        
        IF @Price2Effective is null
            SET @Price2Effective = '1900/01/01'
        
        IF @Price1 is null
            SET @Price1 = 0.0
        
        IF @Price2 is null
            SET @Price2 = 0.0
        
        IF @Cost is null
            SET @Cost = 0.0
        
        IF @Date is null
            SET @Date = '2500/01/01'
    
    
        IF DATEDIFF(d, @Price1Effective, @Date) >= 0 AND DATEDIFF(d, @Price2Effective, @Date) < 0
            BEGIN
                SET @Price = @Price1
            END
        ELSE
        IF DATEDIFF(d, @Price2Effective, @Date) >= 0 AND DATEDIFF(d, @Price1Effective, @Date) < 0
            BEGIN
                SET @Price = @Price2
            END
        ELSE
        IF DATEDIFF(d, @Price1Effective,  @Date) < 0 AND DATEDIFF(d, @Price2Effective,  @Date) < 0
            BEGIN
                IF @Price1 > 0 AND @Price1 > @Price2
                    SET @Price = @Price1
                ELSE
                IF @Price2 > 0
                    SET @Price = @Price2
                ELSE
                    SET @Price = 0 
            END
        ELSE 
        IF DATEDIFF(d,@Price1Effective, @Date) > 0 AND DATEDIFF(d,@Price2Effective, @Date) > 0
            BEGIN
                IF DATEDIFF(d,@Price1Effective,  @Price2Effective) >= 0 
                    SET @Price = @Price2
                ELSE
                    SET @Price = @Price1
            END
       
    
        SET @Discount = ROUND(@Price * (@DiscPerc / 100), 2)
    
    
        IF @Price = 0
            SET @Return =  0.00
        ELSE
            SET @Return = ROUND(((((@Price - @Discount) - @Cost) / (@Price - @Discount)) * 100), 2)
        RETURN @Return
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.GetCostPlusMargin
--Functionality :Calculates GROSS PROFIT % from Cost+Plus markup for one Product
--Parameters    :
--Date          :2007/07/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.GetCostPlusMargin
	(
    	@Cost float,
        @MarkupPerc float
	)

RETURNS float

AS

    BEGIN
        DECLARE @Price float,
               @Return float
        
        IF @Cost IS NULL
          SET @Cost = 0.0
        
        IF @MarkupPerc IS NULL
          SET @MarkupPerc = 0.0
        
        SET @Price = @Cost + ROUND(@Cost * (@MarkupPerc / 100), 2)

        IF @Price <> 0
            SET @Return = ROUND((((@Price - @Cost) / @Price) * 100), 2)
        ELSE
            SET @Return = 0 
        
        RETURN @Return
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.GetEffectiveDate
--Functionality :Returns CURRENT EFFECTIVE DATE for one Product
--Date          :2004/07/22
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.GetEffectiveDate
    (
        @Price1Effective datetime,
        @Price2Effective datetime,
        @SelectedDate DateTime
    )

RETURNS datetime

AS

    BEGIN
    
        DECLARE @CurrentDate datetime
        
        IF @Price1Effective is NULL
            SET @Price1Effective = '1900/01/01'
        
        IF @Price2Effective is NULL
            SET @Price2Effective = '1900/01/01'
        
        IF @SelectedDate is NULL
            SET @SelectedDate = '2500/01/01'
        
        
        IF DATEDIFF(d, @Price1Effective,  @SelectedDate) >= 0 AND DATEDIFF(d, @Price2Effective,  @SelectedDate) < 0
            BEGIN
                SET @CurrentDate= @Price1Effective
            END
        
        ELSE
        IF DATEDIFF(d, @Price2Effective,  @SelectedDate) >= 0 AND DATEDIFF(d, @Price1Effective,  @SelectedDate) < 0
            BEGIN
                SET @CurrentDate= @Price2Effective
            END
        
        ELSE
        IF DATEDIFF(d, @Price1Effective,  @SelectedDate) < 0 AND DATEDIFF(d, @Price2Effective,  @SelectedDate) < 0
            SET @CurrentDate= @Price1Effective
        
        ELSE
        IF DATEDIFF(d, @Price1Effective,  @SelectedDate) >= 0 AND DATEDIFF(d, @Price2Effective,  @SelectedDate) >= 0
            BEGIN
                IF DATEDIFF(d,@Price1Effective,  @Price2Effective) >= 0 
                    SET @CurrentDate= @Price2Effective
            ELSE
                SET @CurrentDate= @Price1Effective
            END



        RETURN @CurrentDate
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.GetEffectivePrice
--Functionality :Return CURRENT SELLING PRICE for one Product
--Parameters    :
--Date          :2002/02/10
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE            FUNCTION dbo.GetEffectivePrice
    (
        @Price1Effective datetime,
        @Price1 money,
        @Price2Effective datetime,
        @Price2 money,
        @Date DateTime
    )

RETURNS money

AS

BEGIN

   DECLARE @Price money, @Return money

   IF @Price1Effective is null
      SET @Price1Effective = '1900/01/01'

   IF @Price2Effective is null
      SET @Price2Effective = '1900/01/01'

   IF @Price1 is null
      SET @Price1 = 0

   IF @Price2 is null
      SET @Price2 = 0

   IF @Date is null
      SET @Date = '2500/01/01'


   IF DateDiff(d,@Price1Effective,  @Date) >= 0 AND DateDiff(d,@Price2Effective,  @Date) < 0
      BEGIN
         SET @Price = @Price1
      END
   ELSE
   IF DateDiff(d,@Price2Effective,  @Date) >= 0 AND DateDiff(d,@Price1Effective,  @Date) < 0
      BEGIN
         SET @Price = @Price2
      END
   ELSE
   IF DateDiff(d,@Price1Effective,  @Date) < 0 AND DateDiff(d,@Price2Effective,  @Date) < 0
      BEGIN
         IF @Price1 > 0 AND @Price1 > @Price2
            SET @Price = @Price1
         ELSE
         IF @Price2 > 0
            SET @Price = @Price2
         ELSE
            SET @Price = 0 
      END
   ELSE 
   IF DateDiff(d,@Price1Effective,  @Date) >= 0 AND DateDiff(d,@Price2Effective,  @Date) >= 0
      BEGIN
         IF DateDiff(d,@Price1Effective,  @Price2Effective) >= 0 
            SET @Price = @Price2
         ELSE
            SET @Price = @Price1
      END

   RETURN @Price
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.GetGrossContribution
--Functionality :NEW - Calculates GROSS PROFIT AMOUNT for one Product
--Parameters    :
--Date          :2002/07/28
--Authors       :TB
--Version       :1.0.0
--Mods          :2002/04/28 - Replaced return value decimal(7,2) with float
--              :             due to OVERFLOW error
-------------------------------------------------------------------------------

CREATE       FUNCTION dbo.GetGrossContribution
	(
		@Price1Effective datetime,
    	@Price1 float,
    	@Price2Effective datetime,
    	@Price2 float,
    	@Date DateTime,    
    	@LastCost float
	)

RETURNS float        --decimal(7,2)

AS

BEGIN

   DECLARE @Price float, @Return float

   IF @Price1Effective is null
      SET @Price1Effective = '1900/01/01'

   IF @Price2Effective is null
      SET @Price2Effective = '1900/01/01'

   IF @Price1 is null
      SET @Price1 = 0.0

   IF @Price2 is null
      SET @Price2 = 0.0

   IF @LastCost is null
      SET @LastCost = 0.0

   IF @Date is null
      SET @Date = '2500/01/01'

   IF DATEDIFF(d, @Price1Effective, @Date) >= 0 AND DATEDIFF(d, @Price2Effective, @Date) < 0
      BEGIN
         SET @Price = @Price1
      END
   ELSE
   IF DATEDIFF(d, @Price2Effective, @Date) >= 0 AND DATEDIFF(d, @Price1Effective, @Date) < 0
      BEGIN
         SET @Price = @Price2
      END
   ELSE
   IF DATEDIFF(d, @Price1Effective,  @Date) < 0 AND DATEDIFF(d, @Price2Effective,  @Date) < 0
      BEGIN
         IF @Price1 > 0 AND @Price1 > @Price2
            SET @Price = @Price1
         ELSE
         IF @Price2 > 0
            SET @Price = @Price2
         ELSE
            SET @Price = 0 
      END
   ELSE 
   IF DATEDIFF(d,@Price1Effective, @Date) > 0 AND DATEDIFF(d,@Price2Effective, @Date) > 0
      BEGIN
         IF DATEDIFF(d,@Price1Effective,  @Price2Effective) >= 0 
            SET @Price = @Price2
         ELSE
            SET @Price = @Price1
      END
   

   IF @Price = 0
      SET @Return =  0.00
   ELSE
      SET @Return = ROUND((@Price - @LastCost), 2)
   RETURN @Return
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.GetGrossMargin
--Functionality :Calculates GROSS MARGIN % for one Product
--Parameters    :
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
--Mods          :2002/04/28 - Replaced return value decimal(7,2) with float
--              :             due to OVERFLOW error
-------------------------------------------------------------------------------

CREATE      FUNCTION dbo.GetGrossMargin
	(
		@Price1Effective datetime,
    	@Price1 float,
    	@Price2Effective datetime,
    	@Price2 float,
    	@Date DateTime,    
    	@LastCost float
	)

RETURNS float        --decimal(7,2)

AS

BEGIN

   DECLARE @Price float, @Return float

   IF @Price1Effective is null
      SET @Price1Effective = '1900/01/01'

   IF @Price2Effective is null
      SET @Price2Effective = '1900/01/01'

   IF @Price1 is null
      SET @Price1 = 0.0

   IF @Price2 is null
      SET @Price2 = 0.0

   IF @LastCost is null
      SET @LastCost = 0.0

   IF @Date is null
      SET @Date = '2500/01/01'

   IF DATEDIFF(d, @Price1Effective, @Date) >= 0 AND DATEDIFF(d, @Price2Effective, @Date) < 0
      BEGIN
         SET @Price = @Price1
      END
   ELSE
   IF DATEDIFF(d, @Price2Effective, @Date) >= 0 AND DATEDIFF(d, @Price1Effective, @Date) < 0
      BEGIN
         SET @Price = @Price2
      END
   ELSE
   IF DATEDIFF(d, @Price1Effective,  @Date) < 0 AND DATEDIFF(d, @Price2Effective,  @Date) < 0
      BEGIN
         IF @Price1 > 0 AND @Price1 > @Price2
            SET @Price = @Price1
         ELSE
         IF @Price2 > 0
            SET @Price = @Price2
         ELSE
            SET @Price = 0 
      END
   ELSE 
   IF DATEDIFF(d,@Price1Effective, @Date) > 0 AND DATEDIFF(d,@Price2Effective, @Date) > 0
      BEGIN
         IF DATEDIFF(d,@Price1Effective,  @Price2Effective) >= 0 
            SET @Price = @Price2
         ELSE
            SET @Price = @Price1
      END
   

   IF @Price = 0
      SET @Return =  0.00
   ELSE
      SET @Return = ROUND((((@Price - @LastCost) / @Price) * 100), 2)
   RETURN @Return
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AB_Account_Is_Sub_Control
--Purpose       :Returns SCALAR bit if GL Account is a Subsidiary Ledger Control
--Date          :2005/05/23
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AB_Account_Is_Sub_Control
	(
		@GLAccountID int
	)

RETURNS bit

AS
	BEGIN
    	DECLARE @Test bit
    
    	IF EXISTS
                (
                    SELECT TOP 1 @GLAccountID
                    FROM AB_Control_Accounts
                    WHERE AB_Accounts_ID = @GLAccountID AND
                          Control_Type = 1
                )
            SET @Test = 1
    	ELSE	
    		SET @Test = 0
    
    	RETURN @Test
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AB_BFWD_GL_Account
--Purpose       :Retrieves GL Account Opening Balance BEFORE a date
--Parameters    :
--Date          :2004/11/08
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AB_BFWD_GL_Account
    (
        @GLAccountID int,
        @OpeningPeriod varchar(6)
    )

RETURNS float

AS

    BEGIN

        DECLARE @BFWD float


        SELECT @BFWD = ISNULL(SUM(AB_Transaction_Amount), 0)
        FROM AB_GL_Transactions
        WHERE AB_Accounts_ID = @GLAccountID AND
              dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @OpeningPeriod


        RETURN(@BFWD)

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AB_Get_Ending_GL_Period
--Purpose       :Returns YEAR(4) and MONTH(2) as 6-digit integer
--Used in       :to ORDER GL transactions in Accounting Periods
--Parameters    :
--Date          :31 DEC 2002
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE        FUNCTION dbo.fn_AB_Get_Ending_GL_Period
    (
        @MonthID tinyint,
        @YearID int
    )

RETURNS varchar(6)

AS

BEGIN

    DECLARE @Monthstr varchar(2),
            @Yearstr varchar(4),
            @PeriodNo varchar(6)

    SET @Yearstr = RTRIM(LTRIM(CONVERT(varchar(4), @YearID)))
    SET @Monthstr = RTRIM(LTRIM(CONVERT(varchar(2), @MonthID)))

    IF LEN(@Yearstr) = 1
        set @Yearstr = '000' + @Yearstr
    ELSE
    IF LEN(@Yearstr) = 2
        set @Yearstr = '00' + @Yearstr
    ELSE
    IF LEN(@Yearstr) = 3
        set @Yearstr = '0' + @Yearstr

    IF LEN(@Monthstr) = 1
        set @Monthstr = '0' + @Monthstr

    SET @PeriodNo = @Yearstr + @Monthstr


    RETURN(@PeriodNo)

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AB_SUM_GL_Account_Transactions
--Purpose       :SUM GL Transaction Total for one GL Account
--Date          :2010/07/15
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE                   FUNCTION dbo.fn_AB_SUM_GL_Account_Transactions
    (
    	@GLAccountID int,
        @CompanyID int
    )

RETURNS money

AS

    BEGIN

        DECLARE @TranTotal money

        SELECT @TranTotal = ROUND(ISNULL(SUM(AB_Transaction_Amount), 0), 2)
        FROM AB_GL_Transactions
        WHERE AW_User_Companies_ID = @CompanyID AND
              AB_Accounts_ID = @GLAccountID


        RETURN @TranTotal

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION fn_AC_Customer_Ageing_Grouped_All_Customers
    (
        @D0 DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
	(
        CustomerID int,
        Amount money,
        Payment money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money
    )

AS

BEGIN

	INSERT @AgeTable
	SELECT    
		AC_Customers_ID as CustomerID,
		SUM(Total_Amount) as Amount, 
		SUM(Payment_Amount) as Payment, 
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D1, @D0,(Total_Amount + Payment_Amount))) as [Current],
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D2, @D1,0)) as [30 Days],
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D3, @D2,0)) as [60 Days],
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D4, @D3,0)) as [90 Days],
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D5, @D4,0)) as [120 Days],
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D6, @D5,0)) as [150 Days],
		SUM(dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D7, @D6,0)) as [180+ Days]
	FROM AS_Transactions 
	WHERE (Sys_AW_Transaction_Types_ID = 3 OR      --Invoice
           Sys_AW_Transaction_Types_ID = 4 OR      --Refund
           Sys_AW_Transaction_Types_ID = 5 OR      --Journal
           Sys_AW_Transaction_Types_ID = 7 OR      --Payment
           Sys_AW_Transaction_Types_ID = 15 OR     --Interest Journal
           Sys_AW_Transaction_Types_ID = 18) AND   --Settlement Discount
          (Total_Amount + Payment_Amount <> 0)
	GROUP BY AC_Customers_ID

RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Ageing_Non_Grouped
--Purpose       :Retrieves Customer Ageing Amounts between each Age Area date
--NOTE          :ANY MOD ALSO TO BE INSERTED IN fn_AO_Supplier_Ageing_Non_Grouped
--Date          :2002/01/21
--Authors       :TB
--Version       :1.0.0
--MODS          :28/05/02 - Added [User] to Choice 1 for display in
--              :           Customer Catalog Unallocated Ageing Transactions
--              :24/07/02 - Added Sys_AW_Transaction_Types_ID 21 & 22
--              :09/08/02 - CONVERT datetime value of Transaction_Date to INT not
--              :           matching when full DATETIME 'YYYY/MM/DD HH:MM:SS' is
--              :           compared to 'YYYY/MM/DD' in fn_AW_Amount_of_Date_Between
--              :18/09/02 - Added ISNULL validation to all amounts
--              :!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
--              :18/09/02 - !!!! REMOVED MODS OF 09/08/02 causing Journal amounts
--              :           not to be included in the Account and Ageing balances
--              :           immediately after posting at Protea !!!!!!!!!!!!!!!
--              :           THIS NEEDS TO BE RE-VISITED to fix the reason for the ORIG mod
--              :!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
--              :30/10/02 - Modified AW_Users join to LEFT from INNER
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AC_Customer_Ageing_Non_Grouped
    (
        @CustomerID int, 
        @D0 DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
    (
        [ID] int, 
        CustomerID int,
        [Date] datetime,
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money,
        [User] varchar(20)
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		AS_Transactions_ID as [ID], 
    		@CustomerID as CustomerID,
    		Transaction_Date,
    		Payment_Amount as Payment, 
    		Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D1,
                     @D0,
                    (Total_Amount + Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D7,                     @D6,
                     0
                ) as [180+ Days],
            AW_Users.UserName AS [User]
    	FROM AS_Transactions
            LEFT JOIN AW_Users
                ON AS_Transactions.[User_ID] = AW_Users.AW_Users_ID
    	WHERE AC_Customers_ID = @CustomerID AND
             (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
              Sys_AW_Transaction_Types_ID = 4 OR        --Refund
              Sys_AW_Transaction_Types_ID = 5 OR        --Journal
              Sys_AW_Transaction_Types_ID = 7 OR        --Payment
              Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
              Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
              Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
              Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
              ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
             DATEDIFF(d, @D0, Transaction_Date) <= 0

    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE   FUNCTION fn_AC_Customer_Ageing_Non_Grouped_All_Customers
    (
        @D0 DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime,
        @CompanyID int
    )

RETURNS @AgeTable TABLE 
	(
        CustomerID int,
        Customer varchar(100),
        Amount money,
        Payment money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money
    )

AS

    BEGIN
    
    	INSERT @AgeTable
    	SELECT    
    		t.AC_Customers_ID AS CustomerID,
    		ISNULL(c.Surname,'') + ISNULL(', ' + c.Firstnames,'') AS Customer,
    		t.Total_Amount AS Amount, 
    		t.Payment_Amount AS Payment, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D1,
                    @D0,
                   (t.Total_Amount + t.Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D2,
                    @D1,
                    0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D3,
                    @D2,
                    0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D4,
                    @D3,
                    0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D5,
                    @D4,0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D6,
                    @D5,0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                   (t.Total_Amount + t.Payment_Amount),
                    t.Transaction_Date,
                    @D7,
                    @D6,0
                ) as [180+ Days]
    	FROM AS_Transactions t
                LEFT JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
    	WHERE (t.Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
               t.Sys_AW_Transaction_Types_ID = 4 OR        --Refund
               t.Sys_AW_Transaction_Types_ID = 5 OR        --Journal
               t.Sys_AW_Transaction_Types_ID = 7 OR        --Payment
               t.Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
               t.Sys_AW_Transaction_Types_ID = 18) AND     --Settlement Discount
              (t.Total_Amount + t.Payment_Amount <> 0) AND
              (t.AW_User_Companies_ID = @CompanyID)
    
    RETURN
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Ageing_Values
--Purpose       :Retrieves Customer Ageing Amounts between each Age Area date
--Parameters    :
--Date          :2002/01/21
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE     FUNCTION fn_AC_Customer_Ageing_Values
    (
        @CustomerID int, 
        @D0 datetime, 
        @D1 datetime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

RETURNS @AgeTable TABLE 
    (
    	CustomerID 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 datetime,
        Days60Date datetime,
        Days90Date datetime,
        Days120Date datetime,
        Days150Date datetime,
        Days180Date datetime
    )

AS

    BEGIN
    
        INSERT @AgeTable
        SELECT CustomerID,
            sum([Payment]) AS [Payment],
            sum([Amount]) AS [Amount],        
            sum([Current]) AS [Current],
            sum([30 Days]) AS [30 Days],
            sum([60 Days]) AS [60 Days],
            sum([90 Days]) AS [90 Days],
            sum([120 Days]) AS [120 Days], 
            sum([150 Days]) AS [150 Days],
            sum([180+ Days]) AS [180+ Days],
            @D0 AS CurrentDate,
            @D1 AS Days30Date,
            @D2 AS Days60Date,
            @D3 AS Days90Date,
            @D4 AS Days120Date,
            @D5 AS Days150Date,
            @D6 AS Days180Date
        FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
            (
                @CustomerID,
                @D0,
                @D1,
                @D2,
                @D3,
                @D4,
                @D5,
                @D6,
                @D7
            )
        GROUP BY CustomerID
    
    RETURN
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AC_Customer_Balance
--Purpose       :Retrieves ONE Customer's Account Balance
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AC_Customer_Balance
    (
        @CustomerID int
    )

RETURNS money

AS

BEGIN

    DECLARE @Balance money

    SET @Balance = 0

    SELECT @Balance =  ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
    FROM AS_Transactions
    WHERE AC_Customers_ID = @CustomerID AND
          ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
         (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
          Sys_AW_Transaction_Types_ID = 4 OR   --Refund
          Sys_AW_Transaction_Types_ID = 5 OR   --Journal
          Sys_AW_Transaction_Types_ID = 7 OR   --Payment
          Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
          Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
          Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
          Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

    RETURN(@Balance)

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AC_Customer_Balance_As_At_Date
--Purpose       :Retrieves ONE Customer's Account Balance
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AC_Customer_Balance_As_At_Date
    (
        @CustomerID int,
        @Date datetime
    )

RETURNS money

AS

BEGIN

    DECLARE @Balance money,
            @Midnight datetime

    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Date), 0, 1)))

    SELECT @Balance =  ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
    FROM AS_Transactions
    WHERE AC_Customers_ID = @CustomerID AND
          Transaction_Date <= @Date AND
          ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
         (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
          Sys_AW_Transaction_Types_ID = 4 OR   --Refund
          Sys_AW_Transaction_Types_ID = 5 OR   --Journal
          Sys_AW_Transaction_Types_ID = 7 OR   --Payment
          Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
          Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
          Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
          Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

    RETURN(@Balance)

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Message
--Purpose       :Returns FLAG if CUSTOMER has received MessageID
--              :    for a specific MONTH of a YEAR
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE            FUNCTION fn_AC_Customer_Has_Message
	(
		@CompanyID int,
        @CustomerID int,
        @MessageID int,
        @Date datetime
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @ReturnCode bit

        IF EXISTS
            (
                SELECT TOP 1 Log_AC_Master_Controller_ID
                FROM Log_AC_Master_Controller
                WHERE Actor_ID = @CustomerID AND
                      AW_User_Companies_ID = @CompanyID AND
                      AW_Messages_ID = @MessageID AND
                     (DATEPART(month, Date_Captured) = DATEPART(month, @Date) AND
                      DATEPART(year, Date_Captured) = DATEPART(year, @Date))
            )
    		SET @ReturnCode = 1

    	ELSE	
    		SET @ReturnCode = 0
    
    	RETURN @ReturnCode
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Message_Span_Period
--Purpose       :Returns FLAG if CUSTOMER received MessageID
--              :    for a specific PERIOD SPAN prior to a date
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION fn_AC_Customer_Has_Message_Span_Period
	(
		@CompanyID int,
        @CustomerID int,
        @MessageID int,
        @Date datetime,
        @Months int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @ReturnCode bit

        IF EXISTS
            (
                SELECT TOP 1 Log_AC_Master_Controller_ID
                FROM Log_AC_Master_Controller
                WHERE Actor_ID = @CustomerID AND
                      AW_User_Companies_ID = @CompanyID AND
                      AW_Messages_ID = @MessageID AND
                      @Date >= DATEADD(month, -@Months, @Date)
            )
    		SET @ReturnCode = 1

    	ELSE	
    		SET @ReturnCode = 0
    
    	RETURN @ReturnCode
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Outstanding_Transactions
--Purpose       :Returns FLAG for Customer Payments PickList
--              :    if Customer has OUTSTANDING TRANSACTIONS amounts
--Parameters    :
--Date          :2002/06/28
--Authors       :TB
--MODS          :02/07/02 - Must not exclude Payments (TranType=7)
--              :04/07/02 - Must now INCLUDE Payments (TranType=7)
--              :10/07/02 - Modified WHERE clause to be INCLUSIVE vs EXCLUSIVE 
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount to return
--              :           transactions inserted with NULL Total_Amount !!
--2004.3.9      :13/06/08 - Changed query to ELIMINATE Customers with an
--              :           OUTSTANDING CREDIT BALANCE - Tessa
--2004.4.3      :07/02/09 - Added new @Option input parameter to INCLUDE/EXCLUDE
--              :           Customers with a CREDIT Account BALANCES - AH
-------------------------------------------------------------------------------

CREATE            FUNCTION fn_AC_Customer_Has_Outstanding_Transactions
	(
        @CustomerID int,
        @Option tinyint
	)

RETURNS bit

AS

    BEGIN
    	DECLARE @Test bit

        SET @Test = 0

        --> INCLUDE Customers with a CREDIT BALANCE
        IF @Option = 1
            BEGIN
                IF EXISTS
                    (
                        SELECT TOP 1 AC_Customers_ID
                        FROM AS_Transactions
                        WHERE AC_Customers_ID = @CustomerID AND
                              (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
                               Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                               Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                               Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                               Sys_AW_Transaction_Types_ID = 18)         --Settlement Discount
                        GROUP BY AC_Customers_ID
                        HAVING SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)) <> 0
                    )
            		SET @Test = 1
            END


        --> EXCLUDE Customers with a CREDIT BALANCE
        ELSE
            BEGIN
                IF EXISTS
                    (
                        SELECT TOP 1 AC_Customers_ID
                        FROM AS_Transactions
                        WHERE AC_Customers_ID = @CustomerID AND
                              (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
                               Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                               Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                               Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                               Sys_AW_Transaction_Types_ID = 18)         --Settlement Discount
                        GROUP BY AC_Customers_ID
                        HAVING SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)) > 0
                    )
            		SET @Test = 1
            END


    	RETURN @Test
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AC_Customer_Has_Sales
--Purpose       :Returns SCALAR bit if Customer has sales between two dates
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2005/05/08
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AC_Customer_Has_Sales
	(
		@CompanyID int,
        @FromDate datetime,
        @ToDate datetime
	)

RETURNS bit

AS
	BEGIN

	DECLARE @Test bit

	IF Exists
            (
                SELECT TOP 1 AC_Customers_ID
                FROM AS_Transactions
                WHERE AW_User_Companies_ID = @CompanyID AND
                     (Transaction_Date > @FromDate AND
                      Transaction_Date <= @ToDate) AND
                     (Sys_AW_Transaction_Types_ID = 3 OR
                      Sys_AW_Transaction_Types_ID = 4)
            )
        SET @Test = 1
	ELSE	
		SET @Test = 0

	RETURN @Test
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Unallocated_Jornals
--Purpose       :Returns FLAG for Unallocated Customer Journals PickList
--              :    if Customer has UNALLOCATED JOURNAL amounts
--Parameters    :
--Date          :2002/07/10
--Authors       :TB
--Version       :1.0.0
--MODS          :10/11/02 - Validate NULL Total_Amount & Payment_Amount to return
--              :           transactions inserted with NULL Total_Amount !!
-------------------------------------------------------------------------------

CREATE         FUNCTION fn_AC_Customer_Has_Unallocated_Journals
	(
        @CustomerID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit

        IF EXISTS
            (
                SELECT TOP 1 AC_Customers_ID
                FROM AS_Transactions
                WHERE AC_Customers_ID = @CustomerID AND
                      ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                      Sys_AW_Transaction_Types_ID = 5
            )
    
    		SET @Test = 1
    	ELSE	
    		SET @Test = 0
    
    	RETURN @Test
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Unallocated_Payments
--Purpose       :Returns FLAG for Unallocated Customer Payments PickList
--              :    if Customer has UNALLOCATED PAYMENT amounts
--Parameters    :
--Date          :2002/07/03
--Authors       :TB
--Version       :1.0.0
--MODS          :24/07/02 - Added Sys_AW_Transaction_Types_ID 21 & 22
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount to return
--              :           transactions inserted with NULL Total_Amount !!
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AC_Customer_Has_Unallocated_Payments]
	(
        @CustomerID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit

        IF EXISTS
            (
                SELECT TOP 1 AC_Customers_ID
                FROM AS_Transactions
                WHERE AC_Customers_ID = @CustomerID AND
--                      ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                      Total_Amount + Payment_Amount <> 0 AND
                     (Sys_AW_Transaction_Types_ID = 7 OR
                      Sys_AW_Transaction_Types_ID = 21 OR
                      Sys_AW_Transaction_Types_ID = 22)
            )
    
    		SET @Test = 1
    	ELSE	
    		SET @Test = 0
    
    	RETURN @Test
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Unallocated_Refunds
--Purpose       :Returns FLAG for Unallocated Customer Refunds PickList
--              :    if Customer has UNALLOCATED REFUND amounts
--Parameters    :
--Date          :2002/08/07
--Authors       :TB
--Version       :1.0.0
--MODS          :10/11/02 - Validate NULL Total_Amount & Payment_Amount to return
--              :           transactions inserted with NULL Total_Amount !!
-------------------------------------------------------------------------------

CREATE          FUNCTION fn_AC_Customer_Has_Unallocated_Refunds
	(
        @CustomerID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit

        IF EXISTS
            (
                SELECT TOP 1 AC_Customers_ID
                FROM AS_Transactions
                WHERE AC_Customers_ID = @CustomerID AND
                        ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                        Sys_AW_Transaction_Types_ID = 4
            )
    
    		SET @Test = 1
    	ELSE	
    		SET @Test = 0
    
    	RETURN @Test
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AC_Customer_Overdue_Amount
--Purpose       :Retrieves ONE Customer's Overdue Amount
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--MODS          :06/03/05 - Advanced the OVERDUE calc by ONE age area
--2004.4.3      :13/03/09 - Reworked TERMS from INVOICE section to SUM
--              :           ALL UNPAID TRANSACTIONS (Except PAYMENTS) from
--              :           ALL UNALLOCATED PAYMENT TRANSACTIONS (in case some are INSIDE the terms)
----------------------------------------------------------------------------

CREATE              FUNCTION dbo.fn_AC_Customer_Overdue_Amount
    (
        @TermsOfSale int,
        @DaysTerms int,
        @CustomerID int,
        @Date datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

RETURNS money

AS

BEGIN

    DECLARE @OtherTrans money,
            @Payments money,
            @Amount money,
            @Midnight datetime,
            @Age1 money,
            @Age2 money,
            @Age3 money,
            @Age4 money,
            @Age5 money,
            @Age6 money,
            @Age7 money


    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Date), 0, 1)))
    SET @Amount = 0


    IF @TermsOfSale = 3    --From Statement
        BEGIN
        	SELECT @Age1 = SUM([Current]),
                   @Age2 = SUM([30 Days]),
                   @Age3 = SUM([60 Days]),
                   @Age4 = SUM([90 Days]),
                   @Age5 = SUM([120 Days]),
                   @Age6 = SUM([150 Days]),
                   @Age7 = SUM([180+ Days])
        	FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
                    ( @CustomerID, @Midnight, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
        	GROUP BY CustomerID

--             IF @DaysTerms < 30                             --'SUM from Current
--                 SET @Amount = @Age1 + @Age2 + @Age3 + @Age4 + @Age5 + @Age6 + @Age7
--             ELSE
--             IF @DaysTerms >= 30 AND @DaysTerms < 60        --'SUM from 30 days
--                 SET @Amount = @Age2 + @Age3 + @Age4 + @Age5 + @Age6 + @Age7
--             ELSE
--             IF @DaysTerms >= 60 AND @DaysTerms < 90        --'SUM from 60 days
--                 SET @Amount = @Age3 + @Age4 + @Age5 + @Age6 + @Age7
--             ELSE
--             IF @DaysTerms >= 90 AND @DaysTerms < 120       --'SUM from 90 days
--                 SET @Amount = @Age4 + @Age5 + @Age6 + @Age7
--             ELSE
--             IF @DaysTerms >= 120 AND @DaysTerms < 150      --'SUM from 120 days
--                 SET @Amount = @Age5 + @Age6 + @Age7
--             ELSE
--             IF @DaysTerms >= 150 AND @DaysTerms < 180      --'SUM from 150 days
--                 SET @Amount = @Age6 + @Age7
--             ELSE
--                 SET @Amount = @Age7

            IF @DaysTerms < 30                             --'SUM from Current
                SET @Amount = @Age2 + @Age3 + @Age4 + @Age5 + @Age6 + @Age7
            ELSE
            IF @DaysTerms >= 30 AND @DaysTerms < 60        --'SUM from 30 days
                SET @Amount = @Age3 + @Age4 + @Age5 + @Age6 + @Age7
            ELSE
            IF @DaysTerms >= 60 AND @DaysTerms < 90        --'SUM from 60 days
                SET @Amount = @Age4 + @Age5 + @Age6 + @Age7
            ELSE
            IF @DaysTerms >= 90 AND @DaysTerms < 120       --'SUM from 90 days
                SET @Amount = @Age5 + @Age6 + @Age7
            ELSE
            IF @DaysTerms >= 120 AND @DaysTerms < 150      --'SUM from 120 days
                SET @Amount = @Age6 + @Age7
            ELSE
            IF @DaysTerms >= 150 AND @DaysTerms < 180      --'SUM from 150 days
                SET @Amount = @Age7
            ELSE
                SET @Amount = @Age7
        END

    ELSE                   -- ANY other Terms of Sale (From Invoice or <None>)
        BEGIN
--     		SELECT @Amount = ISNULL(SUM(Total_Amount) + SUM(Payment_Amount), 0)
--         	FROM AS_Transactions
--         	WHERE AC_Customers_ID = @CustomerID AND
--                  (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
--                   Sys_AW_Transaction_Types_ID = 4 OR        --Refund
--                   Sys_AW_Transaction_Types_ID = 5 OR        --Journal
--                   Sys_AW_Transaction_Types_ID = 7 OR        --Payment
--                   Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
--                   Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
--                   Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
--                   Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
--                   ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
--                 --> If Transaction OLDER THAN @DaysTerms
--                   DATEDIFF(d, @Midnight, Transaction_Date + @DaysTerms) < 0

            --> Select ALL UNPAID TRANSACTIONS (Except PAYMENTS)
    		SELECT @OtherTrans = ISNULL(SUM(Total_Amount) + SUM(Payment_Amount), 0)
        	FROM AS_Transactions
        	WHERE AC_Customers_ID = @CustomerID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                  Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18) AND     --EFT Payment
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                --> If Transaction OLDER THAN @DaysTerms
                  DATEDIFF(d, @Midnight, Transaction_Date + @DaysTerms) < 0

            --> Select ALL UNALLOCATED PAYMENT TRANSACTIONS (in case some are INSIDE the terms)
    		SELECT @Payments = ISNULL(SUM(Total_Amount) + SUM(Payment_Amount), 0)
        	FROM AS_Transactions
        	WHERE AC_Customers_ID = @CustomerID AND
                 (Sys_AW_Transaction_Types_ID = 7 OR        --Payment
                  Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0

            SET @Amount = @OtherTrans + @Payments

        END

    RETURN(@Amount)


END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Period_Procedure_Ageing
--Purpose       :Retrieves Customer Ageing Amounts between each Age Area date
--              :using user-defined cut-off date (@D0) for Customer Period Procedure
--NOTE          :ANY MOD ALSO TO BE INSERTED IN fn_AO_Supplier_Ageing_Non_Grouped
--Date          :2006/09/15
--Authors       :TB
--Source        :Copied from fn_AC_Customer_Ageing_Non_Grouped
--MODS          :
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AC_Customer_Period_Procedure_Ageing
    (
        @CustomerID int, 
        @D0 DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
    (
        [ID] int, 
        CustomerID int,
        [Date] datetime,
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money,
        [User] varchar(20)
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		AS_Transactions_ID as [ID], 
    		@CustomerID as CustomerID,
    		Transaction_Date,
    		Payment_Amount as Payment, 
    		Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D1,
                     @D0,
                    (Total_Amount + Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Transaction_Date)),
                     Transaction_Date,
                     @D7,                     @D6,
                     0
                ) as [180+ Days],
            AW_Users.UserName AS [User]
    	FROM AS_Transactions
            LEFT JOIN AW_Users
                ON AS_Transactions.[User_ID] = AW_Users.AW_Users_ID
    	WHERE AC_Customers_ID = @CustomerID AND
             (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
              Sys_AW_Transaction_Types_ID = 4 OR        --Refund
              Sys_AW_Transaction_Types_ID = 5 OR        --Journal
              Sys_AW_Transaction_Types_ID = 7 OR        --Payment
              Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
              Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
              Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
              Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
              ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
--             DATEDIFF(d, @D0, Transaction_Date) <= 0
              Transaction_Date <= @D0

    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Period_Procedure_Ageing_Non_Grouped
--Purpose       :Set Customer Period Procedure Ageing Amounts between Procedure dates
--Calls         :fn_AW_Amount_of_Date_Between
--Date          :2006/09/30
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION fn_AC_Customer_Period_Procedure_Ageing_Non_Grouped
    (
        @CustomerID int, 
        @ProcedureDate DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
    (
        [ID] int, 
        CustomerID int,
        [Date] datetime,
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money,
        [User] varchar(20)
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		AS_Transactions_ID as [ID], 
    		@CustomerID as CustomerID,
    		Transaction_Date,
    		Payment_Amount as Payment, 
    		Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D1,
                     @ProcedureDate,
                    (Total_Amount + Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D7,                     @D6,
                     0
                ) as [180+ Days],
            AW_Users.UserName AS [User]
    	FROM AS_Transactions
            LEFT JOIN AW_Users
                ON AS_Transactions.[User_ID] = AW_Users.AW_Users_ID
    	WHERE AC_Customers_ID = @CustomerID AND
             (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
              Sys_AW_Transaction_Types_ID = 4 OR        --Refund
              Sys_AW_Transaction_Types_ID = 5 OR        --Journal
              Sys_AW_Transaction_Types_ID = 7 OR        --Payment
              Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
              Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
              Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
              Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
              ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
              Transaction_Date <= @ProcedureDate

    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Period_Procedure_Ageing_Values
--Purpose       :Retrieves Customer Ageing Amounts between each Age Area date
--              :    for Customer Period Procedure
--Calls         :fn_AC_Customer_Period_Procedure_Ageing_Non_Grouped
--Date          :2006/09/30
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            FUNCTION fn_AC_Customer_Period_Procedure_Ageing_Values
    (
        @CustomerID int, 
        @ProcedureDate datetime, 
        @D1 datetime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

RETURNS @AgeTable TABLE 
    (
    	CustomerID 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 datetime,
        Days60Date datetime,
        Days90Date datetime,
        Days120Date datetime,
        Days150Date datetime,
        Days180Date datetime
    )

AS

    BEGIN
    
        INSERT @AgeTable
        SELECT CustomerID,
            sum([Payment]) AS [Payment],
            sum([Amount]) AS [Amount],        
            sum([Current]) AS [Current],
            sum([30 Days]) AS [30 Days],
            sum([60 Days]) AS [60 Days],
            sum([90 Days]) AS [90 Days],
            sum([120 Days]) AS [120 Days], 
            sum([150 Days]) AS [150 Days],
            sum([180+ Days]) AS [180+ Days],
            @ProcedureDate AS CurrentDate,
            @D1 AS Days30Date,
            @D2 AS Days60Date,
            @D3 AS Days90Date,
            @D4 AS Days120Date,
            @D5 AS Days150Date,
            @D6 AS Days180Date
        FROM dbo.fn_AC_Customer_Period_Procedure_Ageing_Non_Grouped
            (
                @CustomerID,
                @ProcedureDate,
                @D1,
                @D2,
                @D3,
                @D4,
                @D5,
                @D6,
                @D7
            )
        GROUP BY CustomerID
    
    RETURN
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION fn_AC_Customer_Statements_Ageing_Non_Grouped
    (
	    @CustomerStatementsID int,
    	@CustomerID int, 
	    @D0 DateTime, 
    	@D1 DateTime,
    	@D2 DateTime,
    	@D3 DateTime,
    	@D4 DateTime,
    	@D5 DateTime,
    	@D6 DateTime,
    	@D7 DateTime
    )

RETURNS @AgeTable TABLE 
	(
        ID int, 
    	CustomerID int,
    	[Date] datetime,
    	Payment money,
    	Amount money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )
AS

BEGIN

	INSERT @AgeTable
	SELECT    
		[ID], 
		@CustomerID as CustomerID,
		Transaction_Date,
		Payment_Amount as Payment, 
		Total_Amount as Amount, 
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D1, @D0,(Total_Amount+Payment_Amount)) as [Current],
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D2, @D1,0) as [30 Days],
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D3, @D2,0) as [60 Days],
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D4, @D3,0) as [90 Days],
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D5, @D4,0) as [120 Days],
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D6, @D5,0) as [150 Days],
		dbo.fn_AW_Amount_of_Date_Between((Total_Amount + Payment_Amount), Transaction_Date, @D7, @D6,0) as [180+ Days]
	FROM 
		fn_AC_Customer_Statements_Transactions(@CustomerStatementsID)
	WHERE (CustomerID = @CustomerID)

RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION fn_AC_Customer_Statements_Ageing_Values
    (
	    @PeriodProcedureID int,
    	@CustomerID int, 
	    @D0 DateTime, 
    	@D1 DateTime,
    	@D2 DateTime,
    	@D3 DateTime,
    	@D4 DateTime,
    	@D5 DateTime,
    	@D6 DateTime,
    	@D7 DateTime
    )
RETURNS @AgeTable TABLE 
    (
    	CustomerID 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 datetime,
        Days60Date datetime,
        Days90Date datetime,
        Days120Date datetime,
        Days150Date datetime,
        Days180Date datetime
    )

AS

BEGIN

    INSERT @AgeTable
    SELECT CustomerID,
        sum([Payment]) AS [Payment],
        sum([Amount]) AS [Amount],        
        sum([Current]) AS [Current],
        sum([30 Days]) AS [30 Days],
        sum([60 Days]) AS [60 Days],
        sum([90 Days]) AS [90 Days],
        sum([120 Days]) AS [120 Days], 
        sum([150 Days]) AS [150 Days],
        sum([180+ Days]) AS [180+ Days],
        @D0 as CurrentDate,
        @D1 as Days30Date,
        @D2 as Days60Date,
        @D3 as Days90Date,
        @D4 as Days120Date,
        @D5 as Days150Date,
        @D6 as Days180Date
    FROM dbo.fn_AC_Customer_Statements_Ageing_Non_Grouped(@PeriodProcedureID, @CustomerID, @D0, @D1, @D2, @D3, @D4, @D5, @D6, @D7)
    GROUP BY CustomerID
RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION fn_AC_Customer_Statements_Transactions
    (
        @PeriodProcedureID int
    )

RETURNS @Transactions TABLE 

	(
		[ID]  int, 
		CustomerID int,
		Transaction_Date DateTime,
		Payment_Amount money,
		Total_Amount money
	)

AS

BEGIN

	INSERT @Transactions

	SELECT
        cst.AC_Customer_Statements_Transactions_ID,
        csc.AC_Customers_ID,
        cst.Transaction_Date,
        cst.Amount,
        cst.Payment
	FROM AC_Customer_Statements_Transactions cst 
		INNER JOIN AC_Customer_Statements_Customers csc
            ON cst.AC_Customer_Statements_Customers_ID = csc.AC_Customer_Statements_Customers_ID
	WHERE csc.AW_Period_Procedures_ID = @PeriodProcedureID

	RETURN 

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Total_Ageing
--Purpose       :Retrieves Total Customer Ageing Amounts between each Age Area date
--NOTE          :ANY MOD ALSO TO BE INSERTED IN fn_AO_Supplier_Ageing_Non_Grouped
--Called by     :Manager Console
--Date          :2002/12/23
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AC_Customer_Total_Ageing
    (
        @D0 DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
    (
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		Payment_Amount as Payment, 
    		Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D1,
                     @D0,
                    (Total_Amount + Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Transaction_Date,
                     @D7,                     @D6,
                     0
                ) as [180+ Days]
    	FROM AS_Transactions
    	WHERE (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
               Sys_AW_Transaction_Types_ID = 4 OR        --Refund
               Sys_AW_Transaction_Types_ID = 5 OR        --Journal
               Sys_AW_Transaction_Types_ID = 7 OR        --Payment
               Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
               Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
               Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
               Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
               ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
               DATEDIFF(d, @D0, Transaction_Date) <= 0

    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Total_Ageing_No_InterCo
--Purpose       :Retrieves Total Customer Ageing Amounts between each Age Area date
--              :Excluding Inter-Company Customers
--NOTE          :ANY MOD ALSO TO BE INSERTED IN
--              :    fn_AC_Customer_Total_Ageing
--              :    fn_AO_Supplier_Ageing_Non_Grouped
--Called by     :Manager Console
--Date          :2009/08/26
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AC_Customer_Total_Ageing_No_InterCo
    (
        @D0 DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
    (
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		t.Payment_Amount as Payment, 
    		t.Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D1,
                     @D0,
                    (t.Total_Amount + t.Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Transaction_Date,
                     @D7,
                     @D6,
                     0
                ) as [180+ Days]
    	FROM AS_Transactions t
            INNER JOIN AC_Customers c
                ON t.AC_Customers_ID = c.AC_Customers_ID
    	WHERE (t.Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
               t.Sys_AW_Transaction_Types_ID = 4 OR        --Refund
               t.Sys_AW_Transaction_Types_ID = 5 OR        --Journal
               t.Sys_AW_Transaction_Types_ID = 7 OR        --Payment
               t.Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
               t.Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
               t.Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
               ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
               DATEDIFF(d, @D0, t.Transaction_Date) <= 0 AND
               c.Sys_AC_Account_Types_ID <> 3

    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Get_Customer_Rating
--Purpose       :Returns latest Customer Rating
--Parameters    :
--Date          :2004/05/16
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          FUNCTION fn_AC_Get_Customer_Rating
	(
    	@CompanyID int,
        @CustomerID int
	)

RETURNS varchar(10)

AS

	BEGIN
        DECLARE @Rating varchar(10)

        SELECT TOP 1 @Rating = ISNULL(b.Description, '')
        FROM AC_History_Ratings a
            LEFT JOIN Slu_AC_Ratings b
                ON a.Slu_AC_Ratings_ID = b.Slu_AC_Ratings_ID
        WHERE a.AC_Customers_ID = @CustomerID AND
              a.AW_User_Companies_ID = @CompanyID AND
              a.Slu_AW_Active_ID = 1
        ORDER BY a.Effective_Date DESC
    
  
    	RETURN @Rating


    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Get_Customer_Status
--Purpose       :Returns latest Customer Status
--Parameters    :
--Date          :2004/07/15
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION fn_AC_Get_Customer_Status
	(
        @CustomerID int
	)

RETURNS varchar(30)

AS

	BEGIN
        DECLARE @Status varchar(30)

        SELECT TOP 1 @Status = ISNULL(b.Description, '')
        FROM AC_History_Status a
            LEFT JOIN Sys_AC_Account_Status b
                ON a.Sys_AC_Account_Status_ID = b.Sys_AC_Account_Status_ID
        WHERE a.AC_Customers_ID = @CustomerID AND
              a.Slu_AW_Active_ID = 1
        ORDER BY a.Date_Changed DESC
    
  
    	RETURN @Status


    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Get_Last_Payment_Amount
--Purpose       :Returns Customer Last Payment Amount
--Parameters    :
--Date          :2004/12/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AC_Get_Last_Payment_Amount
	(
        @CustomerID int
	)

RETURNS money

AS

	BEGIN

        DECLARE @PaymentAmount money

        SELECT TOP 1 @PaymentAmount = Total_Amount
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
             (Sys_AW_Transaction_Types_ID = 7 OR
              Sys_AW_Transaction_Types_ID = 21 OR
              Sys_AW_Transaction_Types_ID = 22)
        ORDER BY Transaction_Date DESC
    
  
    	RETURN @PaymentAmount


    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Get_Last_Payment_Date
--Purpose       :Returns Customer Last Payment Date
--Parameters    :
--Date          :2004/12/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AC_Get_Last_Payment_Date
	(
        @CustomerID int
	)

RETURNS datetime

AS

	BEGIN

        DECLARE @PaymentDate datetime

        SELECT TOP 1 @PaymentDate = Transaction_Date
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
             (Sys_AW_Transaction_Types_ID = 7 OR
              Sys_AW_Transaction_Types_ID = 21 OR
              Sys_AW_Transaction_Types_ID = 22)
        ORDER BY Transaction_Date DESC
    
  
    	RETURN @PaymentDate


    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AC_Get_Last_Sale_Date
--Purpose       :Returns Customer Last Sale Date
--Parameters    :
--Date          :2007/08/20
--Authors       :TB
--MODS          :
--2004.3.8      :21/01/08 - Removed superfluous JOIN with AS_Transaction_Details
-------------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AC_Get_Last_Sale_Date
	(
        @CustomerID int
	)

RETURNS datetime

AS

	BEGIN

        DECLARE @SaleDate datetime


        SELECT TOP 1 @SaleDate = Transaction_Date
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
              Sys_AW_Transaction_Types_ID = 3
        ORDER BY Transaction_Date DESC
    
  
    	RETURN @SaleDate

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





-------------------------------------------------------------------------------
--Description   :dbo.fn_AF_Exists_Factory_JobNo
--Purpose       :Returns FLAG if AF_Job_Tickets.Job_No exists
--Date          :2011/05/07
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            FUNCTION [dbo].[fn_AF_Exists_Factory_JobNo]
	(
        @Value int,
        @CompanyID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit


        IF EXISTS
            (
                SELECT TOP 1 AF_Job_Tickets_ID
                FROM AF_Job_Tickets
                WHERE Job_No = @Value AND
                      AW_User_Companies_ID = @CompanyID
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0



    	RETURN @Test

    END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AO_BFWD_Supplier_Date_Balance
--Purpose       :Retrieves Supplier Opening Balance BEFORE a DATE
--Parameters    :
--Date          :2004/11/21
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AO_BFWD_Supplier_Date_Balance
    (
        @SupplierID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @BFWD float


        SELECT @BFWD = ISNULL(SUM(Total_Amount), 0)
        FROM AO_Transactions
        WHERE AO_Suppliers_ID = @SupplierID AND
              Date_Captured < @OpeningDate


        RETURN(@BFWD)

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AO_BFWD_Supplier_Period_Balance
--Purpose       :Retrieves Supplier Opening Balance BEFORE an Accounting Period
--Parameters    :
--Date          :2004/11/21
--Authors       :TB
--Version       :1.0.0
--MODS          :
--2004.3.5      :22/06/07 - Changed @OpeningPeriod comparison from < to <=
--              :           picked up the period BEFORE the period requested
----------------------------------------------------------------------------

CREATE             FUNCTION dbo.fn_AO_BFWD_Supplier_Period_Balance
    (
        @SupplierID int,
        @OpeningPeriod varchar(6)
    )

RETURNS float

AS

    BEGIN

        DECLARE @BFWD float


        SELECT @BFWD = ISNULL(SUM(Total_Amount), 0)
        FROM AO_Transactions
        WHERE AO_Suppliers_ID = @SupplierID AND
              dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @OpeningPeriod


        RETURN(@BFWD)

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Get_Qty_On_Order
--Purpose       :Returns outstanding ORDER QUANTITY of ONE Product
--Parameters    :
--Date          :2007/08/13
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION fn_AO_Get_Qty_On_Order
	(
        @ProductID int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = (ISNULL(SUM(od.Order_Qty), 0) +
                           ISNULL(SUM(od.Back_Order_Qty), 0) -
                           ISNULL(SUM(od.Received_Qty), 0))
            FROM AO_Order_Details od
                INNER JOIN AO_Orders o
                    ON od.AO_Orders_ID = o.AO_Orders_ID
            WHERE od.AP_Products_ID = @ProductID AND
                  o.Date_Ordered IS NOT NULL AND
                  o.Complete <> 1
                  


    	RETURN @Qty
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Product_Has_Orders
--Purpose       :Returns BOOLEAN if Product has any outstanding orders
--Parameters    :
--Date          :2003/10/12
--Authors       :TB
--MODS          :
--2004.3.7      :13/08/07 - Increased size of @Qty to decimal(9,3)
-------------------------------------------------------------------------------

CREATE          FUNCTION fn_AO_Product_Has_Orders
	(
        @ProductID int
	)

RETURNS bit

AS
	BEGIN

	DECLARE @Test bit,
            @Qty decimal(9,3)


        SELECT @Qty = (ISNULL(SUM(od.Order_Qty), 0) +
                       ISNULL(SUM(od.Back_Order_Qty), 0) -
                       ISNULL(SUM(od.Received_Qty), 0))
        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 = @ProductID


    IF @Qty > 0
        SET @Test = 1
	ELSE	
		SET @Test = 0

	RETURN @Test
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AO_SUM_GL_Supplier_Payment_Amount
--Purpose       :SUM GL Payment Amount for one Supplier Payment
--Parameters    :
--Date          :2007/06/24
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE             FUNCTION dbo.fn_AO_SUM_GL_Supplier_Payment_Amount
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
--        @ABSourceRef varchar(20),
        @AOTranID int,
        @Trade_Creditors_Control_ID int
    )

RETURNS float

AS

    BEGIN

        DECLARE @PaymentTotal float


        SELECT @PaymentTotal = SUM(ISNULL(AB_Transaction_Amount, 0))
        FROM AB_GL_Transactions
        WHERE AW_User_Companies_ID = @CompanyID AND
--              AB_Source_Ref = @ABSourceRef AND
              AB_Transaction_Ref = @AOTranID AND
              Sys_AB_Transaction_Types_ID = 8 AND
              Slu_AW_Months_ID = @MonthID AND
              Slu_AW_Years_ID = @YearID AND
              AB_Accounts_ID = @Trade_Creditors_Control_ID
              

        RETURN(@PaymentTotal)
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION fn_AO_Supplier_Ageing_Grouped_ALL_Suppliers

    (
		@D0 DateTime, 
    	@D1 DateTime,
    	@D2 DateTime,
    	@D3 DateTime,
    	@D4 DateTime,
    	@D5 DateTime,
    	@D6 DateTime,
    	@D7 DateTime
    )

RETURNS @AgeTable TABLE 

	(
--        ID int, 
    	SupplierID int,
--     	[Date] datetime,
    	Payment money,
    	Amount money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

BEGIN

	INSERT @AgeTable
	SELECT    
		AO_Suppliers_ID as SupplierID,
-- 		Date_Captured  AS [Transaction_Date],
		Payment_Amount Payment, 
		Total_Amount Amount, 
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D1, @D0,(isnull(Total_Amount,0) + isnull(Payment_Amount,0))) [Current],
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D2, @D1,0) [30 Days],
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D3, @D2,0) [60 Days],
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D4, @D3,0) [90 Days],
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D5, @D4,0) [120 Days],
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D6, @D5,0) [150 Days],
		dbo.fn_AW_Amount_of_Date_Between((isnull(Total_Amount,0) + isnull(Payment_Amount,0)), Date_Captured, @D7, @D6,0) [180+ Days]
	FROM 
		AO_Transactions
	WHERE (Sys_AW_Transaction_Types_ID = 8    --Purchase Invoice
             OR Sys_AW_Transaction_Types_ID = 9    --Purchase Refund
             OR Sys_AW_Transaction_Types_ID = 10    --Purchase Journal
             OR Sys_AW_Transaction_Types_ID = 12    --Supplier Payment
             OR Sys_AW_Transaction_Types_ID = 6)    --Supplier Settlement Discount
           AND (isnull(Total_Amount,0) + isnull(Payment_Amount,0) <> 0)


RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Ageing_Non_Grouped
--Purpose       :Retrieves Customer Ageing Amounts between each Age Area date
--NOTE          :DOES NOT WORK THE SAME AS fn_AC_Customer_Ageing_Non_Grouped
--              :    NB NB: Transaction Date Based
--Called by     :OLD sp_AO_Supplier_Remittances_Temp_Insert (Supplier Reports)
--Date          :2002/01/21
--Authors       :TB
--Version       :1.0.0
--MODS          :12/09/02 - CONVERT datetime value of Transaction_Date to INT
--              :           not matching when full DATETIME 'YYYY/MM/DD HH:MM:SS'
--              :           is compared to 'YYYY/MM/DD' in fn_AW_Amount_of_Date_Between
--              :12/09/02 - Added DATEDIFF(d, @D0, CONVERT(datetime, CONVERT(int, Date_Captured))) <= 0
--              :           to WHERE clause to inlude all transactions up to present
--              :           as is done in the Customers equivalent script
--              :18/09/02 - Added ISNULL validation to all amounts
--              :!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
--              :25/10/02 - !!!! REMOVED MODS OF 09/08/02 causing Journal amounts
--              :           not to be included in the Account and Ageing balances
--              :           immediately after posting at Protea !!!!!!!!!!!!!!!
--              :           THIS NEEDS TO BE RE-VISITED to fix the reason for the ORIG mod
--              :!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-------------------------------------------------------------------------------

CREATE                FUNCTION fn_AO_Supplier_Ageing_Non_Grouped
    (
    	@Supplier int, 
		@D0 DateTime, 
    	@D1 DateTime,
    	@D2 DateTime,
    	@D3 DateTime,
    	@D4 DateTime,
    	@D5 DateTime,
    	@D6 DateTime,
    	@D7 DateTime
    )

RETURNS @AgeTable TABLE 
	(
        [ID] int, 
    	SupplierID int,
    	[Date] datetime,
    	Payment money,
    	Amount money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

    	INSERT @AgeTable
    
    	SELECT    
    		AO_Transactions_ID as [ID], 
    		@Supplier as SupplierID,
    		Date_Captured AS [Transaction_Date],
    		Payment_Amount as Payment, 
    		Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D1,
                     @D0,
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0))
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
--!!                     CONVERT(datetime, CONVERT(int, Date_Captured)),
                     Date_Captured,
                     @D7,
                     @D6,
                     0
                ) as [180+ Days]
    	FROM AO_Transactions
    	WHERE AO_Suppliers_ID = @Supplier AND
             (Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
              Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
              Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
              Sys_AW_Transaction_Types_ID = 12 OR       --Supplier Payment
              Sys_AW_Transaction_Types_ID = 6) AND      --Supplier Settlement Discount
              ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
              DATEDIFF(d, @D0, Date_Captured) <= 0
--!!              DATEDIFF(d, @D0, CONVERT(datetime, CONVERT(int, Date_Captured))) <= 0
    
    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers
--Purpose       :Retrieves Ageing Totals of All Suppliers
--Date          :2001/08/26
--Authors       :TB
--MODS          :
--2004.5.2      :11/07/11 - Fixed Supplier_Name field length to new size 40 !!!!
-------------------------------------------------------------------------------

CREATE FUNCTION [fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers]
    (    	 
		@D0 DateTime, 
    	@D1 DateTime,
    	@D2 DateTime,
    	@D3 DateTime,
    	@D4 DateTime,
    	@D5 DateTime,
    	@D6 DateTime,
    	@D7 DateTime,
		@CompanyID int
    )

RETURNS @AgeTable TABLE 
	(
        [ID] int,
        [SupplierID] int, 
        [Supplier_Name] varchar(40),
        [Date] datetime,
        [Payment] money,
        [Amount] money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money
    )

AS

BEGIN

	INSERT @AgeTable
	SELECT
            t.AO_Transactions_ID AS [ID], 
            t.AO_Suppliers_ID AS [SupplierID],  
            s.Supplier_Name AS [Supplier_Name],
            t.Date_Captured AS [Transaction_Date],
            t.Payment_Amount AS [Payment], 
            t.Total_Amount AS [Amount], 
            dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D1, @D0,(ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0))
            ) AS [Current],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D2, @D1,0
            ) AS [30 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D3, @D2,0
            ) AS [60 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D4, @D3,0
            ) AS [90 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D5, @D4,0
            ) AS [120 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D6, @D5,0
            ) AS [150 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D7, @D6,0
            ) AS [180+ Days]
    FROM AO_Transactions t
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
	WHERE (t.Sys_AW_Transaction_Types_ID = 8 OR    --Purchase Invoice
           t.Sys_AW_Transaction_Types_ID = 9 OR    --Purchase Refund
           t.Sys_AW_Transaction_Types_ID = 10 OR   --Purchase Journal
           t.Sys_AW_Transaction_Types_ID = 12 OR   --Supplier Payment
           t.Sys_AW_Transaction_Types_ID = 6) AND  --Supplier Settlement Discount
          (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
		  (t.AW_User_Companies_ID = @CompanyID)
    
    RETURN

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Ageing_Values
--Purpose       :Retrieves Supplier Ageing Amounts between each Age Area date
--NOTE          :    NB NB: Transaction Date Based
--Called by     :OLD sp_AO_Supplier_Remittances_Temp_Insert (Supplier Reports)
--Date          :2002/02/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE       FUNCTION fn_AO_Supplier_Ageing_Values
    (
        @SupplierID int, 
        @D0 datetime, 
        @D1 datetime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

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 datetime,
        Days60Date datetime,
        Days90Date datetime,
        Days120Date datetime,
        Days150Date datetime,
        Days180Date datetime
    )

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],
            @D0 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_Ageing_Non_Grouped
            (
                @SupplierID,
                @D0,
                @D1,
                @D2,
                @D3,
                @D4,
                @D5,
                @D6,
                @D7
            )
        GROUP BY SupplierID
    
    RETURN
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AO_Supplier_Balance
--Purpose       :Retrieves ONE Supplier's Account Balance
--              :
--Parameters    :
--Date          :2008/08/12
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AO_Supplier_Balance
    (
        @SupplierID int
    )

RETURNS money

AS

BEGIN

    DECLARE @Balance money

    SET @Balance = 0

    SELECT @Balance =  ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
    FROM AO_Transactions
    WHERE AO_Suppliers_ID = @SupplierID AND
          ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
         (Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
          Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
          Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
          Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
          Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment

    RETURN(@Balance)

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Captured_Ageing_SUM_All
--Purpose       :Retrieves SUM of ALL Supplier Ageing Amounts by Date Captured
--Date          :2005/09/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AO_Supplier_Captured_Ageing_SUM_All
    (
    	@CompanyID 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,
        @Date datetime
    )

RETURNS @AgeTable TABLE 
	(
    	[CompanyID] int,
    	[SupplierID] int,
        [MarkedToPay] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT
            t.AW_User_Companies_ID as [CompanyID],
            t.AO_Suppliers_ID as [SupplierID],
            SUM(t.To_Be_Paid_Amount) AS [MarkedToPay],
            SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                )) as [Current],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                )) as [30 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                )) as [60 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                )) as [90 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                )) as [120 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                )) as [150 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                )) as [180+ Days]

    	FROM AO_Transactions t
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               t.Date_Captured <= @Date
--               AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1
        GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_DocDate_Ageing_SUM_All
--Purpose       :Retrieves SUM of ALL Supplier Ageing Amounts by Transaction Date
--Date          :2005/09/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           FUNCTION fn_AO_Supplier_DocDate_Ageing_SUM_All
    (
    	@CompanyID 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,
        @Date datetime
    )

RETURNS @AgeTable TABLE 
	(
    	[CompanyID] int,
    	[SupplierID] int,
        [MarkedToPay] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT
            t.AW_User_Companies_ID as [CompanyID],
            t.AO_Suppliers_ID as [SupplierID],
            SUM(t.To_Be_Paid_Amount) AS [MarkedToPay],
            SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                )) as [Current],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                )) as [30 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                )) as [60 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                )) as [90 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                )) as [120 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                )) as [150 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                )) as [180+ Days]

    	FROM AO_Transactions t
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               t.Document_Date <= @Date
--               AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1
        GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Has_Outstanding_Transactions
--Purpose       :Returns FLAG for Supplier Payments PickList
--              :    if Supplier has OUTSTANDING TRANSACTIONS amounts
--Parameters    :
--Date          :2002/11/04
--Authors       :TB
--MODS          :
--2004.3.9      :13/06/08 - Changed query to ELIMINATE Suppliers with an
--              :           OUTSTANDING CREDIT BALANCE - Tessa
--2004.4.2      :03/12/08 - Added validation if outstanding amount >= 0 to enable
--              :           posting payments on accounts with a ZERO balanace
--2004.4.3      :21/03/09 - Added @Option to FETCH Suppliers list WITH (@Option = 1)
--              :           or WITHOUT (@Option = 0) an OUTSTANDING DEBIT BALANCE.
--              :           BOTH options INCLUDE Suppliers with ZERO BALANCE but have
--              :           UNALLOCATED debits and credits that CONTRA each other
--2004.4.7      :17/09/09 - Added to select unallocated Payment transactions
--              :           (TranType = 12) for new Lumpsum Payments
-------------------------------------------------------------------------------

CREATE                 FUNCTION fn_AO_Supplier_Has_Outstanding_Transactions
	(
        @SupplierID int,
        @Option tinyint
	)

RETURNS bit

AS

    BEGIN
    	DECLARE @Test bit

        SET @Test = 0

        --> INCLUDE Suppliers with an OUTSTANDING DEBIT BALANCE
        IF @Option = 1
            BEGIN
                IF EXISTS
                    (
                        SELECT AO_Suppliers_ID
                        FROM AO_Transactions
                        WHERE AO_Suppliers_ID = @SupplierID AND
                             (Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement
                              Sys_AW_Transaction_Types_ID = 8 OR        --Supplier Invoice
                              Sys_AW_Transaction_Types_ID = 9 OR        --Supplier Refund
                              Sys_AW_Transaction_Types_ID = 10 OR       --Supplier Journal
                              Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment
                        GROUP BY AO_Suppliers_ID
                        HAVING (SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)) <> 0 OR
                                SUM(ABS(ISNULL(Total_Amount, 0))) <> SUM(ABS(ISNULL(Payment_Amount, 0))))
                    )
            		SET @Test = 1
            END

        --> ELIMINATE Suppliers with an OUTSTANDING DEBIT BALANCE
        ELSE   
            BEGIN
                IF EXISTS
                    (
                        SELECT AO_Suppliers_ID
                        FROM AO_Transactions
                        WHERE AO_Suppliers_ID = @SupplierID AND
                             (Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement
                              Sys_AW_Transaction_Types_ID = 8 OR        --Supplier Invoice
                              Sys_AW_Transaction_Types_ID = 9 OR        --Supplier Refund
                              Sys_AW_Transaction_Types_ID = 10 OR       --Supplier Journal
                              Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment
                          AND ABS(ISNULL(Total_Amount, 0)) <> ABS(ISNULL(Payment_Amount, 0))
                        GROUP BY AO_Suppliers_ID
                        HAVING SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)) >= 0
                    )
            		SET @Test = 1
            END


    	RETURN @Test
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
-- TO TEST NEW VERSION
-------------------------------------------------------------------------------
--     SELECT MAX(AO_Suppliers_ID) AS [ID],
--            MAX(Slu_AW_Years_ID) AS [Year],
--            MAX(Slu_AW_Months_ID) AS [Month],
--            SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)) AS [Owing]
--     FROM AO_Transactions
--     WHERE AO_Suppliers_ID = 4 AND
--           (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)) <> 0
--     GROUP BY Slu_AW_Years_ID, Slu_AW_Months_ID
--     ORDER BY [Year], [Month] DESC
-------------------------------------------------------------------------------

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Period_Ageing
--Purpose       :NEW: Retrieves Supplier Ageing Amounts by Accounting Period
--NOTE          :
--Date          :2002/10/29
--Authors       :TB
--Version       :1.0.0
--MODS:         :02/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
-------------------------------------------------------------------------------

CREATE                    FUNCTION fn_AO_Supplier_Period_Ageing
    (
    	@Supplier 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
    )

RETURNS @AgeTable TABLE 
	(
        [ID] int, 
    	[SupplierID] int,
    	[DocumentDate] datetime,
    	[CaptureDate] datetime,
    	[Amount] money,
    	[Payment] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money,
        [User] varchar(20)
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT    
            t.AO_Transactions_ID as [ID], 
            @Supplier as [SupplierID],
            t.Document_Date AS [DocumentDate],
            t.Date_Captured AS [CaptureDate],
            t.Total_Amount as [Amount], 
            t.Payment_Amount as [Payment], 
            dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                ) as [Current],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                ) as [180+ Days],
            u.UserName AS [User]

    	FROM AO_Transactions t
            LEFT JOIN AW_Users u
                ON t.[User_ID] = u.AW_Users_ID
    	WHERE t.AO_Suppliers_ID = @Supplier AND
             (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
              t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
              t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
              t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
              t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
               dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1

--               t.Slu_AW_Months_ID <= @M1 AND
--               t.Slu_AW_Years_ID <= @Y1

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Period_Ageing_All
--Purpose       :Retrieves ALL Supplier Ageing Amounts by Accounting Period
--Date          :2005/08/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AO_Supplier_Period_Ageing_All
    (
    	@CompanyID 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
    )

RETURNS @AgeTable TABLE 
	(
    	[CompanyID] int,
    	[SupplierID] int,
        [MarkedToPay] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT
            t.AW_User_Companies_ID as [CompanyID],
            t.AO_Suppliers_ID as [SupplierID],
            ISNULL(t.To_Be_Paid_Amount, 0) AS [MarkedToPay],
            dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                ) as [Current],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                ) as [180+ Days]

    	FROM AO_Transactions t
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Period_Ageing_SUM_All
--Purpose       :Retrieves SUM of ALL Supplier Ageing Amounts by Accounting Period
--Date          :2005/08/22
--Authors       :TB
--MODS:         :22/09/05 - Removed SUM of Payment_Amount for each Age Area
-------------------------------------------------------------------------------

CREATE            FUNCTION fn_AO_Supplier_Period_Ageing_SUM_All
    (
    	@CompanyID 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
    )

RETURNS @AgeTable TABLE 
	(
    	[CompanyID] int,
    	[SupplierID] int,
        [MarkedToPay] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT
            t.AW_User_Companies_ID as [CompanyID],
            t.AO_Suppliers_ID as [SupplierID],
            SUM(t.To_Be_Paid_Amount) AS [MarkedToPay],
            SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                )) as [Current],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                )) as [30 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                )) as [60 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                )) as [90 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                )) as [120 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                )) as [150 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                )) as [180+ Days]

    	FROM AO_Transactions t
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1
        GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

--BASED ON: fn_AO_Supplier_Ageing_Values

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Period_Ageing_Values
--Purpose       :Retrieves Supplier Ageing Amounts between each Accounting Period
--NOTE          :    NB NB: Transaction Accounting Period Based
--Called by     :NEW sp_AO_Supplier_Remittances_Temp_Insert (Supplier Reports)
--Date          :2002/11/01
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE        FUNCTION fn_AO_Supplier_Period_Ageing_Values
    (
    	@SupplierID int, 
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
    )

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
    )

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]
        FROM dbo.fn_AO_Supplier_Period_Ageing
                (
                	@SupplierID, 
                	@M1, @Y1,
                	@M2, @Y2,
                	@M3, @Y3,
                	@M4, @Y4,
                	@M5, @Y5,
                	@M6, @Y6,
                	@M7, @Y7
                ) 
		GROUP BY SupplierID

        RETURN

	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Period_Procedure_Ageing_Non_Grouped
--Purpose       :Set Supplier Period Procedure Ageing Amounts between Procedure dates
--Calls         :fn_AW_Amount_of_Date_Between
--Date          :2007/03/06
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            FUNCTION fn_AO_Supplier_Period_Procedure_Ageing_Non_Grouped
    (
        @SupplierID int, 
        @ProcedureDate DateTime, 
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
    )

RETURNS @AgeTable TABLE 
    (
        [ID] int, 
        SupplierID int,
        [Date] datetime,
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money,
        [User] varchar(20)
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		AO_Transactions_ID as [ID], 
    		@SupplierID as SupplierID,
    		Document_Date,
    		Payment_Amount as Payment, 
    		Total_Amount as Amount, 
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D1,
                     @ProcedureDate,
                    (Total_Amount + Payment_Amount)
                ) as [Current],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D2,
                     @D1,
                     0
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D3,
                     @D2,
                     0
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D4,
                     @D3,
                     0
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D5,
                     @D4,
                     0
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D6,
                     @D5,
                     0
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Date_Between
                (
                    (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)),
                     Document_Date,
                     @D7,                     @D6,
                     0
                ) as [180+ Days],
            AW_Users.UserName AS [User]
    	FROM AO_Transactions
            LEFT JOIN AW_Users
                ON AO_Transactions.[User_ID] = AW_Users.AW_Users_ID
    	WHERE AO_Suppliers_ID = @SupplierID AND
             (Sys_AW_Transaction_Types_ID = 6 OR
              Sys_AW_Transaction_Types_ID = 8 OR
              Sys_AW_Transaction_Types_ID = 9 OR
              Sys_AW_Transaction_Types_ID = 10 OR
              Sys_AW_Transaction_Types_ID = 12) AND
              ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
              Document_Date <= @ProcedureDate

    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Procedure_Ageing_SUM_All
--Purpose       :Retrieves SUM of ALL Supplier Ageing Amounts by Date Captured
--              :    at Period Procedure Date
--Date          :2006/03/26
--Authors       :TB
--MODS:         :
--2004.2.7      :26/03/06 - Filter by Date Captured only
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AO_Supplier_Procedure_Ageing_SUM_All
    (
    	@CompanyID 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,
        @Date datetime
    )

RETURNS @AgeTable TABLE 
	(
    	[CompanyID] int,
    	[SupplierID] int,
        [MarkedToPay] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT
            t.AW_User_Companies_ID as [CompanyID],
            t.AO_Suppliers_ID as [SupplierID],
            SUM(t.To_Be_Paid_Amount) AS [MarkedToPay],
            SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                )) as [Current],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                )) as [30 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                )) as [60 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                )) as [90 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                )) as [120 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                )) as [150 Days],
    		SUM(dbo.fn_AW_Amount_of_Period
                (
                    ISNULL(t.Total_Amount, 0),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                )) as [180+ Days]

    	FROM AO_Transactions t
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               t.Date_Captured <= @Date
--               AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1
        GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Procedure_Period_Ageing
--Derived from  :    fn_AO_Supplier_Period_Procedure_Ageing_Non_Grouped
--Purpose       :Set Supplier Period Procedure Ageing Amounts between Accounting Periods
--Calls         :fn_AW_Amount_of_Period_Between
--Date          :2007/03/09
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              FUNCTION fn_AO_Supplier_Procedure_Period_Ageing
    (
        @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 
    (
        [ID] int, 
        SupplierID int,
        [Date] datetime,
        Payment money,
        Amount money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money,
        [User] varchar(20)
    )

AS

    BEGIN
    
    	INSERT @AgeTable

    	SELECT    
    		t.AO_Transactions_ID as [ID], 
    		@SupplierID as SupplierID,
    		t.Document_Date,
    		t.Payment_Amount as Payment, 
    		t.Total_Amount as Amount, 
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D1,
                     @D7
                ) as [Current],
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D2,
                     @D7
                ) as [30 Days],
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D3,
                     @D7
                ) as [60 Days],
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D4,
                     @D7
                ) as [90 Days],
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D5,
                     @D7
                ) as [120 Days],
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D6,
                     @D7
                ) as [150 Days],
            dbo.fn_AW_Amount_of_Period_Between
                (
                    (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                     t.Slu_AW_Months_ID,
                     t.Slu_AW_Years_ID,
                     @D7,
                     @D7
                ) as [180+ Days],
            u.UserName AS [User]
    	FROM AO_Transactions t
            LEFT JOIN AW_Users u
                ON t.[User_ID] = u.AW_Users_ID
    	WHERE t.AO_Suppliers_ID = @SupplierID AND
             (t.Sys_AW_Transaction_Types_ID = 6 OR
              t.Sys_AW_Transaction_Types_ID = 8 OR
              t.Sys_AW_Transaction_Types_ID = 9 OR
              t.Sys_AW_Transaction_Types_ID = 10 OR
              t.Sys_AW_Transaction_Types_ID = 12) AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
              dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    RETURN

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Total_Ageing
--Purpose       :Retrieves Total Supplier Ageing Amounts between each Age Area date
--NOTE          :ANY MOD ALSO TO BE INSERTED IN fn_AO_Supplier_Ageing_Non_Grouped
--Called by     :Manager Console
--Date          :2002/12/23
--Authors       :TB
--MODS:         :01/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
-------------------------------------------------------------------------------

CREATE                       FUNCTION fn_AO_Supplier_Total_Ageing
    (
    	@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
    )

RETURNS @AgeTable TABLE 
	(
    	[Amount] money,
    	[Payment] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT    
            t.Total_Amount as [Amount], 
            t.Payment_Amount as [Payment], 
            dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                ) as [Current],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                ) as [180+ Days]
    	FROM AO_Transactions t
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
               dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1
   
--                t.Slu_AW_Months_ID <= @M1 AND
--                t.Slu_AW_Years_ID <= @Y1

        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Total_Ageing_No_InterCo
--Purpose       :Retrieves Total Supplier Ageing Amounts between each Age Area date
--              :Excluding Inter-Company Suppliers
--NOTE          :ANY MOD ALSO TO BE INSERTED IN
--              :    fn_AO_Supplier_Total_Ageing
--              :    fn_AO_Supplier_Ageing_Non_Grouped
--Called by     :Manager Console
--Date          :2009/08/26
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                       FUNCTION fn_AO_Supplier_Total_Ageing_No_InterCo
    (
    	@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
    )

RETURNS @AgeTable TABLE 
	(
    	[Amount] money,
    	[Payment] money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money
    )

AS

    BEGIN

        DECLARE @Period1 varchar(6),
                @Period2 varchar(6),
                @Period3 varchar(6),
                @Period4 varchar(6),
                @Period5 varchar(6),
                @Period6 varchar(6),
                @Period7 varchar(6)
    
        SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
        SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
        SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
        SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
        SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
        SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
        SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    	INSERT @AgeTable
    
    	SELECT    
            t.Total_Amount as [Amount], 
            t.Payment_Amount as [Payment], 
            dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period1,
                    @Period7
                ) as [Current],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period2,
                    @Period7
                ) as [30 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period3,
                    @Period7
                ) as [60 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period4,
                    @Period7
                ) as [90 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period5,
                    @Period7
                ) as [120 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period6,
                    @Period7
                ) as [150 Days],
    		dbo.fn_AW_Amount_of_Period
                (
                   (ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)),
                    dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID),
                    @Period7,
                    @Period7
                ) as [180+ Days]
    	FROM AO_Transactions t
            INNER JOIN AO_Suppliers s
                ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
    	WHERE (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
               t.Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
               t.Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
               t.Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
               t.Sys_AW_Transaction_Types_ID = 12) AND     --Supplier Payment
               ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
               dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1 AND
               s.Sys_AC_Account_Types_ID <> 3


        RETURN

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_BFWD_Inventory_On_Hand
--Purpose       :Retrieves Opening Inventory On Hand BEFORE a date
--Parameters    :
--Date          :2004/10/09
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	2014-12-05	:Added transaction type 23 - Stock Transfer to sales query
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_BFWD_Inventory_On_Hand]
    (
        @ProductID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @GRV float,
                @ADJ float,
                @SALES float,
                @BFWD float

    -------------------------------------------------------------------------------
    -- GOODS RECEIVED
    -------------------------------------------------------------------------------
        SELECT @GRV = ISNULL(SUM(Qty), 0)
        FROM AO_GRV_Details
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured < @OpeningDate AND
              ISNULL(Qty, 0) <> 0
    -------------------------------------------------------------------------------
    -- ADJUSTMENTS
    -------------------------------------------------------------------------------
        SELECT @ADJ = ISNULL(SUM(ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0)), 0)
        FROM AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured < @OpeningDate AND
             (Sys_AP_Adjustment_Types_ID = 1 OR
              Sys_AP_Adjustment_Types_ID = 6) AND
              ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0
    -------------------------------------------------------------------------------
    -- SALES
    -------------------------------------------------------------------------------
        SELECT @SALES = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Date_Captured < @OpeningDate AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR			--Tax Invoice
              h.Sys_AW_Transaction_Types_ID = 4 OR			--Tax Credit Note
              h.Sys_AW_Transaction_Types_ID = 23 OR			--Stock Transfer
              h.Sys_AW_Transaction_Types_ID = 33 OR			--Consignment Note
              h.Sys_AW_Transaction_Types_ID = 34 OR			--Consignment Sold
              h.Sys_AW_Transaction_Types_ID = 35 ) AND		--Consignment Returned              
              ISNULL(d.Quantity, 0) <> 0
    -------------------------------------------------------------------------------


        SET @BFWD = @GRV + @ADJ - @SALES


        RETURN(@BFWD)

    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_CFWD_Inventory_On_Hand
--Purpose       :Retrieves Opening Inventory On Hand BEFORE a date
--Parameters    :
--Date          :2004/10/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE             FUNCTION dbo.fn_AP_CFWD_Inventory_On_Hand
    (
        @ProductID int,
        @ClosingDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @GRV float,
                @ADJ float,
                @SALES float,
                @CFWD float

    -------------------------------------------------------------------------------
    -- GOODS RECEIVED
    -------------------------------------------------------------------------------
        SELECT @GRV = ISNULL(SUM(Qty), 0)
        FROM AO_GRV_Details
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured <= @ClosingDate AND
              ISNULL(Qty, 0) <> 0
    -------------------------------------------------------------------------------
    -- ADJUSTMENTS
    -------------------------------------------------------------------------------
        SELECT @ADJ = ISNULL(SUM(ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0)), 0)
        FROM AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured <= @ClosingDate AND
             (Sys_AP_Adjustment_Types_ID = 1 OR
              Sys_AP_Adjustment_Types_ID = 6) AND
              ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0
    -------------------------------------------------------------------------------
    -- SALES
    -------------------------------------------------------------------------------
        SELECT @SALES = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Date_Captured <= @ClosingDate AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) and
              ISNULL(d.Quantity, 0) <> 0
    -------------------------------------------------------------------------------


        SET @CFWD = @GRV + @ADJ - @SALES


        RETURN(@CFWD)

    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Consignment_Stock_Qty
--Purpose       :Returns stock quantity on consignment
--Parameters    :
--Date          :2015/04/14
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Qty]
	(
        @ProductID int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = ISNULL(SUM(Qty), 0)
            FROM AO_GRV a
                INNER JOIN AO_GRV_Details d
                    ON a.AO_GRV_ID = d.AO_GRV_ID
            WHERE d.AP_Products_ID = @ProductID AND
				  a.Sys_AW_Transaction_Types_ID in (31, 32, 33, 34, 35) AND	
                  d.Slu_AW_Active_ID = 1 AND
                  a.Slu_AW_Active_ID = 1

    	RETURN @Qty
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Consignment_Stock_Returned
--Purpose       :Returns consignment quantity returned for a specific AS_Transaction_Detail_ID
--Parameters    :
--Date          :2015/05/21
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Returned]
	(
        @AS_Transaction_Details_ID int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = ABS(ISNULL(SUM(Quantity), 0))
            FROM AS_Transaction_Details_Consignment
            WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID AND
				  Sys_AW_Transaction_Types_ID = 35

    	RETURN @Qty
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Consignment_Stock_Sold
--Purpose       :Returns consignment quantity sold for a specific AS_Transaction_Detail_ID
--Parameters    :
--Date          :2015/05/21
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Sold]
	(
        @AS_Transaction_Detail_ID int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = ISNULL(SUM(Quantity), 0)
            FROM AS_Transaction_Details_Consignment
            WHERE AS_Transaction_Details_ID = @AS_Transaction_Detail_ID AND
				  Sys_AW_Transaction_Types_ID = 34

    	RETURN @Qty
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Discount_Price
--Purpose       :Returns stock quantity on consignment
--Parameters    :
--Date          :2015/04/14
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Discount_Price]
	(
        @Price							decimal(9,3),
        @Lup_AC_Discount_Categories_ID	int,
        @Lup_AP_Discount_Groups_ID		int
	)

RETURNS money

AS

	BEGIN
    	DECLARE @Discount_Percentage decimal(5,3)
    	DECLARE @Discount_Price		 decimal(9,3)

		SET @Discount_Percentage = 0
		
            SELECT @Discount_Percentage = ISNULL(Discount_Percentage, 0)
            FROM AS_Discount_Categories_Groups d
            WHERE d.Lup_AP_Discount_Groups_ID = @Lup_AP_Discount_Groups_ID AND
				  d.Lup_AC_Discount_Categories_ID = @Lup_AC_Discount_Categories_ID AND
                  d.Slu_AW_Active_ID = 1 

			SET @Discount_Price = @Price - ( (@Price / 100) * @Discount_Percentage)

    	RETURN @Discount_Price
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Last_Purchase_Date
--Purpose       :Returns Product Last Purchase Date
--Parameters    :
--Date          :2007/05/22
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             FUNCTION dbo.fn_AP_Get_Last_Purchase_Date
	(
        @ProductID int
	)

RETURNS datetime

AS

	BEGIN

        DECLARE @PurchaseDate datetime


        SELECT TOP 1 @PurchaseDate = h.Date_Received
        FROM AO_GRV h
            INNER JOIN AO_GRV_Details d
                ON h.AO_GRV_ID = d.AO_GRV_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Sys_AW_Transaction_Types_ID = 19
        ORDER BY h.Date_Received DESC
    
  
    	RETURN @PurchaseDate

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Last_Purchase_Qty
--Purpose       :Returns Product Last Purchase Qty
--Parameters    :
--Date          :2008/04/08
--Authors       :TB
--MODS          :
--2004.4.5      :28/05/09 - Removed superflous SELECT @PurchasedDate
-------------------------------------------------------------------------------

CREATE               FUNCTION dbo.fn_AP_Get_Last_Purchase_Qty
	(
        @ProductID int
	)

RETURNS decimal(12, 3)

AS

	BEGIN

        DECLARE @PurchaseQty decimal(12, 3)


        SELECT TOP 1 @PurchaseQty = ISNULL(d.Qty, 0)
        FROM AO_GRV h
            INNER JOIN AO_GRV_Details d
                ON h.AO_GRV_ID = d.AO_GRV_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Sys_AW_Transaction_Types_ID = 19
        ORDER BY h.Date_Received DESC
    
  
    	RETURN @PurchaseQty

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Last_Sale_Date
--Purpose       :Returns Product Last Sale Date
--Parameters    :
--Date          :2007/05/22
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             FUNCTION dbo.fn_AP_Get_Last_Sale_Date
	(
        @ProductID int
	)

RETURNS datetime

AS

	BEGIN

        DECLARE @SaleDate datetime


        SELECT TOP 1 @SaleDate = h.Transaction_Date
        FROM AS_Transactions h
            INNER JOIN AS_Transaction_Details d
                ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Sys_AW_Transaction_Types_ID = 3
        ORDER BY h.Transaction_Date DESC
    
  
    	RETURN @SaleDate

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :fn_AP_Get_Product_Bin_Job_Reserved
--Purpose       :SUM all JOB CARD for one Product and Bin
--Parameters    :
--Date          :2015/05/09
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [fn_AP_Get_Product_Bin_Job_Reserved]
    (
        @ProductID		int,
        @ProductBinID	int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD 
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1
		AND ISNULL(Lup_AP_Product_Bins_ID,0) = @ProductBinID
		AND (h.Sys_AW_Transaction_Types_ID = 2)
              
	RETURN(@ReservedQTY)
   
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Product_Bin_Qty
--Purpose       :Returns stock quantity in a Bin
--Parameters    :
--Date          :2015-11-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Product_Bin_Qty]
	(
        @ProductID					int,
        @Lup_AP_Product_Bins_ID		int,
        @AW_User_Companies_ID		int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)
		SET @Qty = 0
		
            SELECT @Qty = ISNULL(On_Hand, 0)
            FROM AP_Products_Bins
            WHERE AP_Products_ID = @ProductID AND
				  Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID AND
				  AW_User_Companies_ID = @AW_User_Companies_ID

    	RETURN @Qty
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Product_Cost
--Purpose       :Returns product cost depending on system setting
--Parameters    :
--Date          :2015/07/05
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Product_Cost]
	(
        @AP_Products_ID int
	)

RETURNS decimal(9,3)

AS

BEGIN
    DECLARE @Cost			money,
			@CostingMethod	int

	SET @CostingMethod = 0
	SELECT @CostingMethod = Control_Index 
	FROM Sys_AW_Options 
	WHERE Control_Name = 'optInventoryValuation' 
	AND Control_Value = 'True'

	--0 - Average Cost
	--1	- Last Cost
	--2 - Standard Cost
	IF @CostingMethod IS NULL
		SET @CostingMethod = 0
		
	IF @CostingMethod = 0
	BEGIN
		SELECT @Cost = ISNULL(Average_Cost,0)
		FROM AP_Products
		WHERE AP_Products_ID = @AP_Products_ID
	END

	IF @CostingMethod = 1
	BEGIN
		SELECT @Cost = ISNULL(Last_Cost,0)
		FROM AP_Products
		WHERE AP_Products_ID = @AP_Products_ID
	END
	
	IF @CostingMethod = 2
	BEGIN
		SELECT @Cost = ISNULL(Standard_Cost,0)
		FROM AP_Products
		WHERE AP_Products_ID = @AP_Products_ID
	END		

  	RETURN @Cost
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Products_Out_On_Consignment
--Purpose       :Returns quantity of how many units are out on Consignment
--Parameters    :
--Date          :2015/06/10
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Products_Out_On_Consignment]
	(
        @ProductID int
	)
RETURNS decimal(9,3)

AS
    BEGIN

        DECLARE @OutOnConsignmentQTY decimal(9,3)

    -------------------------------------------------------------------------------
    --Stock Out On Consignment
    -------------------------------------------------------------------------------
        SELECT @OutOnConsignmentQTY = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 33 OR
              h.Sys_AW_Transaction_Types_ID = 34 OR
              h.Sys_AW_Transaction_Types_ID = 35)
              
    -------------------------------------------------------------------------------

        RETURN(@OutOnConsignmentQTY)
    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Sales_Promotion_Price
--Purpose       :Returns Promotion Price if a product is on promotion
--Parameters    :
--Date          :2004/02/26
--Authors       :TB
--Version       :1.0.0
--MODS          :27/02/04 - Added Slu_AW_Active_ID filter on Product and Promotion 
--              :28/02/04 - Added ORDER BY a.AP_Promotion_Products_ID
-------------------------------------------------------------------------------

CREATE              FUNCTION fn_AP_Get_Sales_Promotion_Price
	(
        @ProductID int,
        @Date datetime
	)

RETURNS money

AS

	BEGIN
        DECLARE @Today datetime,
                @PromoPrice money

        SET @Today = CONVERT(datetime, CONVERT(char(10), @Date, 121))
    
        SELECT TOP 1 @PromoPrice = ISNULL(a.Selling_Price, 0)
        FROM AP_Promotion_Products a
            LEFT JOIN AP_Promotions b
                ON a.AP_Promotions_ID = b.AP_Promotions_ID
        WHERE a.AP_Products_ID = @ProductID AND
             (@Today >= a.Start_Date AND                 -- If PRODUCT still running
              @Today <= a.End_Date) AND                  -- AND
             (@Today >= b.Start_Date AND                 -- If PROMOTION still running
              @Today <= b.End_Date) AND                  -- AND
             (a.Slu_AW_Active_ID = 1 AND                 -- If PRODUCT still ACTIVE
              b.Slu_AW_Active_ID = 1) AND                -- If PROMOTION still ACTIVE
              a.Qty_Sold < a.Qty_Cutoff                  -- AND not SOLD OUT
        ORDER BY a.AP_Promotion_Products_ID
    
  
    	RETURN @PromoPrice


    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Sales_Promotion_Product_ID
--Purpose       :Returns Promotion ProductID if a product is on promotion
--Parameters    :
--Date          :2004/02/26
--Authors       :TB
--Version       :1.0.0
--MODS          :27/02/04 - Added Slu_AW_Active_ID filter on Product and Promotion 
--              :28/02/04 - Added ORDER BY a.AP_Promotion_Products_ID
--2004.3.9      :10/06/08 - Changed DECLARE @PromoProductID from money to int
--              :           because that is what is defined in AP_Promotion_Products
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AP_Get_Sales_Promotion_Product_ID
	(
        @ProductID int,
        @Date datetime
	)

RETURNS int

AS

	BEGIN
        DECLARE @Today datetime,
                @PromoProductID int

        SET @Today = CONVERT(datetime, CONVERT(char(10), @Date, 121))
    
        SELECT TOP 1 @PromoProductID = ISNULL(a.AP_Promotion_Products_ID, -1)
        FROM AP_Promotion_Products a
            LEFT JOIN AP_Promotions b
                ON a.AP_Promotions_ID = b.AP_Promotions_ID
        WHERE a.AP_Products_ID = @ProductID AND
             (@Today >= a.Start_Date AND                 -- If PRODUCT still running
              @Today <= a.End_Date) AND                  -- AND
             (@Today >= b.Start_Date AND                 -- If PROMOTION still running
              @Today <= b.End_Date) AND                  -- AND
             (a.Slu_AW_Active_ID = 1 AND                 -- If PRODUCT still ACTIVE
              b.Slu_AW_Active_ID = 1) AND                -- If PROMOTION still ACTIVE
              a.Qty_Sold < a.Qty_Cutoff                  -- AND not SOLD OUT
        ORDER BY a.AP_Promotion_Products_ID
    
  
    	RETURN @PromoProductID


    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Product_Has_Movement
--Purpose       :Returns BOOLEAN if Product has any movement
--Parameters    :
--Date          :2004/10/16
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE              FUNCTION dbo.fn_AP_Product_Has_Movement
	(
        @ProductID int
	)

RETURNS bit

AS

    BEGIN
        IF EXISTS
            (
                SELECT TOP 1 AP_Products_ID
                FROM AO_GRV_Details
                WHERE AP_Products_ID = @ProductID AND
                      ISNULL(Qty, 0) <> 0
            )
            RETURN 1
        ELSE
        IF EXISTS
            (
                SELECT TOP 1 AP_Products_ID
                FROM AP_Inventory_Adjustments
                WHERE AP_Products_ID = @ProductID AND
                     (Sys_AP_Adjustment_Types_ID = 1 OR
                      Sys_AP_Adjustment_Types_ID = 6) AND
                      ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0
            )
           	RETURN 1
        ELSE
        IF EXISTS
            (
                SELECT TOP 1 AP_Products_ID
                FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h
                        ON d.AS_Transactions_ID = h.AS_Transactions_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                      ISNULL(d.Quantity, 0) <> 0
            )
           	RETURN 1

        RETURN 0
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AP_Product_Has_Movement_Period
--Purpose       :Returns BOOLEAN if Product had movement in Last m Months to d Date
--Functionality :Defaults to movement in LAST 1 month
--Date          :2005/05/22
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AP_Product_Has_Movement_Period
	(
        @ProductID int,
        @Date datetime,
        @Months int = 1
	)

RETURNS bit

AS

    BEGIN
        IF EXISTS
            (
                SELECT TOP 1 d.AP_Products_ID
                FROM AO_GRV_Details d
                     INNER JOIN AO_GRV h
                         ON h.AO_GRV_ID = d.AO_GRV_ID
                WHERE d.AP_Products_ID = @ProductID AND
                      ISNULL(d.Qty, 0) <> 0 AND
                      h.Date_Received >= DATEADD(m, -@Months, @Date)
            )
            RETURN 1
        ELSE
        IF EXISTS
            (
                SELECT TOP 1 AP_Products_ID
                FROM AP_Inventory_Adjustments
                WHERE AP_Products_ID = @ProductID AND
                     (Sys_AP_Adjustment_Types_ID = 1 OR
                      Sys_AP_Adjustment_Types_ID = 6) AND
                      ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0 AND
                      Date_Captured >= DATEADD(m, -@Months, @Date)
            )
           	RETURN 1
        ELSE
        IF EXISTS
            (
                SELECT TOP 1 AP_Products_ID
                FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h
                        ON d.AS_Transactions_ID = h.AS_Transactions_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                      ISNULL(d.Quantity, 0) <> 0 AND
                      h.Transaction_Date >= DATEADD(m, -@Months, @Date)
            )
           	RETURN 1

        RETURN 0
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_Products_Job_Reserved
--Purpose       :SUM all JOB CARD for one Product
--Parameters    :
--Date          :2014/05/22
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Products_Job_Reserved]
    (
        @ProductID int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD 
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1 
		AND (h.Sys_AW_Transaction_Types_ID = 2)
              
	RETURN(@ReservedQTY)
   
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_Products_Quoted
--Purpose       :SUM all Quotes for one Product
--Parameters    :
--Date          :2014/05/22
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Products_Quoted]
    (
        @ProductID int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- Quotes
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1 
		AND (h.Sys_AW_Transaction_Types_ID = 1)
              
	RETURN(@ReservedQTY)
   
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_Products_Sales_Order_Reserved
--Purpose       :SUM all Sales Orders for one Product
--Parameters    :
--Date          :2014/05/22
--Authors       :RL
--MODS          :
----V6.3	RL	2017-05-04	:Added Back Order Qty on Sales Orders
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Products_Sales_Order_Reserved]
    (
        @ProductID int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- Sales Order
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity + d.Back_Order), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1 
		AND (h.Sys_AW_Transaction_Types_ID = 16)
              
	RETURN(@ReservedQTY)
   
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_Reserved
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product
--Parameters    :
--Date          :2006/12/13
--Authors       :TB
--MODS          :
--V6.3	RL	2017-04-21	:Added Back order amount for Sales Orders
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_SUM_Product_Job_Reserved]
    (
        @ProductID int
    )

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        SELECT @ReservedQTY = ISNULL(SUM(d.Quantity + d.Back_Order), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_Reserved_Bin
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product per Bin
--Parameters    :
--Date          :2017-05-15
--Authors       :RL
--MODS          :
--V6.3	RL	2017-04-21	:Added Back order amount for Sales Orders
--V6.3	RL	2017-05-15	:Added Bin Check
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_SUM_Product_Job_Reserved_Bin]
    (
        @ProductID	int,
        @BinID		int
    )

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        SELECT @ReservedQTY = ISNULL(SUM(d.Quantity + d.Back_Order), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Slu_AW_Active_ID = 1 AND
              d.Lup_AP_Product_Bins_ID = @BinID AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product excluding back orders
--Parameters    :
--Date          :2017/10/10
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO]
    (
        @ProductID	int,
        @BinID		int
    )

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Slu_AW_Active_ID = 1 AND
              d.Lup_AP_Product_Bins_ID = @BinID AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_SO_Reserved_NO_BO
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product excluding back orders
--Parameters    :
--Date          :2017/10/10
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_NO_BO]
    (
        @ProductID int
    )

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Qty_ADJ
--Purpose       :SUM all SALES for one Product FROM a DATE
--Parameters    :
--Date          :2004/10/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AP_SUM_Product_Qty_ADJ
    (
        @ProductID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @ADJ float

    -------------------------------------------------------------------------------
    -- ADJUSTMENTS
    -------------------------------------------------------------------------------
        SELECT @ADJ = ISNULL(SUM(ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0)), 0)
        FROM AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured >= @OpeningDate AND
             (Sys_AP_Adjustment_Types_ID = 1 OR
              Sys_AP_Adjustment_Types_ID = 6) AND
              ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0
    -------------------------------------------------------------------------------


        RETURN(@ADJ)

    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Qty_GRV
--Purpose       :SUM all SALES for one Product FROM a DATE
--Parameters    :
--Date          :2004/10/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AP_SUM_Product_Qty_GRV
    (
        @ProductID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @GRV float

    -------------------------------------------------------------------------------
    -- GOODS RECEIVED
    -------------------------------------------------------------------------------
        SELECT @GRV = ISNULL(SUM(Qty), 0)
        FROM AO_GRV_Details
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured >= @OpeningDate AND
              ISNULL(Qty, 0) <> 0
    -------------------------------------------------------------------------------


        RETURN(@GRV)

    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Qty_SALE
--Purpose       :SUM all SALES for one Product FROM a DATE
--Parameters    :
--Date          :2004/10/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AP_SUM_Product_Qty_SALE
    (
        @ProductID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @SALES float

    -------------------------------------------------------------------------------
    -- SALES
    -------------------------------------------------------------------------------
        SELECT @SALES = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Date_Captured >= @OpeningDate AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
              d.Quantity <> 0
    -------------------------------------------------------------------------------


        RETURN(@SALES)

    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-----------------------------------------------------------------------------
--Description   :fn_AP_Sales_Promotion_Top_20_Perc
--Purpose       :Select Top 20% Best Sellers for Sales Promotions
--Functionality :
--Parameters    :
--Date          :2004/02/19
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE            FUNCTION fn_AP_Sales_Promotion_Top_20_Perc
    (
		@CompanyID int,
        @Today datetime
    )

RETURNS @Sales_Table TABLE 
	    (
            [ID] int,
            [SupplierID] int,
            [Product] varchar(50),
            [Code] varchar(20),
            [Last Sale] varchar(10),
            [Sold] decimal(9,3),
            [On Hand] decimal(9,3),
            [Ords] decimal(9,3),
            [Pend] decimal(9,3),
            [Selling 1] money,
            [Selling 2] money,
            [Last Cost] money,
            [Avg Cost] money,
            [GP %] float,
            [MSL] decimal(9,3),
            [MIN] decimal(9,3),
            [MAX] decimal(9,3),
            [SL] decimal(9,3),
            [Pack] decimal(9,3)
        )

AS

BEGIN

--   	DECLARE @StartDate datetime,
--             @EndDate datetime,
--             @StartPeriodNo int,
--             @EndPeriodNo int
-- 
--     SET @StartDate = DATEADD(Week, -24, @Today)
--     SET @EndDate = @Today
--     SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
--     SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

    DECLARE @StartDate datetime,
            @EndDate datetime

    SET @EndDate = @Today
    SET @StartDate = DATEADD(Week, -24, @EndDate)

        INSERT @Sales_Table
    
        SELECT TOP 20 PERCENT WITH TIES
            MAX(p.AP_Products_ID) as [ID],
            MAX(p.Default_Supplier_ID) AS [SupplierID],
            MAX(p.Description) AS [Product], 
            MAX(p.Product_Code) AS [Code],  
            MAX(CONVERT(CHAR(10), p.Last_Sale_Date, 121)) AS [Last Sale], 
            SUM(d.Quantity) AS [Sold],
            MAX(p.On_Hand) AS [On Hand],

            --> On Order
            (
                SELECT
                    CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                         THEN 0
                         ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                         END
                    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 = p.AP_Products_ID
               ) AS [Ords],
            
            --> Pending Orders
            (
                SELECT
                    CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                         THEN 0
                         ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty))
                         END
                    FROM AO_Order_Details od
                        INNER JOIN AO_Orders o
                            ON od.AO_Orders_ID = o.AO_Orders_ID
                    WHERE o.Date_Ordered IS NULL AND
                          od.AP_Products_ID = p.AP_Products_ID
            ) AS [Pend],
            
            MAX(dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, @Today)) as [Selling 1],
            MAX(dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, @Today)) as [Selling 2],
            
            MAX(p.Last_Cost) AS [Last Cost],
            MAX(p.Average_Cost) AS [Avg Cost], 
            
            MAX(dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, @Today, p.Last_Cost)) as [GP %],
            MAX(p.Min_Stock_Level) AS [MSL], 
            MAX(p.Min_Order_Qty) AS [MIN], 
            MAX(p.Max_Order_Qty) AS [MAX], 
            MAX(p.Service_Level) AS [SL],
            MAX(p.Pack_Size) AS [Pack]
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
            INNER JOIN AP_Products p
                ON d.AP_Products_ID = p.AP_Products_ID
        WHERE d.AW_User_Companies_ID = @CompanyID AND
             (h.Transaction_Date > @StartDate AND
              h.Transaction_Date <= @EndDate) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
              p.Slu_AW_YesNo_Non_Stock_Item = 0 
        GROUP BY p.AP_Products_ID
        ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
    
    RETURN 

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

--Description   : fn_AP_Top100Perc_Products_GP
--Purpose       : FUNCTION TO EXTRACT Top 100% Products
--              : By Gross Profit
--Parameters    :
--Date          : 22 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Top100Perc_Products_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Product_GP_Table TABLE 
	(
        [ID] int,
        [Product] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Code] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
     IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Product_GP_Table
        
            SELECT TOP 100 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Product_GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

--Description   : fn_AP_Top20Perc_Products_GP
--Purpose       : FUNCTION TO EXTRACT Top 20% Products
--              : By Gross Profit
--Parameters    :
--Date          : 22 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE           FUNCTION [dbo].[fn_AP_Top20Perc_Products_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Product_GP_Table TABLE 
	(
        [ID] int,
        [Product] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Code] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
     IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Product_GP_Table
        
            SELECT TOP 20 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Product_GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

--Description   : fn_AP_Top50Perc_Products_GP
--Purpose       : FUNCTION TO EXTRACT Top 50% Products
--              : By Gross Profit
--Parameters    :
--Date          : 22 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE           FUNCTION [dbo].[fn_AP_Top50Perc_Products_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Product_GP_Table TABLE 
	(
        [ID] int,
        [Product] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Code] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
     IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Product_GP_Table
        
            SELECT TOP 50 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Product_GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--USER FUNCTION dbo.fn_AS_Calc_Act_GP
--Returns Actual GP on a Sales Transaction Detail item
--Used in sp_AS_4030 (Demand Forecasting)
--TB 10 AUG 2001

CREATE  FUNCTION dbo.fn_AS_Calc_Act_GP
    (
        @Extended_Amount money,
        @Tax_Amount money,
        @Quantity decimal(9,3),
        @Unit_Cost money
    )

RETURNS money

AS

BEGIN

    DECLARE @Result money

    SET @Result = (@Extended_Amount - @Tax_Amount) - (@Quantity * @Unit_Cost)

    RETURN(@Result)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--USER FUNCTION dbo.fn_AS_Calc_Act_Sales_Value
--Returns Actual Sales on a Sales Transaction Detail item
--Used in sp_AS_4030 (Demand Forecasting)
--TB 10 AUG 2001

CREATE FUNCTION dbo.fn_AS_Calc_Act_Sales_Value
    (
        @Extended_Amount money,
        @Tax_Amount money
    )

RETURNS money

AS

BEGIN

    DECLARE @Result money

    SET @Result = @Extended_Amount - @Tax_Amount

    RETURN(@Result)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--USER FUNCTION dbo.fn_AS_Calc_Std_GP
--Returns Standard GP on a Sales Transaction Detail item
--Used in sp_AS_4030 (Demand Forecasting)
--TB 10 AUG 2001

CREATE  FUNCTION dbo.fn_AS_Calc_Std_GP
    (
        @Original_Amount money,
        @Unit_Cost money,
        @Quantity decimal(9,3)
    )

RETURNS money

AS

BEGIN

    DECLARE @Result money

    SET @Result = (@Original_Amount - @Unit_Cost) * @Quantity

    RETURN(@Result)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--USER FUNCTION dbo.fn_AS_Calc_Std_Sales_Value
--Returns Actual Sales on a Sales Transaction Detail item
--Used in sp_AS_4030 (Demand Forecasting)
--TB 10 AUG 2001

CREATE FUNCTION dbo.fn_AS_Calc_Std_Sales_Value
    (
        @Original_Amount money,
        @Quantity decimal(9,3)
    )

RETURNS money

AS

BEGIN

    DECLARE @Result money

    SET @Result = @Original_Amount * @Quantity

    RETURN(@Result)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Get_Day_Number
--Purpose       :Returns DAY(5) and Day(2) as 7-digit integer
--              :for SalesAnalyst
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          :31 OCT 2002
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AS_Get_Day_Number
    (
        @TranDate datetime
    )

RETURNS int

AS

    BEGIN
    
        DECLARE @DayNo varchar(5),
                @DayStr varchar(5)

    --> ROUND using ,0 ,1 with float TRUNCATES date and does NOT it round up
        SET @DayNo = CONVERT(varchar(5), ROUND(CONVERT(float, @TranDate), 0, 1))
    
        RETURN(CONVERT(int, @DayNo))
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Get_Hour_Number
--Purpose       :Returns DAY(5) and HOUR(2) as 7-digit integer
--              :for SalesAnalyst
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          :31 OCT 2002
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE               FUNCTION dbo.fn_AS_Get_Hour_Number
    (
        @DayNo varchar(5),
        @TranDate datetime
    )

RETURNS int

AS

    BEGIN
    
        DECLARE @HourNo varchar(2),
                @HourStr varchar(7)
    
        SET @HourNo = RTRIM(LTRIM(CONVERT(varchar(2),DATEPART(Hour,@TranDate))))
    
        IF LEN(@HourNo) = 1
            SET @HourNo = '0' + @HourNo
    
        SET @HourStr = @DayNo + @HourNo
    
        RETURN(CONVERT(int, @HourStr))
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Get_MonthYear_Number
--Purpose       :Returns MONTH(2) and YEAR(4) as 6-digit integer
--Used in       :Order Analysis Report
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          :11 APR 2003
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AS_Get_MonthYear_Number
    (
        @date datetime
    )

--RETURNS int
RETURNS varchar(6)

AS

BEGIN
    DECLARE @monthstr varchar(2),
            @yearstr varchar(4),
            @DateNo varchar(6)

    SET @yearstr = CONVERT(varchar(4), DATEPART(YEAR, @date))
    SET @monthstr = RTRIM(LTRIM(CONVERT(varchar(2), DATEPART(MONTH, @date))))

    IF LEN(@monthstr) = 1
        set @monthstr = '0' + @monthstr

    SET @DateNo = @monthstr + @yearstr

--    RETURN(CONVERT(int, @DateNo))
    RETURN @DateNo
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Get_Month_Number
--Purpose       :Returns YEAR(4) and MONTH(2) as 6-digit integer
--Used in       :sp_AO_4010 (Demand Forecasting)
--              :for SalesAnalyst
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          :30 APR 2001
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE      FUNCTION dbo.fn_AS_Get_Month_Number
    (
        @date datetime
    )

RETURNS int

AS

BEGIN
    DECLARE @monthstr varchar(2),
            @yearstr varchar(4),
            @DateNo varchar(6)

    SET @yearstr = CONVERT(varchar(4), DATEPART(YEAR, @date))
    SET @monthstr = RTRIM(LTRIM(CONVERT(varchar(2), DATEPART(MONTH, @date))))

    IF LEN(@monthstr) = 1
        set @monthstr = '0' + @monthstr

    SET @DateNo = @yearstr + @monthstr

    RETURN(CONVERT(int, @DateNo))
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Get_MonthYear_Number
--Purpose       :Returns YEAR(4) and MONTH(2) as 6-digit integer
--Used in       :Order Analysis Report
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          :25 SEP 2003
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AS_Get_YearMonth_Number
    (
        @date datetime
    )

--RETURNS int
RETURNS varchar(6)

AS

BEGIN
    DECLARE @monthstr varchar(2),
            @yearstr varchar(4),
            @DateNo varchar(6)

    SET @yearstr = CONVERT(varchar(4), DATEPART(YEAR, @date))
    SET @monthstr = RTRIM(LTRIM(CONVERT(varchar(2), DATEPART(MONTH, @date))))

    IF LEN(@monthstr) = 1
        set @monthstr = '0' + @monthstr

    SET @DateNo = @yearstr + @monthstr

--    RETURN(CONVERT(int, @DateNo))
    RETURN @DateNo
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Product_Has_Sales
--Purpose       :Returns SCALAR bit if Product has sales between two dates
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2003/10/12
--Authors       :TB
--MODS          :
--2004.4.9      :03/10/10 - Added TRANSACTION TYPE 23 - Stock Transfers
-----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AS_Product_Has_Sales
	(
		@CompanyID int,
        @FromDate datetime,
        @ToDate datetime
	)

RETURNS bit

AS
	BEGIN

	DECLARE @Test bit

	IF Exists
            (
                SELECT TOP 1 AP_Products_ID
                FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h
                        ON d.AS_Transactions_ID = h.AS_Transactions_ID
                WHERE h.AW_User_Companies_ID = @CompanyID AND
                     (h.Transaction_Date > @FromDate AND
                      h.Transaction_Date <= @ToDate) AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4 OR
                      h.Sys_AW_Transaction_Types_ID = 23)
            )
        SET @Test = 1
	ELSE	
		SET @Test = 0

	RETURN @Test
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AS_Product_Has_Sales_Transactions
--Purpose       :Returns SCALAR bit if Product has sales between two dates
--              :FOR DEBTOR SALES TRANSACTION TYPES
--Date          :2005/10/11
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AS_Product_Has_Sales_Transactions
	(
		@CompanyID int,
        @ProductID int
	)

RETURNS bit

AS
	BEGIN

	DECLARE @Test bit

	IF Exists
            (
                SELECT TOP 1 AP_Products_ID
                FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h
                        ON d.AS_Transactions_ID = h.AS_Transactions_ID
                WHERE h.AW_User_Companies_ID = @CompanyID AND
                      d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                      h.Sys_AW_Transaction_Types_ID = 4)     --Refund
            )
        SET @Test = 1
	ELSE	
		SET @Test = 0

	RETURN @Test
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   : fn_AS_Top100Perc_Customers_GP
--Purpose       : FUNCTION TO EXTRACT Top 100% Customers
--              : By Gross Profit WITHIN THE LAST 1 YEAR
--Parameters    :
--Date          : 08 JUL 2001
--Authors       : TB
--Version       : 1.0.0
--MODS          :13/05/02 - Fixed overflow error with: LEFT([Customer Name],50) 
--              :05/07/04 - Renamed [Customer Number] field to [Number]
-------------------------------------------------------------------------------

CREATE             FUNCTION [dbo].[fn_AS_Top100Perc_Customers_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [ID] int,
        [Customer Name] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table
        
            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top100Perc_Customers_GP_Extended
--Purpose       :EXTRACT Top 100% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2004/07/07
--Authors       :TB
--MODS          :16/03/06 - Added extract LEFT of varchars to eliminate TRUNCATE
-------------------------------------------------------------------------------

CREATE               FUNCTION [dbo].[fn_AS_Top100Perc_Customers_GP_Extended]
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Send E-mail] tinyint,
        [Customer] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact E-mail] varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact Cell] varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Box] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Office] varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Code] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top100Perc_Customers_GP_Mail_Merge
--Purpose       :EXTRACT Top 100% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2007/12/07
--Authors       :TB
--MODS          :
--2004.4.5      :10/07/09 - Added Delivery Address and Head Office fields
-------------------------------------------------------------------------------

CREATE                  FUNCTION fn_AS_Top100Perc_Customers_GP_Mail_Merge
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Selected] tinyint,
        [Customer] varchar(100),
        [Number] varchar(10),
        [Fax Number] varchar(16),
        [Contact E-mail] varchar(40),
        [Pricipal] varchar(50),
        [Contact] varchar(30),
        [Post Box] varchar(20),
        [Post Office] varchar(30),
        [Post Code] varchar(10),
        [Street Address] varchar(40),
        [Suburb] varchar(30),
        [City] varchar(30),
        [Street Code] varchar(10),
        [Delivery Address] varchar(40),
        [Delivery Suburb] varchar(40),
        [Delivery City] varchar(30),
        [Delivery Code] varchar(10),
        [Head Office] varchar(50)
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Selected],
                MAX(CASE WHEN Firstnames IS NULL
                        THEN ISNULL(Surname, '')
                        ELSE ISNULL(Surname, '') + ', ' + LTRIM(ISNULL(Firstnames, ''))
                        END) AS [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Fax_No), 16) AS [Fax Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                          THEN ISNULL(c.Principal_Name, '')
                          ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                     END), 50) AS [Principal],
                LEFT(MAX(c.Contact_Name), 30) AS [Contact],
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code],
                LEFT(MAX(c.Street_Address), 40) AS [Street Address], 
                LEFT(MAX(c.Suburb), 30) AS [Suburb],
                LEFT(MAX(c.City), 30) AS [City],
                LEFT(MAX(c.Street_Post_Code), 10) AS [Street Code],
                LEFT(MAX(c.Delivery_Address), 40) AS [Delivery Address], 
                LEFT(MAX(c.Delivery_Suburb), 40) AS [Delivery Suburb],
                LEFT(MAX(c.Delivery_City), 30) AS [Delivery City],
                LEFT(MAX(c.Delivery_Post_Code), 10) AS [Delivery Code],
                LEFT(MAX(c.Head_Office), 50) AS [Head Office]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Selected],
                MAX(CASE WHEN Firstnames IS NULL
                        THEN ISNULL(Surname, '')
                        ELSE ISNULL(Surname, '') + ', ' + LTRIM(ISNULL(Firstnames, ''))
                        END) AS [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Fax_No), 16) AS [Fax Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                          THEN ISNULL(c.Principal_Name, '')
                          ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                     END), 50) AS [Principal],
                LEFT(MAX(c.Contact_Name), 30) AS [Contact],
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code],
                LEFT(MAX(c.Street_Address), 40) AS [Street Address], 
                LEFT(MAX(c.Suburb), 30) AS [Suburb],
                LEFT(MAX(c.City), 30) AS [City],
                LEFT(MAX(c.Street_Post_Code), 10) AS [Street Code],
                LEFT(MAX(c.Delivery_Address), 40) AS [Delivery Address], 
                LEFT(MAX(c.Delivery_Suburb), 40) AS [Delivery Suburb],
                LEFT(MAX(c.Delivery_City), 30) AS [Delivery City],
                LEFT(MAX(c.Delivery_Post_Code), 10) AS [Delivery Code],
                LEFT(MAX(c.Head_Office), 50) AS [Head Office]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-->> FUNCTION TO EXTRACT Top 100% Top Sales Transactions Sellers
-->> By Gross Profit
-->> TB 06 JUL 2001

CREATE   FUNCTION fn_AS_Top100Perc_Sales_Tran_GP
    (
		@CompanyID int,
        @FromDate datetime,
        @ToDate datetime
    )
RETURNS @Sales_Table TABLE 
	(ID int,
    	Description varchar(50),
    	 Code varchar(20))
AS

BEGIN
	INSERT @Sales_Table

    SELECT TOP 100 PERCENT WITH TIES
        p.AP_Products_ID as [ID],
        MAX(p.Description) as [Description],
        MAX(p.Product_Code) as [Code]

    FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
            INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AW_User_Companies_ID = @CompanyID AND
         (h.Transaction_Date > @FromDate AND
          h.Transaction_Date <= @ToDate) AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4)
    GROUP BY p.AP_Products_ID
    ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC

	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-->> FUNCTION TO EXTRACT Top 100% Top Sales Transactions Sellers
-->> By Sales Value
-->> TB 06 JUL 2001

CREATE     FUNCTION fn_AS_Top100Perc_Sales_Tran_Value
    (
		@CompanyID int,
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Sales_Table TABLE 
    	(ID int,
         Description varchar(50),
         Code varchar(20))
AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Sales_Table
        
            SELECT TOP 100 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Description],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Sales_Table

            SELECT TOP 100 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Description],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
        END
    RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top20Perc_Customers_GP
--Purpose       :FUNCTION TO EXTRACT Top 20% Customers
--              :By Gross Profit WITHIN THE LAST 1 YEAR
--Parameters    :
--Date          :1 JUL 2001
--Authors       :TB
--Version       :1.0.0
--MODS          :13/05/02 - Fixed overflow error with: LEFT([Customer Name],50) 
--              :05/07/04 - Renamed [Customer Number] field to [Number]
-------------------------------------------------------------------------------

CREATE                FUNCTION fn_AS_Top20Perc_Customers_GP
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [ID] int,
        [Customer Name] varchar(50),
        [Number] varchar(20)
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table
        
            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top20Perc_Customers_GP_Extended
--Purpose       :EXTRACT Top 20% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2004/07/07
--Authors       :TB
--MODS          :16/03/06 - Added extract LEFT of varchars to eliminate TRUNCATE
-------------------------------------------------------------------------------

CREATE               FUNCTION [dbo].[fn_AS_Top20Perc_Customers_GP_Extended]
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Send E-mail] tinyint,
        [Customer] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact E-mail] varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact Cell] varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Box] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Office] varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Code] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN

  	DECLARE @StartWeekNo int, @EndWeekNo int


    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top20Perc_Customers_GP_Mail_Merge
--Purpose       :EXTRACT Top 20% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2007/12/07
--Authors       :TB
--MODS          :
--2004.4.5      :10/07/09 - Added Delivery Address and Head Office fields
-------------------------------------------------------------------------------

CREATE                  FUNCTION fn_AS_Top20Perc_Customers_GP_Mail_Merge
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Selected] tinyint,
        [Customer] varchar(100),
        [Number] varchar(10),
        [Fax Number] varchar(16),
        [Contact E-mail] varchar(40),
        [Pricipal] varchar(50),
        [Contact] varchar(30),
        [Post Box] varchar(20),
        [Post Office] varchar(30),
        [Post Code] varchar(10),
        [Street Address] varchar(40),
        [Suburb] varchar(30),
        [City] varchar(30),
        [Street Code] varchar(10),
        [Delivery Address] varchar(40),
        [Delivery Suburb] varchar(40),
        [Delivery City] varchar(30),
        [Delivery Code] varchar(10),
        [Head Office] varchar(50)
    )

AS

BEGIN

  	DECLARE @StartWeekNo int, @EndWeekNo int


    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Selected],
                MAX(CASE WHEN Firstnames IS NULL
                        THEN ISNULL(Surname, '')
                        ELSE ISNULL(Surname, '') + ', ' + LTRIM(ISNULL(Firstnames, ''))
                        END) AS [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Fax_No), 16) AS [Fax Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                          THEN ISNULL(c.Principal_Name, '')
                          ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                     END), 50) AS [Principal],
                LEFT(MAX(c.Contact_Name), 30) AS [Contact],
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code],
                LEFT(MAX(c.Street_Address), 40) AS [Street Address], 
                LEFT(MAX(c.Suburb), 30) AS [Suburb],
                LEFT(MAX(c.City), 30) AS [City],
                LEFT(MAX(c.Street_Post_Code), 10) AS [Street Code],
                LEFT(MAX(c.Delivery_Address), 40) AS [Delivery Address], 
                LEFT(MAX(c.Delivery_Suburb), 40) AS [Delivery Suburb],
                LEFT(MAX(c.Delivery_City), 30) AS [Delivery City],
                LEFT(MAX(c.Delivery_Post_Code), 10) AS [Delivery Code],
                LEFT(MAX(c.Head_Office), 50) AS [Head Office]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Selected],
                MAX(CASE WHEN Firstnames IS NULL
                        THEN ISNULL(Surname, '')
                        ELSE ISNULL(Surname, '') + ', ' + LTRIM(ISNULL(Firstnames, ''))
                        END) AS [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Fax_No), 16) AS [Fax Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                          THEN ISNULL(c.Principal_Name, '')
                          ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                     END), 50) AS [Principal],
                LEFT(MAX(c.Contact_Name), 30) AS [Contact],
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code],
                LEFT(MAX(c.Street_Address), 40) AS [Street Address], 
                LEFT(MAX(c.Suburb), 30) AS [Suburb],
                LEFT(MAX(c.City), 30) AS [City],
                LEFT(MAX(c.Street_Post_Code), 10) AS [Street Code],
                LEFT(MAX(c.Delivery_Address), 40) AS [Delivery Address], 
                LEFT(MAX(c.Delivery_Suburb), 40) AS [Delivery Suburb],
                LEFT(MAX(c.Delivery_City), 30) AS [Delivery City],
                LEFT(MAX(c.Delivery_Post_Code), 10) AS [Delivery Code],
                LEFT(MAX(c.Head_Office), 50) AS [Head Office]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-->> FUNCTION TO EXTRACT Top 20% Top Sales Transactions Sellers
-->> By Gross Profit
-->> TB 06 JUL 2001

CREATE   FUNCTION fn_AS_Top20Perc_Sales_Tran_GP
    (
		@CompanyID int,
        @FromDate datetime,
        @ToDate datetime
    )
RETURNS @Sales_Table TABLE 
	(ID int,
     Description varchar(50),
     Code varchar(20))
AS

BEGIN
	INSERT @Sales_Table

    SELECT TOP 20 PERCENT WITH TIES
        p.AP_Products_ID as [ID],
        MAX(p.Description) as [Description],
        MAX(p.Product_Code) as [Code]
    FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
            INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AW_User_Companies_ID = @CompanyID AND
         (h.Transaction_Date > @FromDate AND
          h.Transaction_Date <= @ToDate) AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4)
    GROUP BY p.AP_Products_ID
    ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC

	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-->> FUNCTION TO EXTRACT Top 20% Top Sales Transactions Sellers
-->> By Sales Value
-->> TB 06 JUL 2001

CREATE     FUNCTION fn_AS_Top20Perc_Sales_Tran_Value
    (
		@CompanyID int,
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Sales_Table TABLE 
    	(ID int,
         Description varchar(50),
         Code varchar(20))
AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Sales_Table
        
            SELECT TOP 20 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Description],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Sales_Table

            SELECT TOP 20 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Description],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
        END
    RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   : fn_AS_Top50Perc_Customers_GP
--Purpose       : FUNCTION TO EXTRACT Top 50% Customers
--              : By Gross Profit WITHIN THE LAST 1 YEAR
--Parameters    :
--Date          : 08 JUL 2001
--Authors       : TB
--Version       : 1.0.0
--MODS          :13/05/02 - Fixed overflow error with: LEFT([Customer Name],50) 
--              :05/07/04 - Renamed [Customer Number] field to [Number]
-------------------------------------------------------------------------------

CREATE            FUNCTION fn_AS_Top50Perc_Customers_GP
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [ID] int,
        [Customer Name] varchar(50),
        [Number] varchar(20)
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table
        
            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top50Perc_Customers_GP_Extended
--Purpose       :EXTRACT Top 50% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2004/07/07
--Authors       :TB
--MODS          :16/03/06 - Added extract LEFT of varchars to eliminate TRUNCATE
-------------------------------------------------------------------------------

CREATE               FUNCTION [dbo].[fn_AS_Top50Perc_Customers_GP_Extended]
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Send E-mail] tinyint,
        [Customer] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact E-mail] varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact Cell] varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Box] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Office] varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Code] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Top50Perc_Customers_GP_Mail_Merge
--Purpose       :EXTRACT Top 50% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2007/12/07
--Authors       :TB
--MODS          :
--2004.4.5      :10/07/09 - Added Delivery Address and Head Office fields
-------------------------------------------------------------------------------

CREATE                  FUNCTION fn_AS_Top50Perc_Customers_GP_Mail_Merge
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Selected] tinyint,
        [Customer] varchar(100),
        [Number] varchar(10),
        [Fax Number] varchar(16),
        [Contact E-mail] varchar(40),
        [Pricipal] varchar(50),
        [Contact] varchar(30),
        [Post Box] varchar(20),
        [Post Office] varchar(30),
        [Post Code] varchar(10),
        [Street Address] varchar(40),
        [Suburb] varchar(30),
        [City] varchar(30),
        [Street Code] varchar(10),
        [Delivery Address] varchar(40),
        [Delivery Suburb] varchar(40),
        [Delivery City] varchar(30),
        [Delivery Code] varchar(10),
        [Head Office] varchar(50)
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Selected],
                MAX(CASE WHEN Firstnames IS NULL
                        THEN ISNULL(Surname, '')
                        ELSE ISNULL(Surname, '') + ', ' + LTRIM(ISNULL(Firstnames, ''))
                        END) AS [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Fax_No), 16) AS [Fax Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                          THEN ISNULL(c.Principal_Name, '')
                          ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                     END), 50) AS [Principal],
                LEFT(MAX(c.Contact_Name), 30) AS [Contact],
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code],
                LEFT(MAX(c.Street_Address), 40) AS [Street Address], 
                LEFT(MAX(c.Suburb), 30) AS [Suburb],
                LEFT(MAX(c.City), 30) AS [City],
                LEFT(MAX(c.Street_Post_Code), 10) AS [Street Code],
                LEFT(MAX(c.Delivery_Address), 40) AS [Delivery Address], 
                LEFT(MAX(c.Delivery_Suburb), 40) AS [Delivery Suburb],
                LEFT(MAX(c.Delivery_City), 30) AS [Delivery City],
                LEFT(MAX(c.Delivery_Post_Code), 10) AS [Delivery Code],
                LEFT(MAX(c.Head_Office), 50) AS [Head Office]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Selected],
                MAX(CASE WHEN Firstnames IS NULL
                        THEN ISNULL(Surname, '')
                        ELSE ISNULL(Surname, '') + ', ' + LTRIM(ISNULL(Firstnames, ''))
                        END) AS [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Fax_No), 16) AS [Fax Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                          THEN ISNULL(c.Principal_Name, '')
                          ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                     END), 50) AS [Principal],
                LEFT(MAX(c.Contact_Name), 30) AS [Contact],
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code],
                LEFT(MAX(c.Street_Address), 40) AS [Street Address], 
                LEFT(MAX(c.Suburb), 30) AS [Suburb],
                LEFT(MAX(c.City), 30) AS [City],
                LEFT(MAX(c.Street_Post_Code), 10) AS [Street Code],
                LEFT(MAX(c.Delivery_Address), 40) AS [Delivery Address], 
                LEFT(MAX(c.Delivery_Suburb), 40) AS [Delivery Suburb],
                LEFT(MAX(c.Delivery_City), 30) AS [Delivery City],
                LEFT(MAX(c.Delivery_Post_Code), 10) AS [Delivery Code],
                LEFT(MAX(c.Head_Office), 50) AS [Head Office]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-->> FUNCTION TO EXTRACT Top 50% Top Sales Transactions Sellers
-->> By Gross Profit
-->> TB 06 JUL 2001

CREATE   FUNCTION fn_AS_Top50Perc_Sales_Tran_GP
    (
		@CompanyID int,
        @FromDate datetime,
        @ToDate datetime
    )
RETURNS @Sales_Table TABLE 
	(ID int,
     Description varchar(50),
     Code varchar(20))
AS

BEGIN
	INSERT @Sales_Table

    SELECT TOP 50 PERCENT WITH TIES
        p.AP_Products_ID as [ID],
        MAX(p.Description) as [Description],
        MAX(p.Product_Code) as [Code]

    FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
            INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AW_User_Companies_ID = @CompanyID AND
         (h.Transaction_Date > @FromDate AND
          h.Transaction_Date <= @ToDate) AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4)
    GROUP BY p.AP_Products_ID
    ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC

	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-->> FUNCTION TO EXTRACT Top 50% Top Sales Transactions Sellers
-->> By Sales Value
-->> TB 06 JUL 2001

CREATE     FUNCTION fn_AS_Top50Perc_Sales_Tran_Value
    (
		@CompanyID int,
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Sales_Table TABLE 
    	(ID int,
         Description varchar(50),
         Code varchar(20))
AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Sales_Table
        
            SELECT TOP 50 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Description],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Sales_Table

            SELECT TOP 50 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Description],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM(d.Extended_Amount - d.Tax_Amount) DESC
        END
    RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_AS_Users_Supervisor_Password_Check
--Purpose       :Select if POS User = Supervisor
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS          :05/10/02 - Inserted validate IsSupervisor field in AW_Users to
--              :           establish if User is as members of Supervisors
--              :27/05/03 - Removed superfluous JOIN with AW_Users_Per_Role
-------------------------------------------------------------------------------

CREATE             FUNCTION fn_AS_Users_Supervisor_Password_Check
	(
		@Password varchar(20)
	)

	RETURNS int

AS

	BEGIN
		DECLARE @ID int

		SELECT TOP 1 @ID = AW_Users_ID
		FROM AW_Users
        WHERE IsSupervisor = 1 AND
              Password = @Password


		IF @ID IS NULL 	
			SET @ID = 0 
		
		RETURN @ID
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION fn_AT_Get_Actor
	()
RETURNS @ActorTable TABLE 
	(ID int, Actor varchar(50))
AS
BEGIN
	INSERT @ActorTable
	SELECT AW_Users_ID as Actor_ID, Firstname + ' ' + Surname as Actor
		FROM AW_Users
	
	UNION
		SELECT Sys_AT_Actor_Types_ID as Actor_ID, [Description] as Actor 
		FROM Sys_AT_Actor_Types
	RETURN
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :Get the ageing values for a customer
--Purpose       :Returns a scalar value for the passed in period,
--              :    If the TransactionDate falls within the selected Age Area,
--				:        the Amount will be the Amount,
--              :            else the Amount will be 0
--Date          :2002/03/07
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE         FUNCTION fn_AW_Amount_of_Date_Between
    (
    	@Amount money, 
    	@TransactionDate datetime, 
    	@PeriodStartDate datetime, 
    	@PeriodEndDate datetime,
    	@DefaultAmount money = 0
    )

RETURNS money

AS

    BEGIN
    	DECLARE @AgeAmount money	
    
    	IF @PeriodStartDate IS NULL AND
           @PeriodEndDate IS NULL AND
           @TransactionDate IS NULL
    		SET @AgeAmount = 0
    
    	ELSE 
    	IF @PeriodStartDate IS NULL AND
           @PeriodEndDate IS NULL
    		SET @AgeAmount = @DefaultAmount
    
    	ELSE
    	IF @PeriodStartDate IS NOT NULL AND
           @PeriodEndDate IS NULL
    		SET @AgeAmount = 0
    
    	ELSE
    	IF @PeriodEndDate IS NOT NULL AND
           @PeriodStartDate IS NULL
    		BEGIN
    			IF @TransactionDate <= @PeriodEndDate
    				SET @AgeAmount = @Amount
    			ELSE
    				SET @AgeAmount = 0
    		END
    
    	ELSE	
    	IF @TransactionDate <= @PeriodEndDate AND
           @TransactionDate > @PeriodStartDate
    		SET @AgeAmount = @Amount
    	ELSE
    		SET @AgeAmount = 0
    
    	RETURN @AgeAmount
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :fn_AW_Amount_of_Period
--Purpose       :Get the ageing values for a Supplier
--              :NEW: Returns a scalar value for the passed in period:
--              :     If the TransactionDate falls within the selected Period,
--				:         Then the Amount will be the Parameter Amount,
--              :         Else the Amount will be 0
--Date          :2002/10/29
--Authors       :TB
--Version       :1.0.0
--MODS:         :01/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :02/01/03 - Fixed COMPARE not picking up if transaction period
--              :           is older than the OLDEST period
------------------------------------------------------------------------------

CREATE             FUNCTION fn_AW_Amount_of_Period
    (
        @Amount money,
        @TransactionPeriod varchar(6),
        @ComparisonPeriod varchar(6),
        @OldestPeriod varchar(6)
    )        


RETURNS money

AS

    BEGIN

    	DECLARE @AgeAmount money	
    
        SET @AgeAmount = 0

        -- If PERIOD <= OLDEST period AND
        -- @ComparisonPeriod = @OldestPeriod (period 7) (180+)
        ------------------------------------------------------
        IF @TransactionPeriod <= @OldestPeriod AND
           @OldestPeriod = @ComparisonPeriod

            SET @AgeAmount = @Amount

        -- If this is LATER than the OLDEST (Period 1 to 6)
        ---------------------------------------------------
        ELSE
        IF @TransactionPeriod = @ComparisonPeriod

            SET @AgeAmount = @Amount


        RETURN @AgeAmount

    END

-- THE PREVIOUS SR 1.5 version
------------------------------
--     BEGIN
--     	DECLARE @AgeAmount money	
-- 
--         SET @AgeAmount = 0
-- 
--     --> If this is the OLDEST (180+) PERIOD (period 7) AND
--     --  MonthID and YearID are EQUAL or OLDER than this period
--         IF @TransactionMonth <= @OldestMonth AND
--            @TransactionYear <= @OldestYear AND
--            @TransactionMonth = @PeriodMonth AND
--            @TransactionYear = @PeriodYear
-- 
--             SET @AgeAmount = @Amount
-- 
--     --> If this is LATER than the OLDEST (Period 1 to 6)
--         ELSE
--         IF @TransactionMonth = @PeriodMonth AND
--            @TransactionYear = @PeriodYear
-- 
--             SET @AgeAmount = @Amount
-- 
-- 
--     	RETURN @AgeAmount
-- 
--     END

-- THE PREVIOUS date-based version
----------------------------------
--    BEGIN    
--     	IF @PeriodStartDate IS NULL AND
--            @PeriodEndDate IS NULL AND
--            @TransactionDate IS NULL
--     		SET @AgeAmount = 0
--     
--     	ELSE 
--     	IF @PeriodStartDate IS NULL AND
--            @PeriodEndDate IS NULL
--     		SET @AgeAmount = @DefaultAmount
--     
--     	ELSE
--     	IF @PeriodStartDate IS NOT NULL AND
--            @PeriodEndDate IS NULL
--     		SET @AgeAmount = 0
--     
--     	ELSE
--     	IF @PeriodEndDate IS NOT NULL AND
--            @PeriodStartDate IS NULL
--     		BEGIN
--     			IF @TransactionDate <= @PeriodEndDate
--     				SET @AgeAmount = @Amount
--     			ELSE
--     				SET @AgeAmount = 0
--     		END
--     
--     	ELSE	
--     	IF @TransactionDate <= @PeriodEndDate AND
--            @TransactionDate > @PeriodStartDate
--     		SET @AgeAmount = @Amount
--     	ELSE
--     		SET @AgeAmount = 0
--     
--     	RETURN @AgeAmount
--    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :Get the ageing values for a Supplier
--Purpose       :Returns a scalar value for the passed in period,
--              :    If the Accounting Period falls within the selected Accounting Period
--				:        then Amount will be the Amount,
--              :        else the Amount will be 0
--Date          :2007/03/09
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE           FUNCTION fn_AW_Amount_of_Period_Between
    (
    	@Amount money, 
        @TranMonthID int,
        @TranYearID int,
        @Period varchar(6),
        @Period7 varchar(6)
    )

RETURNS money

AS

    BEGIN
    	DECLARE @AgeAmount money	


        SET @AgeAmount = 0


        IF @Period = @Period7        -- 180+ Age Area
            BEGIN
                IF dbo.fn_AB_Get_Ending_GL_Period(@TranMonthID, @TranYearID) <= @Period
                    BEGIN
                        SET @AgeAmount = @Amount
                    END
            END

        ELSE                         -- All other Areas
            BEGIN
                IF dbo.fn_AB_Get_Ending_GL_Period(@TranMonthID, @TranYearID) = @Period
                    BEGIN
                        SET @AgeAmount = @Amount
                    END
            END


    
    	RETURN @AgeAmount
    
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE    FUNCTION fn_AW_Comment_Single
	(@ActorTypeID int)
RETURNS @CommentTable TABLE 
	(
	Actor_ID int,
	 [Comments] varchar(500)
	)
AS
BEGIN
	INSERT @CommentTable
	SELECT 
		Min(Comment) as Comments,
		Actor_ID
	FROM AW_Comments
	WHERE  Sys_AT_Actor_Types_ID = @ActorTypeID
	GROUP BY Actor_ID
	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION fn_AW_Comments
	(@ActorTypeID int)
RETURNS @Comments TABLE 
	(ID int,
	 Comment varchar(500),
	ActorID int,
	ActorTypeID int)
AS
BEGIN
	INSERT @Comments
	SELECT AW_Comments_ID, Comment, Actor_ID, Sys_AT_Actor_Types_ID FROM AW_Comments WHERE Sys_AT_Actor_Types_ID = @ActorTypeID
	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.fn_AW_Exists_Customer_Reference
--Purpose       :Returns FLAG if AS_Transactions.Customer_Reference exists for INVOICE
--Date          :2008/11/21 (2004.4.2)
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            FUNCTION dbo.fn_AW_Exists_Customer_Reference
	(
        @Value varchar(1000),
        @ActorID int,
        @CompanyID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit


        IF EXISTS
            (
                SELECT TOP 1 AS_Transactions_ID
                FROM AS_Transactions
                WHERE Customer_Reference = @Value AND
                      AC_Customers_ID = @ActorID AND
                      AW_User_Companies_ID = @CompanyID AND
                      Sys_AW_Transaction_Types_ID = 3
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0



    	RETURN @Test

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.fn_AW_Exists_Product_Code
--Purpose       :Returns FLAG if AP_Products.Product_Code exists
--Date          :2004/12/10
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AW_Exists_Product_Code
	(
        @Value varchar(1000),
        @ActorID int,
        @CompanyID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit


        IF EXISTS
            (
                SELECT TOP 1 a.AP_Products_Suppliers_ID
                FROM AP_Products_Suppliers a
                    INNER JOIN AP_Products b
                        ON a.AP_Products_ID = b.AP_Products_ID
                WHERE b.Product_Code = @Value AND
                      a.AO_Suppliers_ID = @ActorID AND
                      a.AW_User_Companies_ID = @CompanyID
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0



    	RETURN @Test

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.fn_AW_Exists_SO_Customer_Reference
--Purpose       :Returns FLAG if AS_Transactions.Customer_Reference exists for an active sales order
--Date          :2017/09/27 V6.3
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AW_Exists_SO_Customer_Reference]
	(
        @Value varchar(1000),
        @ActorID int,
        @CompanyID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit

        IF EXISTS
            (
                SELECT TOP 1 AS_Transactions_ID
                FROM AS_Transactions
                WHERE AC_Customers_ID = @ActorID AND 
					  ISNULL(Customer_Reference,'') = @Value AND
                      AW_User_Companies_ID = @CompanyID AND
                      Sys_AW_Transaction_Types_ID = 16 AND
					  Slu_AW_Active_ID = 1
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0

    	RETURN @Test

    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.fn_AW_Exists_Supplier_Invoice
--Purpose       :Returns FLAG if AO_Transactions.Document_Number exists
--Date          :2005/05/08 (2004.2.2)
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AW_Exists_Supplier_Invoice
	(
        @Value varchar(1000),
        @ActorID int,
        @CompanyID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit


        IF EXISTS
            (
                SELECT TOP 1 AO_Transactions_ID
                FROM AO_Transactions
                WHERE Document_Number = @Value AND
                      AO_Suppliers_ID = @ActorID AND
                      AW_User_Companies_ID = @CompanyID
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0



    	RETURN @Test

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :dbo.fn_AW_Exists_User_Name
--Purpose       :Returns FLAG if AW_Users.UserName exists
--Date          :2005/03/06
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AW_Exists_User_Name
	(
        @Value varchar(100)
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit


        IF EXISTS
            (
                SELECT TOP 1 AW_Users_ID
                FROM AW_Users
                WHERE UserName = @Value
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0



    	RETURN @Test

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AW_Get_Allocation_Status
--Purpose       :Returns Customer/Supplier Transaction allocation status
--Date          :2007/11/03
--Authors       :TB
--MODS          :
--2004.3.8      :30/03/08 - Reworked the status logic
--2004.4.3      :07/03/09 - Reworked the status logic AGAIN and added @Diff
--2004.4.8      :21/05/10 - Added RETURN after FIRST condition is met
-----------------------------------------------------------------------------

CREATE                FUNCTION dbo.fn_AW_Get_Allocation_Status
    (
        @TableID tinyint,
        @TranID int,
        @Amount money = 0
    )

RETURNS tinyint

AS

    BEGIN

        DECLARE @Total money,
                @Payment money,
                @Diff money,
                @AllocStatus tinyint
    
    
        SET @AllocStatus = 0
    

        ---------------------------------------------------------
        --> Get the transaction
        ---------------------------------------------------------
        IF @TableID = 1
            BEGIN
            	SELECT @Total = ISNULL(Total_Amount, 0),
                       @Payment = ISNULL(Payment_Amount, 0),
                       @Diff = ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)
                FROM AS_Transactions
            	WHERE AS_Transactions_ID = @TranID
            END
    
        ELSE
        IF @TableID = 2
            BEGIN
            	SELECT @Total = ISNULL(Total_Amount, 0),
                       @Payment = ISNULL(Payment_Amount, 0),
                       @Diff = ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0)
                FROM AO_Transactions
            	WHERE AO_Transactions_ID = @TranID
            END
    
    
        ---------------------------------------------------------
        --> UNALLOCATED (Payment = 0)
        ---------------------------------------------------------
        IF @Payment = 0
            BEGIN
                SET @AllocStatus = 1

                RETURN @AllocStatus
            END

        ---------------------------------------------------------
        --> FULLY ALLOCATED (Total + Payment = 0)
        ---------------------------------------------------------
        IF @Diff = 0
            BEGIN
                SET @AllocStatus = 3

                RETURN @AllocStatus
            END


        ---------------------------------------------------------
        --> ALLOCATED (Payment <> 0)
        ---------------------------------------------------------


        ---------------------------------------------------------
        --> PARTIALLY ALLOCATED (Payment < Total) - NEW 2004.4.3
        ---------------------------------------------------------
        IF @Total > 0        --Debit
            BEGIN
                IF @Diff > 0 AND @Diff < @Total
                    BEGIN
                        SET @AllocStatus = 2

                        RETURN @AllocStatus
                    END
            END
        ELSE
        IF @Total <= 0       --Credit
            BEGIN
                IF @Diff < 0 AND @Diff > @Total
                    BEGIN
                        SET @AllocStatus = 2

                        RETURN @AllocStatus
                    END
            END

        ---------------------------------------------------------
        --> OVER-ALLOCATED (Payment > Total) - NEW 2004.4.3
        ---------------------------------------------------------
        IF @Total > 0        --Debit
            BEGIN
                IF @Diff < 0
                    BEGIN
                        SET @AllocStatus = 4

                        RETURN @AllocStatus
                    END
            END
        ELSE
        IF @Total <= 0       --Credit
            BEGIN
                IF @Diff > 0
                    BEGIN
                        SET @AllocStatus = 4

                        RETURN @AllocStatus
                    END
            END

        ---------------------------------------------------------
        --> INVALID ALLOCATION (Payment sign = Total sign)
        ---------------------------------------------------------
        IF @Total > 0        --Debit
            BEGIN
                IF @Payment > 0
                    BEGIN
                        SET @AllocStatus = 5

                        RETURN @AllocStatus
                    END
            END
        ELSE
        IF @Total <= 0       --Credit
            BEGIN
                IF @Payment < 0
                    BEGIN
                        SET @AllocStatus = 5

                        RETURN @AllocStatus
                    END
            END

        ---------------------------------------------------------
        --> WILL BECOME OVERALLOCATED (Payment will exceed Total)
        ---------------------------------------------------------
        IF @Total > 0        --Debit
            BEGIN
                IF (@Diff + @Amount) < 0
                    BEGIN
                        SET @AllocStatus = 6

                        RETURN @AllocStatus
                    END
            END
        ELSE
        IF @Total <= 0       --Credit
            BEGIN
                IF (@Diff + @Amount) > 0
                    BEGIN
                        SET @AllocStatus = 6

                        RETURN @AllocStatus
                    END
            END
        ---------------------------------------------------------

        RETURN @AllocStatus
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AW_Get_YearID_From_Year
--Purpose       :Returns Slu_AW_Years_ID from Year
--Date          :13 OCT 2008
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AW_Get_YearID_From_Year
    (
        @Year smallint
    )

RETURNS smallint

AS

    BEGIN

        DECLARE @YearID smallint
    
            SELECT @YearID = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE Description = @Year
    
        RETURN @YearID

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AW_Get_Year_From_YearID
--Purpose       :Returns YEAR 4-digit integer
--Date          :24 DEC 2003
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE          FUNCTION dbo.fn_AW_Get_Year_From_YearID
    (
        @YearID int
    )

RETURNS smallint

AS

    BEGIN

        DECLARE @Year smallint
    
            SELECT @Year = Description
            FROM Slu_AW_Years
            WHERE Slu_AW_Years_ID = @YearID
    
        RETURN @Year

    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

------------------------------------------------------------------------------
--Description   :fn_AW_Months
--Purpose       :Used by Period Procedure
--Parameters    :
--Date          :2002/11/02
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE               FUNCTION fn_AW_Months	()

RETURNS @Table TABLE 
	(
        ID int, 
        [Month] char(3)
    )

AS

	BEGIN
		INSERT @Table
            (
                ID,
                [Month]
            )

		SELECT Slu_AW_Months_ID AS [ID], 
				Description AS [Month] 
		FROM Slu_AW_Months
		RETURN
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AW_Ping_Remote_DataSource
--Purpose       :Returns SCALAR bit if DataSource Access failure/success
--Funtionality  :    0 = Success, 1 = Failure
--Notes         :-n Count    - specifies the number of Echo Request messages sent. Default = 4 (4 messages)
--              :-w Timeout  - specifies time in milliseconds to wait for Echo Reply message. Default = 4000 (4 seconds)
--Date          :2009/09/11
--Authors       :TB
--MODS          :
--RL	V6.0	:2014-04-10 - Enhanced MSSQL instance handeling
-----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AW_Ping_Remote_DataSource]
	(
        @DataSource varchar(50),
        @Timeout int
	)

RETURNS bit

AS

	BEGIN	
    	DECLARE @RetCode bit,
                @CmdTxt varchar(100),
                @Pos	Int

        SET @RetCode = 1

		SET @Pos = 0
		SELECT @Pos = CHARINDEX('\', @DataSource)

		IF @Pos <> 0
		BEGIN
			SELECT @DataSource = SUBSTRING(@DataSource,0,@Pos)
		END

        SET @CmdTxt = 'ping -n 1 -w ' + CONVERT(varchar(4), @Timeout) + ' ' + ltrim(rtrim(@DataSource))
        EXEC @RetCode = master..xp_cmdshell @CmdTxt, no_output

	    RETURN @RetCode    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :dbo.fn_AW_Split_Text_To_Words
--Purpose       :Splits a concatenated string into words with space separator
--Date          :22 JUN 2009
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE           FUNCTION dbo.fn_AW_Split_String_To_Words
    (
        @Value varchar(1000)
    )

RETURNS varchar(2000)

AS

BEGIN

    DECLARE @Char1 char(1),
            @Char2 char(1),
            @Words varchar(200),
            @Len smallint,
            @Pos smallint

    SET @Char1 = ''
    SET @Char2 = ''
    SET @Words = ''
    SET @Len = LEN(@Value)
    SET @Pos = 1


--WORKS
    WHILE @Pos <= @Len
        BEGIN
            SET @Char1 = SUBSTRING(@Value, @Pos, 1)

            IF @Pos < @Len
                SET @Char2 = SUBSTRING(@Value, (@Pos + 1), 1)

            IF (ASCII(@Char1) >= 65 AND ASCII(@Char1) <= 90) AND
                (ASCII(@Char2) < 65 OR ASCII(@Char2) > 90)
                BEGIN
                    IF @Pos > 1 AND @Pos < @Len
                        SET @Words = @Words + ' ' + @Char1
                    ELSE
                        SET @Words = @Words + @Char1
                END
            ELSE
                SET @Words = @Words + @Char1

            SET @Pos = @Pos + 1
        END


    RETURN(@Words)

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

------------------------------------------------------------------------------
--Description   :fn_AW_Years
--Purpose       :Used by Period Procedure
--Parameters    :
--Date          :2002/11/02
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE   FUNCTION fn_AW_Years()

RETURNS @Table TABLE 
	(
        ID int, 
        [Year] smallint
    )

AS

	BEGIN
		INSERT @Table
            (
                ID,
                [Year]
            )

		SELECT Slu_AW_Years_ID AS [ID], 
				Description AS [Year] 
		FROM Slu_AW_Years
		RETURN
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   FUNCTION fn_Caption_From_TableName
	(@Tablename varchar(100))
RETURNS varchar(100)
AS
BEGIN
	SET @Tablename = Replace(@TableName, 'Lup_AW_','')   		--'ActiveWare')
	SET @Tablename = Replace(@TableName, 'Lup_AP_', '')   		--'ActiveProducts')
	SET @Tablename = Replace(@TableName, 'Lup_AC_', '')		--'ActiveCustomers')
	SET @Tablename = Replace(@TableName, 'Lup_AS_', '')		--'ActiveSales')
	SET @Tablename = Replace(@TableName, 'Lup_AB_', '')		--'ActiveBooks')
	SET @Tablename = Replace(@TableName, 'Lup_AO_', '')		--'ActiveOrders')

	SET @Tablename = Replace(@TableName, 'Slu_AW_','')   		--'ActiveWare')
	SET @Tablename = Replace(@TableName, 'Slu_AP_', '')   		--'ActiveProducts')
	SET @Tablename = Replace(@TableName, 'Slu_AC_', '')		--'ActiveCustomers')
	SET @Tablename = Replace(@TableName, 'Slu_AS_', '')		--'ActiveSales')
	SET @Tablename = Replace(@TableName, 'Slu_AB_', '')		--'ActiveBooks')
	SET @Tablename = Replace(@TableName, 'Slu_AO_', '')		--'ActiveOrders')


	SET @Tablename = Replace(@TableName, 'AW_User_', '')
	SET @Tablename = Replace(@TableName, 'ies_ID', 'y')
	SET @Tablename = Replace(@TableName, 's_ID', '')
	SET @Tablename = Replace(@TableName, '_ID', '')
	--SET @Tablename = Replace(@TableName, 'Slu_', '')
	--SET @Tablename = Replace(@TableName, 'Lup_', '')
	SET @Tablename = Replace(@TableName, '_', ' ')


	RETURN @TableName
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :fn_Customer_Has_Transaction
--Purpose       :Returns FLAG for Customer Payments PickList
--              :    if Customer has OUTSTANDING TRANSACTIONS amounts
--Parameters    :
--Date          :2002/06/28
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE   FUNCTION fn_Customer_Has_Transaction
	(
		@CustomerID int,
		@CompanyID int
	)

RETURNS bit

AS

BEGIN
	DECLARE @Test bit
	IF Exists(SELECT top 1 AC_Customers_ID
              FROM AS_Transactions t
			  WHERE t.AW_User_Companies_ID = @CompanyID AND
                   (t.Sys_AW_Transaction_Types_ID = 3 OR 
                    t.Sys_AW_Transaction_Types_ID = 4) AND
                    t.Total_Amount + Payment_Amount  <> 0 )
		SET @Test = 1
	ELSE	
		SET @Test = 0

	RETURN @Test
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE FUNCTION fn_GetDate
	(@Date DateTime, 
	 @StartEnd int)
RETURNS DateTime
AS
BEGIN
	DECLARE @IntDate int, @FloatDate float
	SET @FloatDate = convert(float, @Date)
	SET @IntDate = convert(int, @FloatDate)
	IF @StartEnd = 0
		SET @Date = convert(DateTime, @IntDate)
	ELSE
		SET @Date = convert(DateTime, @IntDate + 0.9999999999)

	RETURN @Date
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--Returns the Default Company or the First Company
--GL
--2001/08/01
CREATE FUNCTION fn_Get_Default_Company_ID
	(
		
	)
RETURNS int
	BEGIN
		DECLARE @CompanyID int
	--Check for the first company with Default = True
		SELECT TOP 1 @CompanyID = AW_User_Companies_ID 
			FROM AW_User_Companies 
			WHERE Yes_No_Default_Company <> 0 
	--Get First company if there is no default
 		IF @CompanyID IS NULL
			SELECT TOP 1 @CompanyID = AW_User_Companies_ID 
				FROM AW_User_Companies 
				ORDER BY AW_User_Companies_ID
	--Return 0 if there is no company
		IF @CompanyID IS NULL
			SET @CompanyID = 0

		RETURN @CompanyID
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE   FUNCTION fn_ProductDiscountsPerCustomer
   (@DiscountCategory int)
RETURNS TABLE
AS
   RETURN SELECT 
         p.AP_Products_ID as ID,
         isnull(dcg.Discount_Percentage, 0) as Discount_Percentage
      FROM AP_Products p JOIN AS_Discount_Categories_Groups dcg 
            ON p.Lup_AP_Discount_Groups_ID = dcg.Lup_AP_Discount_Groups_ID
      WHERE Lup_AC_Discount_Categories_ID = @DiscountCategory
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--Checks to see if there are any Transactions against a Supplier that has to be aged
--2001/08/01
--GL
---------------------------------------------------------------------------------------------------------------------------------------
CREATE   FUNCTION fn_Supplier_Has_Transaction
	(
		@SupplierID int,
		@CompanyID int
	)
RETURNS bit
AS
	BEGIN
	DECLARE @Test bit
	IF Exists(Select top 1 AO_Suppliers_ID From AO_Transactions t 
					WHERE t.AW_User_Companies_ID = @CompanyID 
							AND (t.Sys_AW_Transaction_Types_ID = 8 
											OR t.Sys_AW_Transaction_Types_ID = 9)  
							AND   isnull(t.Total_Amount,0) + isnull(Payment_Amount,0)  <> 0 )

		SET @Test = 1
	ELSE	
		SET @Test = 0

	RETURN @Test
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

Create View vw_AC_Customers
As

Select 
	c.AC_Customers_ID As 'Customer ID',
	IsNull(c.Surname,'') As 'Surname',
	IsNull(c.Firstnames,'') As 'Firstnames',
	IsNull(c.Initials,'') As 'Initials',
	--c.Slu_AW_Titles_ID,
	ISNULL(t.[Description],'') As 'Title',
	--c.Slu_AW_Languages_ID,
	ISNULL(l.[Description],'') As 'Language',
	IsNull(c.IDReg_Number,'') As 'ID/Reg No',
	ISNULL(Convert(Varchar(19),c.[Start_Date],121),'') As 'Start Date',

	--c.Slu_AW_Active_ID,
	ISNULL(av.[Description],'') As 'Active',
	--AW_YesNo_Change_Doc_Details
	IsNull(pd.[Description],'') As 'Change POS Doc',

	IsNull(c.Customer_Number,'') As 'Customer No',
	--c.AW_YesNo_Net_Billing_ID
	IsNull(nb.[Description],'') As 'Apply Net Billing',
	IsNull(c.Old_Customer_Number,'') As 'Merchant/WHouse No',
	--c.[AW_YesNo_CostPlus_Billing_ID]
	IsNull(nc.[Description],'') As 'Apply Cost+Billing',
	IsNull(c.Head_Office,'') As 'Head Office',

	--c.Lup_AC_Customer_Types_ID,
	ISNULL(ct.[Description],'') As 'Customer Type', 
	--c.Lup_AC_Customer_Groups_ID,
	ISNULL(cg.[Description],'') As 'Customer Group',
	--c.Sys_AC_Use_Assets_ID
	IsNull(ca.[Description],'') As 'Use Assets',
	--c.AW_YesNo_Apply_Product_Levy
	IsNull(al.[Description],'') As 'Apply Product Levy',
	--c.Sys_AW_Tax_Codes_ID, 
	IsNull(tx.[Description],'') As 'Tax Code',
	IsNull(c.Tax_Number,'') As 'V.A.T. Number', 
	--c.AW_YesNo_Purchase_Order_ID
	IsNull(fp.[Description],'') As 'Force Purchase Order No',

	--c.Lup_AC_Discount_Categories_ID,
	IsNull(dc.[Description],'') As 'Sales Discount Catagory',
	--c.Lup_AC_Markup_Categories_ID
	IsNull(mc.[Description],'') As 'Cost+Plus Billing Category',
	ISNULL(c.Credit_Limit,0) As 'Credit Limit',
	--[AW_YesNo_Override_Credit_Limit]
	IsNull(oc.[Description],'') As 'Override Credit Limit',
	--c.Slu_AW_Credit_Terms_ID,
	ISNULL(lc.[Description],'') As 'Credit Terms',
	--[AW_YesNo_Override_Overdue]
	IsNull(oo.[Description],'') As 'Override Overdue',
	--c.Sys_AC_Credit_Term_Types_ID,
	ISNULL(lt.[Description],'') As 'Terms of Sale',
	ISNULL(c.Credit_Insurers_Reference,'') As 'Credit Insurer Ref',
	ISNULL(c.Credit_Insurers_Limit,0) As 'Insurer Credit Limit',
	--c.AW_YesNo_Charge_Interest_ID
	IsNull(ci.[Description],'') As 'Charge Interest',
	IsNull(c.Default_Settlement_Discount,0) As 'Settlement Discount %',

	--Slu_AW_Controllers_ID
	IsNull(cc.Surname,'') + IsNull(cc.FirstName,'') As 'Controller',
	--AW_YesNo_Pre_Notify_ID
	IsNull(pe.[Description],'') As 'Pre-Notify',
	--AW_YesNo_Post_Notify_ID
	IsNull(po.[Description],'') As 'Post-Notify',
	--c.Lup_AS_Reps_ID, 
	ISNULL(cr.[Description],'') As 'Salesperson',
	--c.Lup_AC_Sales_Areas_ID, 
	ISNULL(sa.[Description],'') As 'Sales Area',
	ISNULL(c.Contact_Name,'') As 'Contact Name',
	--Sys_AW_Delivery_Methods_ID
	IsNull(dm.[Description],'') As 'Delivery Method',
	--c.Sys_AC_Account_Types_ID,
	ISNULL(at.[Description],'') As 'Account Type',
	--c.Sys_AC_Account_Status_ID,
	ISNULL(st.[Description],'') As 'Account Status',

	IsNull(c.Notes,'') As 'Notes',

	IsNull(c.Post_Box,'') As 'Post Box',
	IsNull(c.Post_Office,'') As 'Post Office',
	IsNull(c.Post_Code,'') As 'Post Code',

	IsNull(c.Street_Address,'') As 'Street Address',
	IsNull(c.Suburb,'') As 'Suburb',
	IsNull(c.City,'') As 'City',
	IsNull(c.Street_Post_Code,'') As 'Street Code',

	IsNull(c.Delivery_Address,'') As 'Delivery Address',
	IsNull(c.Delivery_Suburb,'') As 'Delivery Suburb',
	IsNull(c.Delivery_City,'') As 'Delivery City',
	IsNull(c.Delivery_Post_Code,'') As 'Delivery Post Code',

	--c.Slu_AW_Countries_ID, 
	ISNULL(cl.[Description],'') As 'Country',
	IsNull(c.Home_Tel_No,'') As 'Home Tel No', 
	IsNull(c.Work_Tel_No,'') As 'Work Tel No', 
	IsNull(c.Cell_No,'') As 'Contact Cell No', 
	IsNull(c.Fax_No,'') As 'Fax No', 

	IsNull(c.Principal_Name,'') As 'Principal Name', 
	IsNull(c.Principal_Firstname,'') As 'Principal Firstname', 
	IsNull(c.Principal_Cell_No,'') As 'Principal Cell No', 
	ISNULL(Convert(Varchar(19),c.Principal_Birthday,121),'') As 'Principal Birthday',

	--Principal_Contact_Method_ID
	IsNull(pc.[Description],'') As 'Principal Delivery Method',

	IsNull(c.Web_Site_URL,'') As 'Web Site URL', 
	IsNull(c.Orders_URL,'') As 'Accounts E-mail', 
	IsNull(c.Home_Email,'') As 'Contact E-mail', 
	IsNull(c.Work_Email,'') As 'Principal E-mail', 
	--AW_YesNo_Send_Email_ID
	IsNull(se.[Description],'') As 'Send E-Mail Message',
	--AW_YesNo_Attach_Tran_ID
	IsNull(ad.[Description],'') As 'Attach Statement Doc',	
	Convert(Varchar(19),c.Date_Captured,121) As 'Date Captured'

From AC_Customers c
	Left Outer Join Slu_AW_Titles t 
		On c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
	Left Outer Join Slu_AW_Languages l 
		On c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
	Left Outer Join Lup_AC_Customer_Types ct 
		On c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID
	Left Outer Join Lup_AC_Customer_Groups cg 
		On c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID
	Left Outer Join Sys_AC_Account_Status st 
		On c.Sys_AC_Account_Status_ID = st.Sys_AC_Account_Status_ID
	Left Outer Join Sys_AC_Account_Types at 
		On c.Sys_AC_Account_Types_ID = at.Sys_AC_Account_Types_ID
	Left Outer Join Lup_AS_Reps r 
		On c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
	Left Outer Join Lup_AC_Sales_Areas sa 
		On c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
	Left Outer Join Slu_AW_Countries cl 
		On c.Slu_AW_Countries_ID = cl.Slu_AW_Countries_ID
	Left Outer Join Sys_AW_Tax_Codes tx 
		On c.Sys_AW_Tax_Codes_ID = tx.Sys_AW_Tax_Codes_ID
	Left Outer Join AW_Users u 
		On c.[User_ID] = u.AW_Users_ID
	Left Outer Join AW_User_Companies cp 
		On c.AW_User_Companies_ID = cp.AW_User_Companies_ID
	Left Outer Join Slu_AW_Active av 
		On c.Slu_AW_Active_ID = av.Slu_AW_Active_ID
	Left Outer Join Sys_AC_Credit_Term_Types lt
		On c.Sys_AC_Credit_Term_Types_ID = lt.Sys_AC_Credit_Term_Types_ID
	Left Outer Join Slu_AW_Credit_Terms lc
		On c.Slu_AW_Credit_Terms_ID = lc.Slu_AW_Credit_Terms_ID
	Left Outer Join Slu_AW_YesNo nb
		On c.AW_YesNo_Net_Billing_ID = nb.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo nc
		On c.AW_YesNo_CostPlus_Billing_ID = nc.Slu_AW_YesNo_ID
	Left Outer Join Sys_AC_Use_Assets ca
		On c.Sys_AC_Use_Assets_ID = ca.Sys_AC_Use_Assets_ID
	Left Outer Join Slu_AW_YesNo al
		On c.AW_YesNo_Apply_Product_Levy = al.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo fp
		On c.AW_YesNo_Purchase_Order_ID = fp.Slu_AW_YesNo_ID
	Left Outer Join Lup_AC_Discount_Categories dc
		On c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
	Left Outer Join Lup_AC_Markup_Categories mc
		On c.Lup_AC_Markup_Categories_ID = mc.Lup_AC_Markup_Categories_ID
	Left Outer Join Slu_AW_YesNo oc
		On c.AW_YesNo_Override_Credit_Limit = oc.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo oo
		On c.AW_YesNo_Override_Overdue = oo.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo ci
		On c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
	Left Outer Join Lup_AS_Reps cr
		On c.Lup_AS_Reps_ID = cr.Lup_AS_Reps_ID
	Left Outer Join Slu_AW_YesNo pe
		On c.AW_YesNo_Pre_Notify_ID = pe.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo po
		On c.AW_YesNo_Post_Notify_ID = po.Slu_AW_YesNo_ID
	Left Outer Join Sys_AW_Delivery_Methods dm
		On c.Sys_AW_Delivery_Methods_ID = dm.Sys_AW_Delivery_Methods_ID
	Left Outer Join Sys_AW_Delivery_Methods pc
		On c.Principal_Contact_Method_ID = pc.Sys_AW_Delivery_Methods_ID
	Left Outer Join Slu_AW_YesNo se
		On c.AW_YesNo_Send_Email_ID = se.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo pd
		On c.AW_YesNo_Change_Doc_Details = pd.Slu_AW_YesNo_ID
	Left Outer Join AW_Users cc
		On c.Slu_AW_Controllers_ID = cc.AW_Users_ID
	Left Outer Join Slu_AW_YesNo ad
		On c.AW_YesNo_Attach_Tran_ID = ad.Slu_AW_YesNo_ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   : Selects the Transaction Details for Dynamic reports
--Purpose       : Dynamic SQL statements have a 8,000 character limit
--Functionality : Overcome 8,000 character limit
--Parameters    : 
--Date          : 2017/06/19
--Authors       : RL
--Version       : 1
-------------------------------------------------------------------------------
CREATE     VIEW [dbo].[vw_ASTD]

AS

    SELECT *
    FROM AS_Transaction_Details

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   : vw_AS_Banks_Cards_Union
--Purpose       : Fetch the Payments for Banking
--Functionality : Tables: Slu_AS_Card_Institutions
--              :         Slu_AW_Banks
--              :
--Called from   :         vw_AS_Payments_Select
--              :
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            VIEW vw_AS_Banks_Cards_Union

AS

    SELECT Slu_AS_Card_Institutions_ID AS [ID], 
           Description, 
           Sys_AW_Institution_Types_ID AS [TypeID]
    FROM Slu_AS_Card_Institutions 
    
    UNION
    
    SELECT Slu_AW_Banks_ID AS [ID], 
           Description, 
           Sys_AW_Institution_Types_ID AS [TypeID]
    FROM Slu_AW_Banks 


--SELECT * FROM vw_AS_Banks_Cards_Union







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--Used in the cash up to determine if a cashup has been dayended

CREATE  VIEW vw_AS_Cash_Ups_Active
AS
SELECT DISTINCT Cashed_Up
	FROM AS_Cash_Ups 
	WHERE Slu_AW_Active_ID = 1







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE VIEW vw_AT_Tasks
AS
	SELECT 
		Remind, 
		Task_Message as [Message],	
		Start_Date as [Start], 
		Date_Started as [Started],
		Due_Date as [Due],
		Date_Completed as [Completed],  
		Actual_Work as [Actual Work], 
		Actor1_ID  as [Created By],
		Actor2_ID as [Created For],
		Subject_ObjectName as [Subject Type], 
		Subject_ID as Subject,
		SYS_AT_Status_ID as Status,
		SYS_AT_Notifications_ID as Notification,
		Date_Captured  as [Date Captured],
		User_ID  as [User],
		AW_User_Companies_ID as [Company],
		Slu_AW_Active_ID  as [Active],
		AT_Tasks_ID as ID  
	FROM AT_Tasks 





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE       VIEW vw_AW_Banks_Cards_Union

AS

SELECT     
	Slu_AS_Card_Institutions_ID AS ID, 
	Description, 
       Sys_AW_Institution_Types_ID AS TypeID
FROM Slu_AS_Card_Institutions 

UNION

SELECT     
	Slu_AW_Banks_ID AS ID, 
	Description, 
       Sys_AW_Institution_Types_ID AS TypeID
FROM Slu_AW_Banks 

--SELECT * FROM vw_AW_Banks_Cards_Union







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE    VIEW vw_RPT_AC_Customer_Ageing


AS

SELECT
    c.AC_Customers_ID AS [ID], 
	c.Customer_Number AS [Customer No], 
	c.Surname AS [Name], 
	c.Firstnames AS [First Names], 
	CASE WHEN t.[Description] = '<None>' OR t.[Description] IS NULL
         THEN ''
         ELSE t.[Description]
         END AS [Title], 
	c.Initials AS [Initials], 
	l.[Description] AS [Language], 
	c.IDReg_Number AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	a.[Description] AS [Active], 
	s.[Description] AS [Account Status],
	c.Contact_Name AS [Contact Name], 
	r.[Description] AS [Salesperson],
	c.Post_Box AS [Post Box], 
	c.Post_Office AS [Post Office], 
	c.Post_Code AS [Post Code], 
	c.Street_Address AS [Street Address], 
	c.Suburb AS [Suburb], 
	c.City AS [City], 
	c.Street_Post_Code AS [Street Code], 
	cu.[Description] + ' (' + cu.Country_Code3 + ')' AS [Country], 
	c.Delivery_Address AS [Delivery Address], 
	c.Delivery_Suburb AS [Delivery Suburb], 
	c.Delivery_City AS [Delivery City], 
	c.Delivery_Post_Code AS [Delivery Post Code], 
	c.Web_Site_URL AS [Web Site URL], 
	c.Orders_URL AS [Order URL], 
	c.Home_Email AS [E-mail Home], 
	c.Work_Email AS [E-mail Work],
	c.Home_Tel_No AS [Home Tel No], 
	c.Work_Tel_No AS [Work Tel No], 
	c.Cell_No AS [Cell No], 
	c.Fax_No AS [Fax No], 
	dc.[Description] AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ct.[Description] AS [Credit Terms],
	c.Credit_Insurers_Reference AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ci.[Description] AS [Charge Interest],
	sa.[Description] AS [Sales Area], 
	c.Head_Office AS [Head Office], 
	ct.[Description] AS [Customer Type], 
	tc.[Description] AS [Tax Code], 
	c.Tax_Number AS [Tax Number],
	act.[Description] AS [Account Types],
	ctt.[Description] AS [Credit Term Types],
	c.Notes,
    c.Account_Balance AS [Account Balance]

FROM AC_Customers c
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :vw_RPT_AC_Customer_List
--Purpose       :Customer Catalog Listing Report
--Parameters    :
--Date          :2002/01/01
--Authors       :TB
--Version       :1.0.0
--MODS:         :19/09/03 - Added c.AW_User_Companies_ID AS [CompanyID] for MULTI-Company
--RL	V6.0	2014-10-21 : Added Customer Type Description, Customer Group Description
--							 Old_Customer_Number (Merchant / WHouse No), Principal Firstname
--							 Principal Name, Principal Cell No and Account Type
-------------------------------------------------------------------------------

CREATE VIEW [dbo].[vw_RPT_AC_Customer_List]
AS

SELECT
    c.AC_Customers_ID AS [ID], 
	c.Customer_Number AS [Customer No], 
	c.Surname AS [Name], 
	c.Firstnames AS [First Names], 
	CASE WHEN t.[Description] = '<None>' OR t.[Description] IS NULL
         THEN ''
         ELSE t.[Description]
         END AS [Title], 
	c.Initials AS [Initials], 
	l.[Description] AS [Language], 
	c.IDReg_Number AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	a.[Description] AS [Active], 
	s.[Description] AS [Account Status],
	c.Contact_Name AS [Contact Name], 
	r.[Description] AS [Salesperson],
	c.Post_Box AS [Post Box], 
	c.Post_Office AS [Post Office], 
	c.Post_Code AS [Post Code], 
	c.Street_Address AS [Street Address], 
	c.Suburb AS [Suburb], 
	c.City AS [City], 
	c.Street_Post_Code AS [Street Code], 
	cu.[Description] + ' (' + cu.Country_Code3 + ')' AS [Country], 
	c.Delivery_Address AS [Delivery Address], 
	c.Delivery_Suburb AS [Delivery Suburb], 
	c.Delivery_City AS [Delivery City], 
	c.Delivery_Post_Code AS [Delivery Post Code], 
	c.Web_Site_URL AS [Web Site URL], 
	c.Orders_URL AS [Order URL], 
	c.Home_Email AS [E-mail Home], 
	c.Work_Email AS [E-mail Work],
	c.Home_Tel_No AS [Home Tel No], 
	c.Work_Tel_No AS [Work Tel No], 
	c.Cell_No AS [Cell No], 
	c.Fax_No AS [Fax No], 
	dc.[Description] AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ct.[Description] AS [Credit Terms],
	c.Credit_Insurers_Reference AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ci.[Description] AS [Charge Interest],
	sa.[Description] AS [Sales Area], 
	c.Head_Office AS [Head Office], 
	tc.[Description] AS [Tax Code], 
	c.Tax_Number AS [Tax Number],
	act.[Description] AS [Account Types],
	ctt.[Description] AS [Credit Term Types],
	c.Notes,
    c.AW_User_Companies_ID AS [CompanyID],
    ty.[Description] AS [Customer Type],
    gr.[Description] AS [Customer Group],
    c.Old_Customer_Number AS [Merch / WHouse],
    c.Principal_Firstname AS [Principal Firstname],
    c.Principal_Name AS [Principal Name],
    c.Principal_Cell_No AS [Principal Cell No],
	act.[Description] AS [Account Type],
	c.Slu_AW_Active_ID AS [Slu_AW_Active_ID],
	c.Sys_AC_Account_Status_ID AS [Sys_AC_Account_Status_ID],
	c.Lup_AC_Customer_Groups_ID AS [Lup_AC_Customer_Groups_ID],
	c.Lup_AC_Customer_Types_ID AS [Lup_AC_Customer_Types_ID],
	c.Lup_AS_Reps_ID AS [Lup_AS_Reps_ID],	
	c.Lup_AC_Sales_Areas_ID As [Lup_AC_Sales_Areas_ID]
FROM AC_Customers c
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
        LEFT JOIN Lup_AC_Customer_Groups gr
            ON c.Lup_AC_Customer_Groups_ID = gr.Lup_AC_Customer_Groups_ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









CREATE       VIEW dbo.vw_RPT_AC_Customer_Statements
AS

SELECT 
    d.Date_Captured AS [TransactionDate], 
    tt.[Description] AS Type, 
    d.Transaction_Number AS [TransactionNo], 
    ISNULL(d.Amount, 0) AS Amount, 
    ISNULL(d.Payment, 0) AS Payment, 
    ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS Balance, 
    c.AC_Customers_ID AS CustomerID, 
    c.Surname + c.Initials AS Customer, 
    c.Post_Box as CustomerPostAddress,
    c.Post_Office as CustomerPostOffice,
    c.Post_Code as CustomerPostCode,
    c.Work_Email as CustomerEmail
FROM AC_Statements t 
    RIGHT OUTER JOIN AC_Customers c
        ON t.AC_Customers_ID = c.AC_Customers_ID 
    JOIN AC_Statement_Details d
        ON t.AC_Statements_ID = d.AC_Statements_ID
    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
        ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE VIEW vw_SYS_AT_Filters AS  SELECT SYS_AT_Filters_ID AS [ID],  Description AS [Description],  Filter AS [Filter]   FROM SYS_AT_Filters




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

Create View vw_AC_Suppliers
As

Select 
	ss.AO_Suppliers_ID As 'Supplier ID', 
	IsNull(ss.Supplier_Name,'') As 'Name', 
	IsNull(ss.Supplier_Number,'') As 'Supplier No', 
	IsNull(ss.Old_Code,'') As 'Account No', 
	ISNULL(Convert(Varchar(19),ss.[Start_Date],121),'') As 'Start Date',
	
	--ss.Slu_AW_Active_ID, 
	IsNull(ac.[Description],'') As 'Active',
	Case IsNull(Use_Supplier_Discount_Defaults,0)
		When 0 Then 'No'
		Else 'Yes'
	End As 'Use Discount Defaults', 
	--ss.AW_Trade_Discount_Formula_ID, 
	IsNull(td.[Description],'') AS 'Trade Discount',
	--ss.AW_Rebate_Discount_Formula_ID, 
	IsNull(rd.[Description],'') As 'Rebate Discount',
	
	--ss.Use_Other_Discount_Control_Acc, 	
	Case IsNull(Use_Other_Discount_Control_Acc,0)
		When 0 Then 'No'
		Else 'Yes'
	End As 'Use Other Discount Account', 
	--ss.AB_Other_Discounts_Account_ID, 
	IsNull(oa.[Description],'') As 'Other Discount Account',
	--ss.Use_Rebate_Discount_Control_Acc, 
	Case IsNull(Use_Rebate_Discount_Control_Acc,0)
		When 0 Then 'No'
		Else 'Yes'
	End As 'Use Rebate Discount Account', 
	--ss.AB_Rebate_Discount_Account_ID, 
	IsNull(oa.[Description],'') As 'Rebate Discount Account',
	
	--ss.Slu_AW_Banks_ID,
	IsNull(sb.[Description],'') As 'Bank', 
	IsNull(Bank_Branch_Code,'') As 'Bank Branch Code', 
	IsNull(ss.Bank_Branch,'') As 'Bank Branch', 
	IsNull(ss.Account_Name,'') As 'Bank Account Name', 
	IsNull(ss.Account_Number,'') As 'Bank Account No', 
	

	IsNull(ss.Credit_Limit,0) As 'Credit Limit', 
	--ss.Slu_AW_Credit_Terms_ID, 
	IsNull(ct.[Description],'') As 'Credit Terms',
	IsNull(ss.Default_Settlement_Discount,0) As 'Default Settlement Disc', 
	IsNull(ss.Supplier_Contact,'') As 'Contact Name', 
	--ss.Sys_AC_Account_Status_ID,
	--ss.Lup_AO_Purchase_Price_Types_ID,
	IsNull(lp.[Description],'') AS 'Purchase Price', 
	--ss.AW_YesNo_Apply_Product_Levy
	IsNull(pl.[Description],'') As 'Apply Product Levy',

	--ss.Sys_AC_Account_Types_ID, 
	IsNull(at.[Description],'') As 'Account Type',
	IsNull(sa.[Description],'') As 'Account Status', 
	--ss.Sys_AW_Tax_Codes_ID, 
	IsNull(tc.[Description],'') As 'Tax Code',
	IsNull(ss.Tax_Number,'') As 'Tax Number', 
	
	--ss.Sys_AO_Delivery_Methods_ID, 
	IsNull(dm.[Description],'') As 'Delivery Method',
	
	--ss.Lup_AO_Supplier_Types_ID,
	IsNull(st.[Description],'') As 'Supplier Type', 
	--ss.Lup_AO_Supplier_Groups_ID,
	IsNull(sg.[Description],'') As 'Supplier Group', 
	
	IsNull(ss.Notes,'') As 'Notes', 

	IsNull(ss.Post_Box,'') As 'Post Box', 
	IsNull(ss.Post_Office,'') As 'Post Office', 
	IsNull(ss.Post_Code,'') As 'Post Code', 

	IsNull(ss.Street_Address,'') As 'Street Address', 
	IsNull(ss.Suburb,'') As 'Suburb', 
	IsNull(ss.City,'') As 'City', 
	IsNull(ss.Street_Post_Code,'') As 'Street Code', 

	--ss.Slu_AW_Countries_ID, 
	IsNull(cc.[Description],'') As 'Country',
	IsNull(ss.Supplier_Telephone,'') As 'Tel No', 
	IsNull(ss.Contact_Cellphone,'') As 'Contact Cell No', 
	IsNull(ss.Supplier_Fax,'') As 'Fax No',  

	IsNull(ss.Web_Site_URL,'') As 'Web Site URL', 
	IsNull(ss.Orders_URL,'') As 'Orders URL', 
	IsNull(ss.Email_Address,'') As 'E-mail Address',
	Convert(Varchar(19),ss.Date_Captured,121) As 'Date Captured'

	--ss.Date_Captured, 
	--ss.User_ID, 
	--ss.AW_User_Companies_ID, 
	--ss.Touched, 
From AO_Suppliers ss
	Left Outer Join Lup_AO_Purchase_Price_Types lp
		On SS.Lup_AO_Purchase_Price_Types_ID = lp.Lup_AO_Purchase_Price_Types_ID
	Left Outer Join AW_Formulas td
		On ss.AW_Trade_Discount_Formula_ID = td.AW_Formulas_ID
	Left Outer Join AW_Formulas rd
		On ss.AW_Rebate_Discount_Formula_ID = rd.AW_Formulas_ID
	Left Outer Join AB_Accounts oa
		On ss.AB_Other_Discounts_Account_ID = oa.AB_Accounts_ID
	Left Outer Join AB_Accounts ra
		On ss.AB_Rebate_Discount_Account_ID = ra.AB_Accounts_ID
	Left Outer Join Slu_AW_Credit_Terms ct
		On ss.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID	
	Left Outer Join Sys_AC_Account_Status sa
		On ss.Sys_AC_Account_Status_ID = sa.Sys_AC_Account_Status_ID
	Left Outer Join Sys_AW_Tax_Codes tc
		On ss.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
	Left Outer Join Slu_AW_Countries cc
		On ss.Slu_AW_Countries_ID = cc.Slu_AW_Countries_ID
	Left Outer Join Slu_AW_Banks sb
		On ss.Slu_AW_Banks_ID = sb.Slu_AW_Banks_ID
	Left Outer Join Slu_AW_Active ac
		On ss.Slu_AW_Active_ID = ac.Slu_AW_Active_ID
	Left Outer Join Sys_AO_Delivery_Methods dm
		On ss.Sys_AO_Delivery_Methods_ID = dm.Sys_AO_Delivery_Methods_ID
	Left Outer Join Lup_AO_Supplier_Types st
		On ss.Lup_AO_Supplier_Types_ID = st.Lup_AO_Supplier_Types_ID
	Left Outer Join Lup_AO_Supplier_Groups sg
		On ss.Lup_AO_Supplier_Groups_ID = sg.Lup_AO_Supplier_Groups_ID
	Left Outer Join Sys_AC_Account_Types at
		On ss.Sys_AC_Account_Types_ID = at.Sys_AC_Account_Types_ID
	Left Outer Join Slu_AW_YesNo pl
		On ss.AW_YesNo_Apply_Product_Levy = pl.Slu_AW_YesNo_ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :vw_AO_Transactions
--Purpose       :Select Supplier Transactions
--Functionality :
--Parameters    :
--Date          :2002/01/07
--Authors       :TB
--Version       :1.0.0
--Mods          :28/10/02 - Added Slu_AW_Months_ID & Slu_AW_Years_ID
--              :           for Option 10 Account Balances tab in
--              :           sp_AO_Transaction_Headers_Unallocated_Select
--              :01/11/02 - Added To_Be_Paid_Amount field
--              :17/04/04 - Added Comment from AO_Transactions as [Comment]
--              :           and renamed Comment from AW_Comments as [Notes]
------------------------------------------------------------------------------

CREATE           VIEW vw_AO_Transactions

AS

    SELECT
        t.AO_Transactions_ID,
        t.AO_Suppliers_ID,
        t.Supplier_Reference, 
        t.Sys_AW_Transaction_Types_ID,
        t.Document_Number,
        t.Document_Date, 
        t.Slu_AW_Months_ID,
        t.Slu_AW_Years_ID,
        t.AO_GRV_ID,
        t.Comment AS [Comment],
        t.AW_Comments_ID,
        c.Comment AS [Notes], 
        t.Trade_Discount_Total,
        t.Rebate_Discount_Total,
        t.Other_Discount_Total, 
        t.Net_Amount,
        t.Total_Tax_Amount,
        t.Total_Amount, 
        t.Payment_Amount,
        t.To_Be_Paid_Amount,
        t.Date_Captured,
        t.User_ID, 
        t.AW_User_Companies_ID,
        t.Slu_AW_Active_ID
    FROM AO_Transactions t
        LEFT OUTER JOIN AW_Comments c
            ON t.AW_Comments_ID = c.AW_Comments_ID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-----------------------------------------------------------------------------
--Description  :vw_AP_Stock_Month_End
--Purpose      :Retrieves Stock On-Hand Data from AP_Products
--             :    for Stock Valuations
--Date         :2002/02/19
--Revised      :
--Authors      :TB
--Version      :1.0.0
-----------------------------------------------------------------------------

CREATE   VIEW dbo.vw_AP_Stock_Month_End

AS

    SELECT
        ph.AP_Products_History_ID AS [ID],
        p.AP_Products_ID AS [Product_ID],

        ISNULL(Product_Code, '') AS [Code],
        ISNULL(p.[Description], '') AS [Product],
        ISNULL(Pack_Size, 0) AS [Size],
        ISNULL(Last_Cost, 0) AS [Unit Cost],
        ISNULL(Price1_Price1, 0) AS [Price],
        ISNULL(On_Hand, 0) AS [OnHand],
        ISNULL(Min_Order_Qty, 0) AS [Min],
        ISNULL(Max_Order_Qty, 0) AS [Max],

        me.AW_Period_Procedures_ID AS [ME_ID], 
        me.Date_Captured AS [Date],
        ISNULL(ph.Cost, 0) AS [Cost],
        ISNULL(ph.Qty, 0) AS [Qty],
        ROUND(ISNULL(ph.Cost, 0) * ISNULL(ph.Qty, 0), 2) AS [Total_Cost], 
        p.Lup_AP_Product_Manufacturers_ID AS [Manufacturer_ID],
        p.Lup_AP_Product_Types_ID AS [Type_ID], 
        p.Lup_AP_Product_Groups_ID AS [Product_Group_ID],
        p.Lup_AP_Product_Departments_ID AS [Department_ID], 
        p.Lup_AP_Product_Locations_ID AS [Location_ID],
        p.Lup_AP_Discount_Groups_ID AS [Discount_Group_ID], 
        p.Lup_AP_Commission_Groups_ID AS [Commission_Group_ID],
        cg.[Description] AS [Commission_Group],
        dg.[Description] AS [Discount_Group], 
        pl.[Description] AS [Location],
        pm.[Description] AS [Manufacturer],
        pt.[Description] AS [Type],
        pg.[Description] AS [Product_Group],
        pd.[Description] AS [Department], 
        me.AW_User_Companies_ID AS [Company_ID]
    FROM AP_Products p
        INNER JOIN AP_Products_History ph
            ON p.AP_Products_ID = ph.AP_Products_ID
        INNER JOIN AW_Period_Procedures me
            ON ph.AW_Period_Procedures_ID = me.AW_Period_Procedures_ID
        LEFT OUTER JOIN Lup_AP_Product_Manufacturers pm
            ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID
        LEFT OUTER JOIN Lup_AP_Product_Types pt
            ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
        LEFT OUTER JOIN Lup_AP_Product_Groups pg
            ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID
        LEFT OUTER JOIN Lup_AP_Product_Departments pd
            ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID
        LEFT OUTER JOIN Lup_AP_Commission_Groups cg
            ON p.Lup_AP_Commission_Groups_ID = cg.Lup_AP_Commission_Groups_ID
        LEFT OUTER JOIN Lup_AP_Discount_Groups dg
            ON p.Lup_AP_Discount_Groups_ID = dg.Lup_AP_Discount_Groups_ID
        LEFT OUTER JOIN Lup_AP_Sell_By_Codes sbc
            ON p.Lup_AP_Sell_By_Codes_ID = sbc.Lup_AP_Sell_By_Codes_ID
        LEFT OUTER JOIN Lup_AP_Product_Locations pl
            ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   : Selects the Transaction for Dynamic reports
--Purpose       : Dynamic SQL statements have a 8,000 character limit
--Functionality : Overcome 8,000 character limit
--Parameters    : 
--Date          : 2017/06/19
--Authors       : RL
--Version       : 1
-------------------------------------------------------------------------------
CREATE     VIEW [dbo].[vw_AST]

AS

    SELECT *
    FROM AS_Transactions

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :vw_AS_POS_Customers_Select
--Purpose       :POS Customers SELECT
--Functionality :NB: Parameter name must be identical to the field aliases
--              :    in sp_AS_POS_Customer_Insert_Update with a '@' prefix
--Date          :2000/03/21
--Authors       :TB
--Version       :
--MODS          :09/09/02 - Inserted Slu_AW_Active_ID as ActiveID
--              :           to Select ONLY Active Customers (Enabled)
--              :14/09/02 - Added CustTaxRate to OVERRIDE POS Product-level Tax
--              :           with setting in AC_Customers.Sys_AW_Tax_Codes_ID
--              :02/10/02 - Replaced AC_Customers.Account_Balance with
--              :           SUM(Transactions - Payments) from AS_Transactions
--              :08/10/02 - Fixed AC_Customers.Account_Balance incorrectly
--              :           showing sum of ALL TRANSACTIONS TYPES
--              :25/02/04 - Added [TermsValue] from Slu_AW_Credit_Terms for
--              :           Sales Promotions terms validation in POS
--              :20/08/04 - Added [AccountType] and [AccountTypeID] from
--              :           Sys_AC_Account_Types for Central Billing
--              :20/08/04 - Added [CustomerGroup] and [CustomerGroupID] from
--              :           Lup_AC_Customer_Groups for E-mail Marketing
--              :09/12/04 - Added [TaxNumber] input parameters for new fields
--              :           in POS Customer Add/Edit
--              :02/01/05 - Added ISNULL validation to [AccountBalance] and [CreditLimit]
--              :           fields causing POS Credit Limit Exceeded message if balance
--              :           is zero when all trans are paid
--2004.3.2      :11/10/06 - Added new [NetBilling] and [PurchaseOrder] fields
--2004.3.7      :24/07/07 - Added new [CostPlusBilling] field
--              :17/08/07 - Added new [TermsID] field for Promotions !!
-------------------------------------------------------------------------------

CREATE                      VIEW vw_AS_POS_Customers_Select

AS

	SELECT     
		a.Surname AS [Name], 
		a.Firstnames AS [FirstNames], 
		a.Initials AS [Initials],
        a.Tax_Number AS [TaxNumber],
		a.Suburb AS [Suburb], 
		a.Cell_No AS [CellNo], 
		a.Work_Tel_No AS [WorkTelNo], 
		a.Home_Tel_No AS [HomeTelNo], 
		a.Street_Address AS [StreetAddress], 
		a.City AS [City],
        ISNULL(a.Credit_Limit, 0) AS [CreditLimit], 
        ISNULL(
            (
                SELECT SUM(ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0))
                FROM AS_Transactions h
                WHERE a.AC_Customers_ID = h.AC_Customers_ID AND
                      ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) <> 0 AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                      h.Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                      h.Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                      h.Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                      h.Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
                      h.Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
                      h.Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                      h.Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
            ), 0) AS [AccountBalance], 
		a.Work_Email AS [WorkEmail], 
		a.Notes AS [Notes], 

		a.Sys_AC_Account_Status_ID AS [AccountStatusID], 
		a.Lup_AC_Customer_Types_ID AS [CustomerTypeID],
		a.Lup_AC_Customer_Groups_ID AS [CustomerGroupID],

		b.[Description] AS [AccountStatus], 
		c.[Description] AS [CustomerType],
		g.[Description] AS [CustomerGroup],

		a.Date_Captured AS [Date], 
		a.[User_ID] AS [UserID], 
		a.AW_User_Companies_ID AS [CompanyID], 
		a.AC_Customers_ID AS [CustomerID], 
		-1 as [ActorTypeID],
		a.Lup_AC_Discount_Categories_ID,
        a.Slu_AW_Active_ID AS [ActiveID],
        ISNULL(d.Tax_Rate, 0) AS [CustTaxRate],
        a.Slu_AW_Credit_Terms_ID AS [TermsID],
        e.Terms_Value AS [TermsValue],
        f.[Description] AS [AccountType], 
        a.Sys_AC_Account_Types_ID AS [AccountTypeID],

        a.AW_YesNo_Net_Billing_ID AS [NetBilling], 
        a.AW_YesNo_Purchase_Order_ID AS [PurchaseOrder],
        a.AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling]
	FROM AC_Customers a        LEFT JOIN Sys_AC_Account_Status b
            ON a.Sys_AC_Account_Status_ID = b.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AC_Customer_Types c
            ON a.Lup_AC_Customer_Types_ID = c.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes d
            ON a.Sys_AW_Tax_Codes_ID = d.Sys_AW_Tax_Codes_ID
        LEFT JOIN Slu_AW_Credit_Terms e
            ON a.Slu_AW_Credit_Terms_ID = e.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Account_Types f
            ON a.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID
        LEFT JOIN Lup_AC_Customer_Groups g
            ON a.Lup_AC_Customer_Groups_ID = g.Lup_AC_Customer_Groups_ID


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :vw_AS_POS_Transaction_Headers_Select
--              :The view that gets the Transaction Headers
--Date          :2002/01/11
--Called By     :sp_AS_POS_Transaction_Document_Select
--Authors       :TB
--Version       :1.0.0
--MODS          :07/10/02 - Commented 'CashedUp' and 'DayEnd' columns because
--              :(Post SR1) their values get carried over to any subsequent
--              :           POS transaction e.g. from Proforma to Invoice which
--              :           causes unexpected results when attempting to balance
--              :           to previous completed Day-End
--2004.5.3      :11/09/11 - Added [SmallComment] field to replace t.Transmitted
--              :           to fetch AS_Transactions.Comment field as POS 'Asset'
--              :           Done in vw_AS_POS_Transaction_Headers_Select WAY BACK !!!
------------------------------------------------------------------------------

CREATE             VIEW vw_AS_POS_Transaction_Headers_Select

AS

	SELECT     
        t.AS_Transactions_ID AS [DocumentID], 
        t.AC_Customers_ID AS [CustomerID], 
        t.AB_Accounts_ID AS [AccountID], 
        t.Transaction_Number AS [No], 
        t.Total_Amount AS [Total Amount], 
        t.Payment_Amount AS Payment, 
        t.Transaction_Date AS [Date], 
        t.Expiry_Date AS [ExpiryDate], 
        t.Version_Number AS [VersionNumber], 
        ISNULL(t.Customer_Reference, '') AS [CustomerReference], 
        c.Comment, 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
        t.Lup_AS_Marketing_Indicators_ID AS [MarketingIndicatorsID], 
        t.Lup_AW_Stores_ID AS [StoreID], 
        t.Lup_AW_Workstations_ID AS [WorkstationID], 
        t.Lup_AS_Tills_ID AS [TillID], 
        t.Lup_AS_Cashiers_ID AS [CashierID], 
        t.Lup_AS_Reps_ID AS [RepID], 
        t.Slu_AW_Currencies_ID AS [CurrencyID], 
        t.Old_Sys_AW_Transaction_Types_ID AS [OldTransactionTypeID], 
        t.Cancelled_User_ID AS [CancelledUserID], 
        t.Cancelled_DateTime AS [CancelledDate], 
--         t.Cashed_Up AS [CashedUp],
--         t.Day_End AS [DayEnd], 
        NULL AS [CashedUp],
        NULL AS [DayEnd], 
        ISNULL(t.Comment, '') as [SmallComment],    --t.Transmitted, 
        t.Date_Captured AS [DateCaptured], 
        t.[User_ID] AS [UserID], 
        t.AW_User_Companies_ID AS [CompanyID],
        t.AW_Comments_ID as [CommentID]
	FROM  AS_Transactions t
        LEFT JOIN AW_Comments c
            ON t.AW_Comments_ID = c.AW_Comments_ID
	WHERE t.Slu_AW_Active_ID <> 0














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :vw_AS_POS_Transaction_Headers_Select_Absolute
--              :Used at POS for absolute values of the Transaction
--Date          :2002/01/11
--Called By     :sp_AS_POS_Transaction_Document_Select_Filtered
--Authors       :TB
--Version       :1.0.0
--MODS          :07/10/02 - Commented 'CashedUp' and 'DayEnd' columns because
--              :(Post SR1) their values get carried over to any subsequent
--              :           POS transaction e.g. from Proforma to Invoice which
--              :           causes unexpected results when attempting to balance
--              :           to previous completed Day-End 
--              :09/01/03 - Added [SmallComment] field to replace t.Transmitted
--              :           to return Asset in AS_Transactions.Comment field
--              :09/05/04 - Changed WHERE clause to select ONLY ACTIVE transactions.
--              :           Previously selecting ALL NOT DEACTIVATED also returned
--              :           transactions disabled (Active = 2) in Expire Transactions
------------------------------------------------------------------------------

CREATE                VIEW vw_AS_POS_Transaction_Headers_Select_Absolute

AS

	SELECT     
        t.AS_Transactions_ID AS [DocumentID], 
        t.AC_Customers_ID AS [CustomerID], 
        t.AB_Accounts_ID AS [AccountID], 
        t.Transaction_Number AS [No], 
        ABS(t.Total_Amount) AS [Total Amount], 
        ABS(t.Payment_Amount) AS [Payment], 
        t.Transaction_Date AS [Date], 
        t.Expiry_Date AS [ExpiryDate], 
        t.Version_Number AS [VersionNumber], 
        ISNULL(t.Customer_Reference, '') AS [CustomerReference], 
        c.Comment, 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
        t.Lup_AS_Marketing_Indicators_ID AS [MarketingIndicatorsID], 
        t.Lup_AW_Stores_ID AS [StoreID], 
        t.Lup_AW_Workstations_ID AS [WorkstationID], 
        t.Lup_AS_Tills_ID AS [TillID], 
        t.Lup_AS_Cashiers_ID AS [CashierID], 
        t.Lup_AS_Reps_ID AS [RepID], 
        t.Slu_AW_Currencies_ID AS [CurrencyID], 
        t.Old_Sys_AW_Transaction_Types_ID AS [OldTransactionTypeID], 
        t.Cancelled_User_ID AS [CancelledUserID], 
        t.Cancelled_DateTime AS [CancelledDate], 
--         t.Cashed_Up AS [CashedUp],
--         t.Day_End AS [DayEnd], 
        NULL AS [CashedUp],
        NULL AS [DayEnd], 
        ISNULL(t.Comment, '') as [SmallComment],    --t.Transmitted, 
        t.Date_Captured AS [DateCaptured], 
        t.[User_ID] AS [UserID], 
        t.AW_User_Companies_ID AS [CompanyID],
        t.AW_Comments_ID as [CommentID]
	FROM  AS_Transactions t
        LEFT JOIN AW_Comments c
            ON t.AW_Comments_ID = c.AW_Comments_ID
	WHERE t.Slu_AW_Active_ID = 1
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--*** REDUNDANT ?? ***


-- references vw_AW_Banks_Cards_Union and
-- CANNOT be created UNTIL vw_AW_Banks_Cards_Union exists

-------------------------------------------------------------------------------
--Description   : vw_AS_Payments_Select
--Purpose       : Fetch the Payments for Banking
--Functionality : Tables: AS_Transaction_Payments
--              :         Sys_AW_Payment_Methods
--              :         vw_AW_Banks_Cards_Union
--              :
--Called from   :         sp_AS_Banking_Payments_Select
--              :
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            VIEW vw_AS_Payments_Select

AS

    SELECT pm.Description as Method,		
           cbu.Description as Institution,
           tp.Amount,
           tp.Payor_Name as Payor,
           tp.Card_Expiry_Date as [Expiry/Branch],
           tp.Card_Number as [No],
           tp.Authorisation_Number as Auth,
           tp.Banked,
           tp.Sys_AW_Payment_Methods_ID as MethodID,
           tp.Slu_AS_Card_Institutions_ID as InstitutionID,
           tp.AW_User_Companies_ID as CompanyID

    FROM AS_Transaction_Payments tp
    	LEFT JOIN Sys_AW_Payment_Methods pm
            ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID
    	LEFT JOIN vw_AW_Banks_Cards_Union cbu
            ON tp.Slu_AS_Card_Institutions_ID = cbu.ID AND
               cbu.TypeID = pm.Sys_AW_Institution_Types_ID


--SELECT * FROM vw_AS_Payments_Select








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








--*** REDUNDANT ?? ***


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Description   : Selects the Transaction Details for POS
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/6/25
--Authors       : GL
--Version       : 1
-------------------------------------------------------------------------------
CREATE     VIEW vw_AS_Transaction_Details

AS

    SELECT 
        p.Description as Description, 
        p.Product_Code as Code, 
        td.Quantity as Qty, 
        td.Unit_Cost as Cost, 
        td.Unit_Price as Price, 
        td.Original_Price as [OriginalPrice], 
        td.Discount_Amount as [Discount], 
        td.Tax_Amount as Tax, 
        td.Extended_Amount as [Amount], 
        td.Commission_Amount as Commission, 
        td.AP_Promotion_Products_ID as Item, 
        
        td.AP_Products_ID as ProductID, 
        td.AS_Transactions_ID as TransactionID,
        td.Date_Captured as [Date], 
        td.User_ID as UserID, 
        td.AW_User_Companies_ID as CompanyID,
        td.AS_Transaction_Details_ID as ID
    FROM AS_Transaction_Details td LEFT JOIN AP_Products p ON td.AP_Products_ID = p.AP_Products_ID
    WHERE  td.Slu_AW_Active_ID = 1 








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

Create View vw_AS_Transaction_Details_Full
As

Select 
	th.AS_Transactions_ID As 'Tran Id', 
	th.AC_Customers_ID As 'Customer ID',
	ISNULL(cd.Firstnames, '') + ISNULL(cd.Surname, '') + ISNULL(', ' + cd.Initials, '') AS 'Customer',
	--th.Sys_AW_Transaction_Types_ID	
	IsNull(tt.[Description],'') As 'Transaction Type', 
	IsNull(th.Transaction_Number,'') As 'Transaction No',
	Convert(Varchar(19),th.Transaction_Date,121) As 'Transaction Date',
	IsNull(th.Customer_Reference,'') As 'Ref No', 
	IsNull(th.Comment,'') As 'Comment', 
	 
	IsNull(th.Total_Cost,0) As 'Header Total Cost', 
	IsNull(th.Amount,0) As 'Header Amount', 
	IsNull(th.Total_Tax_Amount,0) As 'Header Tax', 
	IsNull(th.Total_Discount_Amount,0) As 'Header Discount', 
	IsNull(th.Total_Amount,0) As 'Header Total Amount', 
	IsNull(th.Payment_Amount,0) As 'Header Payment Amount',
	--th.Lup_AS_Tills_ID, 
	IsNull(ti.[Description],'') As 'Till',
	--th.Lup_AS_Reps_ID,  
	IsNull(tr.[Description],'') As 'Sales Rep', 	
	Convert(Varchar(19),th.Day_End,121) As 'Day End',		
	Convert(Varchar(19),th.Date_Captured,121) As 'Date Captured',	
	--th.User_ID,
	ISNULL(us.Surname, '') + ISNULL(', ' + us.FirstName, '') AS 'User', 	
	--th.Slu_AW_Active_ID,
	IsNull(ai.[Description],'') As 'Active',
	--th.AW_Comments_ID,	
	IsNull(tc.Comment,'') As 'Transaction Comment', 
	
	--th.AB_Accounts_ID,
	--IsNull(ac.Description,'<None>') As 'GL Account', 
	--th.Expiry_Date, 
	--th.Version_Number, 
	--th.Lup_AS_Marketing_Indicators_ID, 
	--th.Lup_AW_Stores_ID, 
	--th.Lup_AW_Workstations_ID, 
	--th.Lup_AS_Cashiers_ID, 
	--th.Slu_AW_Currencies_ID, 
	--th.Old_Sys_AW_Transaction_Types_ID, 
	--th.Cancelled_User_ID, 
	--th.Cancelled_DateTime, 
	--th.Cashed_Up, 
	--th.Transmitted, 
	--th.AW_User_Companies_ID, 
	--th.Touched, 
	
	IsNull(pr.Product_Code,'') As 'Product Code',
	IsNull(pr.[Description],'') As 'Product Description',
	--td.Lup_AP_Product_Bins_ID,
	IsNull(pb.[Description],'') As 'Product Bin',
	IsNull(td.Quantity,0) As 'Detail Qty', 
	IsNull(td.Unit_Cost,0) As 'Detail Cost', 
	IsNull(td.Unit_Price,0) As 'Detail Unit Price', 
	IsNull(td.Original_Price,0) As 'Detail Original Price', 
	IsNull(td.Original_Discount,0) As 'Detail Original Discount', 
	IsNull(td.Discount_Amount,0) As 'Detail Discount', 
	IsNull(td.Tax_Amount,0) As 'Detail Tax', 
	IsNull(td.Extended_Amount,0) As 'Detail Total Amount',
	--td.Slu_AW_Active_ID,
	IsNull(da.[Description],'') As 'Detail Active',
	--td.AS_Job_References_ID,  
	IsNull(af.Job_No,'') As 'Job Ticket',
	IsNull(td.Serial_No,'') As 'Serial No', 
	IsNull(td.Make,'') As 'Make', 
	IsNull(td.Customer,'') As 'Job Customer', 
	IsNull(td.TDHeader,'') As 'Detail Header', 
	IsNull(td.TDDetail,'') As 'Detail Detail' 

	--td.AS_Transaction_Details_ID, 
	--td.AS_Transactions_ID, 
	--td.AP_Products_ID,
	--td.Commission_Amount, 
	--td.AP_Promotion_Products_ID, 
	--td.Date_Captured, 
	--td.User_ID, 
	--td.AW_User_Companies_ID, 
	--td.Touched, 
	--td.Back_Order, 
	--td.Consignment_Left, 
From AS_Transactions th
	Left Outer Join AS_Transaction_Details td
		On th.AS_Transactions_ID = td.AS_Transactions_ID
	Left Outer Join AC_Customers cd
		On th.AC_Customers_ID = cd.AC_Customers_ID
	Left Outer Join AW_Comments tc
		On th.AW_Comments_ID = tc.AW_Comments_ID
	Left Outer Join Sys_AW_Transaction_Types tt
		On th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
	Left Outer Join Lup_AS_Tills ti
		On th.Lup_AS_Tills_ID = ti.Lup_AS_Tills_ID
	Left Outer Join Lup_AS_Reps tr
		On th.Lup_AS_Reps_ID = tr.Lup_AS_Reps_ID
	Left Outer Join AW_Users us
		On th.[User_ID] = us.AW_Users_ID
	Left Outer Join Slu_AW_Active ai
		On th.Slu_AW_Active_ID = ai.Slu_AW_Active_ID
	Left Outer Join AP_Products pr
		On td.AP_Products_ID = pr.AP_Products_ID
	Left Outer Join AF_Job_Tickets af
		On td.AS_Job_References_ID = af.AF_Job_Tickets_ID
	Left Outer Join Lup_AP_Product_Bins pb
		On td.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
	Left Outer Join Slu_AW_Active da
		On td.Slu_AW_Active_ID = da.Slu_AW_Active_ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :General View for AS_Transactions
--Date          :2002/03/15
--Authors       :TB
--Version       :1.0.0
--MODS          :25/06/02 - Added t.Comment AS [Comment], c.Comment AS [SysComment]
-------------------------------------------------------------------------------

CREATE           VIEW vw_AS_Transaction_Headers

AS

    SELECT
    	t.Transaction_Number AS [No], 
    	t.Total_Amount AS [Amount], 
    	t.Payment_Amount AS [Payment], 
    	t.Total_Discount_Amount AS [Discount], 
    	t.Total_Tax_Amount AS [Tax],
    	t.Transaction_Date AS [Date], 
    	t.Expiry_Date AS [Expiry], 
    	t.Version_Number AS [Ver], 
    	t.AC_Customers_ID AS [CustomerID],
        t.Comment AS [Comment], 
    	c.Comment AS [SysComment], 
    	t.Sys_AW_Transaction_Types_ID AS [TypeID], 
    	t.Lup_AS_Marketing_Indicators_ID AS [IndID], 
    	t.Lup_AW_Stores_ID AS [StoreID], 
    	t.Lup_AW_Workstations_ID AS [StationID], 
    	t.Lup_AS_Tills_ID AS [TillID], 
    	t.Lup_AS_Cashiers_ID AS [CashierID], 
    	t.Lup_AS_Reps_ID AS [RepID], 
    	t.Slu_AW_Currencies_ID AS [CurrencyID], 
    	t.Cancelled_User_ID AS [CancelUserID], 
    	t.Cancelled_DateTime AS [CancelDate], 
    	t.Cashed_Up AS [CashUp], 
    	t.Day_End AS [DayEnd], 
    	t.Transmitted AS [Transmit], 
    	t.Date_Captured AS [DateCaptured], 
    	t.User_ID AS [UserID], 
    	t.AW_User_Companies_ID AS [CompanyID], 
    	t.AW_Comments_ID as [CommentID],
    	t.Old_Sys_AW_Transaction_Types_ID AS [OldTypeID], 
    	t.AS_Transactions_ID AS [ID]
    	FROM AS_Transactions t
            LEFT JOIN AW_Comments c
                ON t.AW_Comments_ID = c.AW_Comments_ID
    	WHERE t.Slu_AW_Active_ID <> 0












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


CREATE   VIEW vw_AS_Transaction_Payment_Allocations
AS
SELECT     
	td.AS_Transaction_Details_ID AS TransactionDetailID, 
	isnull(td.Quantity,0) AS Qty, 
      p.Sales_Order_Reserved AS SOReserved, 
	p.Quote_Reserved AS QuoteReserved, 
	p.Job_Reserved AS JobReserved, 
	p.AP_Products_ID AS ProductID, 
      t.Sys_AW_Transaction_Types_ID AS TypeID
FROM 
	AS_Transactions t 
		INNER JOIN AS_Transaction_Details td ON td.AS_Transactions_ID = t.AS_Transactions_ID 
		INNER JOIN AP_Products p ON td.AP_Products_ID = p.AP_Products_ID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE       VIEW vw_AS_Transaction_Payments
AS
    SELECT 
        m.Description as						[Method],
        i.Description as							[Institution],
        p.Payor_Name as						[Payor Name], 
        p.Card_Expiry_Date as					[Card Expiry Date], 
        p.Card_Number  as						[Card Number], 
        p.Authorisation_Number as				[Authorisation Number], 
        p.Amount   as							[Amount], 
	
        p.Sys_AW_Payment_Methods_ID as		[MethodID], 
        p.Slu_AS_Card_Institutions_ID as 		[InstitutionID], 
        p.AS_Transactions_ID as  	       		[TransactionID], 
        p.Date_Captured as						[Date], 
        p.[User_ID] as							[UserID], 
        p.AW_User_Companies_ID as			[CompanyID],
        p.AS_Transaction_Payments_ID as		[ID]
    FROM AS_Transaction_Payments p
        LEFT JOIN Sys_AW_Payment_Methods m
            ON p.Sys_AW_Payment_Methods_ID = m.Sys_AW_Payment_Methods_ID
        LEFT JOIN Slu_AS_Card_Institutions I
            ON p.Slu_AS_Card_Institutions_ID = i.Slu_AS_Card_Institutions_ID
	WHERE p.Slu_AW_Active_ID = 1







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :vw_AS_Transactions
--              :General view for Transactions
--Date          :2002/01/13
--Revised	    :
--Authors       :TB
--Version       :1.0.0
--MODS          :30/12/02 - Added t.Comment AS [SmallComment] for POS Asset No
------------------------------------------------------------------------------

CREATE           VIEW vw_AS_Transactions

AS

    SELECT 
    	t.AS_Transactions_ID,
    	t.AC_Customers_ID,
    	t.AB_Accounts_ID,
    	t.Transaction_Number,
    	t.Total_Cost,
    	t.Amount,
    	t.Total_Tax_Amount,
    	t.Total_Discount_Amount,
    	t.Total_Amount,
    	t.Payment_Amount,
    	t.Transaction_Date,
    	t.Expiry_Date,
    	t.Version_Number,
    	t.Customer_Reference,
    	c.Comment,
    	t.Sys_AW_Transaction_Types_ID,
    	t.Lup_AS_Marketing_Indicators_ID,
    	t.Lup_AW_Stores_ID,
    	t.Lup_AW_Workstations_ID,
    	t.Lup_AS_Tills_ID,
    	t.Lup_AS_Cashiers_ID,
    	t.Lup_AS_Reps_ID,
    	t.Slu_AW_Currencies_ID,
    	t.Old_Sys_AW_Transaction_Types_ID,
    	t.Cancelled_User_ID,
    	t.Cancelled_DateTime,
    	t.Cashed_Up,
    	t.Day_End,
    	t.Transmitted,
    	t.Date_Captured,
    	t.User_ID,
    	t.AW_User_Companies_ID,
    	t.Slu_AW_Active_ID,
    	t.AW_Comments_ID as CommentID,
        t.Comment AS [SmallComment]
    FROM AS_Transactions t
        LEFT JOIN fn_AW_Comments(-7) c
            ON t.AW_Comments_ID = c.ID













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









------------------------------------------------------------------------------
--Description   :vw_AS_Transactions_View
--              :The view that gets the Transaction Headers
--Date          :2002/01/11
--Revised	    :
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE      VIEW vw_AS_Transactions_View

AS

    SELECT 
    	t.AS_Transactions_ID,
    	t.AC_Customers_ID,
    	t.AB_Accounts_ID,
    	t.Transaction_Number ,
    	t.Total_Cost  ,
    	t.Amount ,
    	t.Total_Tax_Amount  ,
    	t.Total_Discount_Amount  ,
    	t.Total_Amount ,
    	t.Payment_Amount ,
    	t.Transaction_Date ,
    	t.Expiry_Date,
    	t.Version_Number ,
    	t.Customer_Reference ,
    	c.Comment ,
    	t.Sys_AW_Transaction_Types_ID,
    	t.Lup_AS_Marketing_Indicators_ID,
    	t.Lup_AW_Stores_ID,
    	t.Lup_AW_Workstations_ID,
    	t.Lup_AS_Tills_ID,
    	t.Lup_AS_Cashiers_ID,
    	t.Lup_AS_Reps_ID,
    	t.Slu_AW_Currencies_ID,
    	t.Old_Sys_AW_Transaction_Types_ID,
    	t.Cancelled_User_ID,
    	t.Cancelled_DateTime,
    	t.Cashed_Up,
    	t.Day_End,
    	t.Transmitted,
    	t.Date_Captured,
    	t.User_ID,
    	t.AW_User_Companies_ID,
    	t.Slu_AW_Active_ID,
    	t.AW_Comments_ID as CommentID
    FROM AS_Transactions t
        LEFT JOIN AW_Comments c
            ON t.AW_Comments_ID = c.AW_Comments_ID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE VIEW dbo.vw_AS_Users_Roles
AS
SELECT     u.AW_Users_ID AS UserID, ISNULL(u.Surname, '') + ISNULL(', ' + u.FirstName, '') AS Fullname, r.AW_Roles_ID AS RoleID, 
                      r.Description AS RoleDescription, ur.AW_User_Companies_ID AS CompanyID
FROM         dbo.AW_Users u INNER JOIN
                      dbo.AW_Users_Per_Role ur ON u.AW_Users_ID = ur.AW_Users_ID INNER JOIN
                      dbo.AW_Roles r ON ur.AW_Roles_ID = r.AW_Roles_ID





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  VIEW dbo.vw_AW_Transaction_Detail_Described
AS
SELECT     
	td.AS_Transaction_Details_ID AS ID, 
	td.AS_Transactions_ID AS TransactionID, 
	p.Description AS Product, 
	p.Product_Code AS [Product Code], 
	td.Quantity AS Qty, 
	td.Unit_Cost AS Cost, 
	td.Unit_Price AS Price, 
	td.Original_Price AS [Original Price], 
	td.Discount_Amount AS Discount, 
	td.Tax_Amount AS Tax, 
	td.Extended_Amount AS Total, 
	td.Commission_Amount AS Commission
FROM AS_Transaction_Details td 
	INNER JOIN AP_Products p ON td.AP_Products_ID = p.AP_Products_ID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

CREATE   VIEW dbo.vw_AW_Transaction_Header_Described
AS
	SELECT     
		t.AS_Transactions_ID AS ID, 
		c.Surname + ISNULL(', ' + c.Firstnames, '') AS Customer, 
		a.Description AS Account, 
		t.Transaction_Number AS [Trans No], 
             t.Total_Cost AS Cost, 
		t.Amount AS Amount, 
		t.Total_Tax_Amount AS Tax, 
		t.Total_Discount_Amount AS Discount, 
		t.Total_Amount AS Total, 
             t.Payment_Amount AS Payment, 
		t.Transaction_Date AS Date, 
		t.Customer_Reference AS [Customer Ref]
		
	FROM AS_Transactions t 
		INNER JOIN  AC_Customers c ON t.AC_Customers_ID = c.AC_Customers_ID 
		INNER JOIN AB_Accounts a ON t.AB_Accounts_ID = a.AB_Accounts_ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









CREATE    VIEW vw_RPT_AO_Supplier_List

AS

SELECT
        s.AO_Suppliers_ID AS [ID] ,
        s.Supplier_Name AS [Name] ,
        s.Supplier_Number AS [Number] ,
        s.Old_Code AS [Old Code] ,
        t.[Description] AS [Purchase Price Types] ,
        s.Use_Supplier_Discount_Defaults AS [Use Supplier Discount Defaults] ,
        tf.[Description] AS [Trade Discount Formula] ,
        rf.[Description] AS [Rebate Discount Formula] ,
        od.[Description] AS [Other Discounts Account] ,
        rd.[Description] AS [Rebate Discount Account] ,
        s.Use_Other_Discount_Control_Acc AS [Use Other Discount Control Acc] ,
        s.Use_Rebate_Discount_Control_Acc AS [Use Rebate Discount Control Acc] ,
        s.Account_Balance AS [Balance] ,
        s.Current_Balance AS [Current] ,
        s.Days_30 AS [30 Days] ,
        s.Days_60 AS [60 Days] ,
        s.Days_90 AS [90 Days] ,
        s.Days_120 AS [120 Days] ,
        s.Days_150 AS [150 Days] ,
        s.Days_180 AS [180 Days] ,
        s.Start_Date AS [Start Date] ,
        s.Credit_Limit AS [Credit Limit] ,
        ct.[Description]  AS [Credit Terms] ,
        s.Default_Settlement_Discount AS [Std Sett Disc] ,
        s.Supplier_Contact AS [Contact] ,
        st.[Description]  AS [Account Status] ,
        tc.[Description]  AS [Tax Code] ,
        s.Tax_Number AS [Tax Number] ,
        s.Post_Box AS [Post Box] ,
        s.Post_Office AS [Post Office] ,
        s.Post_Code AS [Post Code] ,
        s.Street_Address AS [Street Address] ,
        s.Suburb AS [Suburb] ,
        s.City AS [City] ,
        s.Street_Post_Code AS [Street Code] ,
        co.[Description]  AS [Country] ,
        s.Supplier_Telephone AS [Tel No] ,
        s.Contact_Cellphone AS [Cell No] ,
        s.Supplier_Fax AS [Fax] ,
        s.Web_Site_URL AS [Web URL] ,
        s.Orders_URL AS [Orders_URL] ,
        s.Email_Address AS [Email Address] ,
        s.Notes AS [Notes] ,
        ba.[Description]  AS [Bankers] ,
        s.Bank_Branch AS [Bank Branch] ,
        s.Bank_Branch_Code AS [Branch Code] ,
        s.Account_Name AS [Account Name] ,
        s.Account_Number AS [Account No] ,
        ac.[Description]  AS [Active]
FROM AO_Suppliers s
        LEFT JOIN Lup_AO_Purchase_Price_Types t
            ON s.Lup_AO_Purchase_Price_Types_ID = t.Lup_AO_Purchase_Price_Types_ID
        LEFT JOIN AW_Formulas tf
            ON s.AW_Trade_Discount_Formula_ID = tf.AW_Formulas_ID
        LEFT JOIN AW_Formulas rf
            ON s.AW_Rebate_Discount_Formula_ID = rf.AW_Formulas_ID
        LEFT JOIN AB_Accounts od
            ON s.AB_Other_Discounts_Account_ID = od.AB_Accounts_ID
        LEFT JOIN AB_Accounts rd
            ON s.AB_Rebate_Discount_Account_ID = rd.AB_Accounts_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Account_Status st
            ON s.Sys_AC_Account_Status_ID = st.Sys_AC_Account_Status_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON s.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Slu_AW_Countries co
            ON s.Slu_AW_Countries_ID = co.Slu_AW_Countries_ID
        LEFT JOIN Slu_AW_Banks ba
            ON s.Slu_AW_Banks_ID = ba.Slu_AW_Banks_ID
        LEFT JOIN Slu_AW_Active ac
            ON s.Slu_AW_Active_ID = ac.Slu_AW_Active_ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--*** NOT USED ***
-------------------------------------------------------------------------------
--Description   :vw_RPT_AS_Sales_Analyst
--Purpose       :Sales Analyst Category sales totals extract from AS_Transactions
--Parameters    :
--Date          :2002/05/28
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE     VIEW vw_RPT_AS_Sales_Analyst

AS

    SELECT  
--        ISNULL(c.Surname, '') + isnull(', ' + c.Firstnames, '') AS Customer,
--        ISNULL(c.Credit_Limit,0) AS [Credit Limit], 
--        ISNULL(c.Account_Balance,0) AS [Account Balance], 
        ISNULL(t.Transaction_Number,'') AS [No], 
        ISNULL(t.Total_Cost,0) AS [Cost], 
        ISNULL(t.Amount,0) AS [Amount], 
        ISNULL(t.Total_Tax_Amount,0) AS [Tax], 
        ISNULL(t.Total_Discount_Amount,0) AS [Discount], 
        ISNULL(t.Total_Amount,0) AS [Total], 
        ISNULL(t.Payment_Amount,0) AS [Payment], 
        t.Transaction_Date, 
        tt.[Description] AS [TransactionType], 
--        tills.[Description] AS [Till], 
--        cashiers.[Description] AS [Cashier], 
--        reps.[Description] AS [Rep], 
--        t.Cashed_Up, 
--        t.Day_End, 
--        t.Customer_Reference, 
--        t.Expiry_Date,
--        com.Comment, 
        uc.Company_Name,
        t.AW_User_Companies_ID AS [CompanyID], 
--        t.Lup_AS_Cashiers_ID AS [CashierID], 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
--        t.Lup_AS_Tills_ID AS [TillID], 
--        t.Lup_AS_Reps_ID AS [RepID], 
--        c.AC_Customers_ID AS [CustomerID],
        t.AS_Transactions_ID AS [ID]   

	FROM         
		AS_Transactions t 
-- 			LEFT JOIN AC_Customers c
--                 ON t.AC_Customers_ID = c.AC_Customers_ID 
-- 			LEFT JOIN fn_AW_Comments(-7) com
--                 ON t.AW_Comments_ID = com.ID
			LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
-- 			LEFT JOIN Lup_AS_Tills tills
--                 ON t.Lup_AS_Tills_ID = tills.Lup_AS_Tills_ID 
-- 			LEFT JOIN Lup_AS_Cashiers cashiers
--                 ON t.Lup_AS_Cashiers_ID = cashiers.Lup_AS_Cashiers_ID 
-- 			LEFT JOIN Lup_AS_Reps reps
--                 ON t.Lup_AS_Reps_ID = reps.Lup_AS_Reps_ID
			LEFT JOIN AW_User_Companies uc
                ON t.AW_User_Companies_ID = uc.AW_User_Companies_ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :vw_RPT_AS_Transaction_Headers
--Purpose       :Day End sales totals extract from AS_Transactions
--Parameters    :
--Date          :2002/05/07
--Authors       :TB
--MODS:         :07/05/02 - Cleaned up
--              :13/07/02 - Removed superfluous columns
--2004.4.2      :24/10/08 - Removed superfluous joins
-------------------------------------------------------------------------------

CREATE          VIEW vw_RPT_AS_Transaction_Headers

AS

    SELECT  
        ISNULL(c.Surname, '') + isnull(', ' + c.Firstnames, '') AS [Customer],
        ISNULL(c.Credit_Limit,0) AS [Credit Limit], 
        ISNULL(c.Account_Balance,0) AS [Account Balance], 
        ISNULL(t.Transaction_Number,'') AS [No], 
        ISNULL(t.Total_Cost,0) AS [Cost], 
        ISNULL(t.Amount,0) AS [Amount], 
        ISNULL(t.Total_Tax_Amount,0) AS [Tax], 
        ISNULL(t.Total_Discount_Amount,0) AS [Discount], 
        ISNULL(t.Total_Amount,0) AS [Total], 
        ISNULL(t.Payment_Amount,0) AS [Payment], 
        t.Transaction_Date, 
        tt.[Description] AS [TransactionType], 
        t.Day_End, 
        uc.Company_Name,
        t.AW_User_Companies_ID AS [CompanyID], 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
        c.AC_Customers_ID AS [CustomerID],
        t.AS_Transactions_ID AS [ID]
	FROM AS_Transactions t 
		LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID 
		LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
		LEFT JOIN AW_User_Companies uc
            ON t.AW_User_Companies_ID = uc.AW_User_Companies_ID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE    VIEW dbo.vw_RPT_Customer_Statements
AS

SELECT 
    t.Date_Captured AS [TransactionDate], 
    tt.Description AS Type, 
    t.Transaction_Number AS [TransactionNo], 
    ISNULL(t.Total_Amount, 0) AS Amount, 
    ISNULL(t.Payment_Amount, 0) AS Payment, 
    ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS Balance, 
    c.AC_Customers_ID AS CustomerID, 
    c.Surname + c.Initials AS Customer, 
    c.Post_Box as CustomerPostAddress,
    c.Post_Office as CustomerPostOffice,
    c.Post_Code as CustomerPostCode,
    c.Work_Email as CustomerEmail
FROM AS_Transactions t 
    RIGHT OUTER JOIN AC_Customers c
        ON t.AC_Customers_ID = c.AC_Customers_ID 
    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
        ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :vw_AS_POS_Products    -- now REDUNDANT
--Purpose       :Extracts POS NORMAL Lookup Products 
--Date          :2002/02/16
--Functionality :Tables: AP_Products + 10 LUP Joins
--Authors       :TB
--Version       :1.0.0
--MODS          :26/07/02 - Converted [Gross Margin] from FLOAT to MONEY
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :02/06/03 - Added Average Margin field based on Average_Cost
--              :03/07/03 - Changed Discount GroupID field
--              :           from  p.Lup_AP_Product_Groups_ID as [GroupID]
--              :           to    p.Lup_AP_Discount_Groups_ID as [GroupID]
--              :20/12/03 - Added MinGPPerc field based on Min_GP_Percentage
--              :12/01/04 - Added [Edit Discount] alias to Slu_AW_YesNo_Edit_Price
--              :19/01/04 - Added ISNULL validation of NULL Product_Code
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :           Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :26/02/04 - Added [PromoPrice] from fn_AP_Get_Sales_Promotion_Price
--              :28/02/04 - Added [GrossProfit] to fix POS MARGIN sorts (+ & -)
--              :28/02/04 - Added [PromoProductID] from fn_AP_Get_Sales_Promotion_Product_ID
--2004.2.7      :12/04/06 - Removed Quote_Reserved from [Qty Reserved]
--2004.3.4      :30/12/06 - Reworked Job Card and Sales Order Reserved in realtime
--              :           using fn_AP_SUM_Product_Job_Reserved
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS
--              :           2. Moving this code to sp_AS_POS_Products_Select
--Now Retired   :           Now Retired
--              :26/07/07 - Added p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID]
--              :29/07/07 - Added p.Standard_Cost as [Std Cost]
--              :09/08/07 - Removed unused [Job_Reserved] field
--              :13/08/07 - Removed unused [OpenOrderQty] field
--              :26/08/07 - Added p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem]
--2004.3.8      :10/05/08 - Removed JOIN with Lup_AP_Product_Departments and its
--              :           Min_GP_Percentage field and renamed the alias of the
--              :           Max_Discount_Perc to [MinGPPerc] and the alias of the
--              :           Slu_AW_YesNo_Max_Discount_Perc to [UseMinGPPerc] (new Profit Protector)
--2004.3.9      :05/06/08 - Converted [Qty on Hand] to decimal(9, 3) (Sales Order formatting)
--              :05/06/08 - Added p.Pack_Mass AS [Pack Mass] (Sales Orders)
--              :16/06/08 - Removed unused [Price], [Date], [UserID], [Tax Code]
--              :16/06/08 - Rename [OpenOrderQty] to [On Order]
--2004.4.2      :24/10/08 - Added new field [Standard Margin]
--2004.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE VIEW [vw_AS_POS_Products]
AS

	SELECT 
		p.Description, 
		ISNULL(p.Product_Code, '') as [Code], 
		p.Last_Cost AS [Last Cost], 
		0 as [Standard Discount],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) as [Price 1],
		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
		p.Average_Cost AS [Avg Cost], 
		CONVERT(money, dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2, Price2_Effective_Date, Price2_Price2, getdate()) as [Price 2],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) as [Unit Price],
		p.Pack_Size AS [Qty],
		0 as [Discount %],
		0 as [Discount],
--		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) as Price,
		p.AP_Products_ID as [ID],
		p.Lup_AP_Product_Types_ID as [TypeID],
--		tc.Description AS [Tax Code], 
		tc.Tax_Rate as [Tax Rate], 
        p.Pack_Mass AS [Pack Mass], 
		p.Pack_Volume AS [Pack Volume], 
		p.On_Hand AS [On Hand], 
		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
		p.Keywords, 
        p.Lup_AP_Discount_Groups_ID as [GroupID],
        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
--		p.Date_Captured AS [Date], 
--		p.User_ID AS [UserID], 
        p.AW_User_Companies_ID AS [CompanyID],
        p.Slu_AW_Active_ID AS [Active],
        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
        CONVERT(money, dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
        CONVERT(money, dbo.GetGrossContribution(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
        p.Standard_Cost AS [Std Cost],
        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
        p.SKU_Code AS [SKU_Code],
        p.Supercession AS [Supercession],
        p.Alternate_Code1 AS [Alternate_Code1],
        p.Alternate_Code2 AS [Alternate_Code2],
        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :vw_AS_POS_Products_Gross_Contribution
--Purpose       :Extracts POS NORMAL Lookup Products 
--Date          :2002/02/16
--Functionality :Tables: AP_Products + 10 LUP Joins
--Authors       :TB
--MODS          :26/07/02 - Converted [Gross Margin] from FLOAT to MONEY
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :02/06/03 - Added Average Margin field based on Average_Cost
--              :03/07/03 - Changed Discount GroupID field
--              :           from  p.Lup_AP_Product_Groups_ID as [GroupID]
--              :           to    p.Lup_AP_Discount_Groups_ID as [GroupID]
--              :20/12/03 - Added MinGPPerc field based on Min_GP_Percentage
--              :12/01/04 - Added [Edit Discount] alias to Slu_AW_YesNo_Edit_Price
--              :19/01/04 - Added ISNULL validation of NULL Product_Code
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :           Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :26/02/04 - Added [Promotion] from fn_AP_Get_Sales_Promotion_Price
--              :28/02/04 - Added [GrossProfit] to fix POS MARGIN sorts (+ & -)
--              :28/02/04 - Added [PromoProductID] from fn_AP_Get_Sales_Promotion_Product_ID
--2004.2.7      :12/04/06 - Removed Quote_Reserved from [Qty Reserved]
--2004.3.4      :30/12/06 - Reworked Job Card and Sales Order Reserved in realtime
--              :           using fn_AP_SUM_Product_Job_Reserved
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS
--              :26/07/07 - Added p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID]
--              :29/07/07 - Added p.Standard_Cost as [Std Cost]
--              :09/08/07 - Removed unused [Job_Reserved] field
--              :13/08/07 - Removed unused [OpenOrderQty] field
--              :26/08/07 - Added p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem]
--2004.3.8      :10/05/08 - Removed JOIN with Lup_AP_Product_Departments and its
--              :           Min_GP_Percentage field and renamed the alias of the
--              :           Max_Discount_Perc to [MinGPPerc] and the alias of the
--              :           Slu_AW_YesNo_Max_Discount_Perc to [UseMinGPPerc] (new Profit Protector)
--2004.3.9      :05/06/08 - Converted [Qty on Hand] to decimal(9, 3) (Sales Order formatting)
--              :05/06/08 - Added p.Pack_Mass AS [Pack Mass] (Sales Orders)
--              :16/06/08 - Removed unused [Price], [Date], [UserID], [Tax Code]
--              :16/06/08 - Rename [OpenOrderQty] to [On Order]
--2004.4.2      :24/10/08 - Added new field [Standard Margin]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE VIEW [vw_AS_POS_Products_Gross_Contribution]
AS

	SELECT 
		p.Description, 
		ISNULL(p.Product_Code, '') as [Code],
		p.Last_Cost AS [Last Cost], 
		0 as [Standard Discount],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) as [Price 1],
		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
		p.Average_Cost AS [Avg Cost], 
		CONVERT(money, dbo.GetGrossContribution(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()) as [Price 2],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) as [Unit Price],
		p.Pack_Size AS [Qty],
		0 as [Discount %],
		0 as [Discount],
		p.AP_Products_ID as [ID],
		p.Lup_AP_Product_Types_ID as [TypeID],
		tc.Tax_Rate as [Tax Rate],
        p.Pack_Mass AS [Pack Mass], 
		p.Pack_Volume AS [Pack Volume],
		p.On_Hand AS [On Hand],
		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
		p.Keywords, 
        p.Lup_AP_Discount_Groups_ID as [GroupID],
        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
        p.AW_User_Companies_ID AS [CompanyID],
        p.Slu_AW_Active_ID AS [Active],
        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
        CONVERT(money, dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
        CONVERT(money, dbo.GetGrossContribution(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
        p.Standard_Cost AS [Std Cost],
        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
        p.SKU_Code AS [SKU_Code],
        p.Supercession AS [Supercession],
        p.Alternate_Code1 AS [Alternate_Code1],
        p.Alternate_Code2 AS [Alternate_Code2],
        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



























-------------------------------------------------------------------------------
--Description   :vw_AS_POS_Products_Top_20_Perc
--Purpose       :Extracts Top 20% by GP ORDER BY GP% DESC
--Date          :2002/07/26
--Functionality :Tables: AP_Products + 12 LUP Joins
--Authors       :TB
--MODS          :26/07/02 - Converted [Gross Margin] from FLOAT to MONEY
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :02/06/03 - Added Average Margin field based on Average_Cost
--              :03/07/03 - Changed Discount GroupID field
--              :           from  p.Lup_AP_Product_Groups_ID as [GroupID]
--              :           to    p.Lup_AP_Discount_Groups_ID as [GroupID]
--              :20/12/03 - Added MinGPPerc field based on Min_GP_Percentage
--              :12/01/04 - Added [Edit Discount] alias to Slu_AW_YesNo_Edit_Price
--              :19/01/04 - Added ISNULL validation of NULL Product_Code
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :           Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :26/02/04 - Added [Promotion] from fn_AP_Get_Sales_Promotion_Price
--              :28/02/04 - Added [GrossProfit] to fix POS MARGIN sorts (+ & -)
--              :28/02/04 - Added [PromoProductID] from fn_AP_Get_Sales_Promotion_Product_ID
--2004.2.7      :12/04/06 - Removed Quote_Reserved from [Qty Reserved]
--2004.3.4      :30/12/06 - Reworked Job Card and Sales Order Reserved in realtime
--              :           using fn_AP_SUM_Product_Job_Reserved
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS
--              :26/07/07 - Added p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID]
--              :29/07/07 - Added p.Standard_Cost as [Std Cost]
--              :09/08/07 - Removed unused [Job_Reserved] field
--              :13/08/07 - Removed unused [OpenOrderQty] field
--              :26/08/07 - Added p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem]
--2004.3.8      :10/05/08 - Removed JOIN with Lup_AP_Product_Departments and its
--              :           Min_GP_Percentage field and renamed the alias of the
--              :           Max_Discount_Perc to [MinGPPerc] and the alias of the
--              :           Slu_AW_YesNo_Max_Discount_Perc to [UseMinGPPerc] (new Profit Protector)
--2004.3.9      :05/06/08 - Converted [Qty on Hand] to decimal(9, 3) (Sales Order formatting)
--              :05/06/08 - Added p.Pack_Mass AS [Pack Mass] (Sales Orders)
--              :16/06/08 - Removed unused [Price], [Date], [UserID], [Tax Code]
--              :16/06/08 - Rename [OpenOrderQty] to [On Order]
--2004.4.2      :24/10/08 - Added new field [Standard Margin]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE                                  VIEW vw_AS_POS_Products_Top_20_Perc

AS

    SELECT TOP 20 PERCENT WITH TIES
		MAX(p.Description) AS [Description], 
		MAX(ISNULL(p.Product_Code, '')) as [Code],
		MAX(p.Last_Cost) AS [Last Cost], 
		MAX(0) as [Standard Discount],
		MAX(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())) as [Price 1],
		MAX(dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate())) as [Promotion],
        MAX(CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)))) as [Qty on Hand],
		MAX(dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate())) as [PromoProductID],
		MAX(p.Average_Cost) AS [Avg Cost], 
		MAX(CONVERT(money, dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost))) as [Gross Margin],
		MAX(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2, getdate())) as [Price 2],
		MAX(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate())) as [Unit price],
		MAX(p.Pack_Size) AS [Qty],
		MAX(0) as [Discount %],
		MAX(0) as [Discount],
		p.AP_Products_ID as [ID],
		MAX(p.Lup_AP_Product_Types_ID) as [TypeID],
		MAX(tc.Tax_Rate) as [Tax Rate],
        MAX(p.Pack_Mass) AS [Pack Mass], 
		MAX(p.Pack_Volume) AS [Pack Volume], 
		MAX(p.On_Hand) AS [On Hand], 
		MAX(p.Slu_AW_YesNo_Edit_Price) AS [Edit Price], 
		MAX(p.Slu_AW_YesNo_Edit_Discount) AS [Edit Discount], 
		MAX(p.Keywords) AS [Keywords], 
        MAX(p.Lup_AP_Discount_Groups_ID) as [GroupID],
        MAX(CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Reserved],
        MAX(CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID))) as [On Order],
        MAX(p.AW_User_Companies_ID) AS [CompanyID],
        MAX(p.Slu_AW_Active_ID) AS [Active],
        MAX(p.Slu_AW_YesNo_Non_Stock_Item) AS [NonStockItem],
--        MAX(p.Slu_AW_YesNo_Hide_Remote) AS [HideRemote],
        MAX(CONVERT(money, dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate(), Average_Cost))) as [Average Margin],
        MAX(ISNULL(p.Max_Discount_Perc, 0)) AS [MinGPPerc],
        MAX(p.Slu_AW_YesNo_Max_Discount_Perc) AS [UseMinGPPerc],
        MAX(CONVERT(money, dbo.GetGrossContribution(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost))) as [GrossProfit],
        MAX(p.Lup_AP_Markup_Groups_ID) AS [CostPlusGroupID],
        MAX(p.Slu_AW_YesNo_Cost_Plus_Item) AS [IsCostPlusItem],
        MAX(p.Standard_Cost) AS [Std Cost],
        MAX(CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost))) as [Standard Margin],
        MAX(p.SKU_Code) AS [SKU_Code],
        MAX(p.Supercession) AS [Supercession],
        MAX(p.Alternate_Code1) AS [Alternate_Code1],
        MAX(p.Alternate_Code2) AS [Alternate_Code2]
	FROM AP_Products p  
        INNER JOIN AS_Transaction_Details d
            ON d.AP_Products_ID = p.AP_Products_ID
        INNER JOIN AS_Transactions h
            ON d.AS_Transactions_ID = h.AS_Transactions_ID
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
    WHERE (h.Transaction_Date > DATEADD(m, -3, getdate()) AND
           h.Transaction_Date <= getdate()) AND
          (h.Sys_AW_Transaction_Types_ID = 3 OR
           h.Sys_AW_Transaction_Types_ID = 4)
    GROUP BY p.AP_Products_ID
    ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC 























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------------------------------
--Description   :vw_RPT_AB_Cash_Book_Transactions
--Purpose       :Returns Cash Book Transactions
--Date          :2002/03/08
--Authors       :TB
--MODS          :
--2004.3.8      :31/03/08 - Replaced int(Transaction_Date) conversion with
--              :           CHAR(10)(Transaction_Date) to prevent ROUNDING UP
--              :           dats after 12:00PM to the next day !!
--2004.3.9      :28/06/08 - Added new t.AW_Company_Banks_ID AS [BankID] to fix
--              :           obscure disassembly of Bank Account Description in
--              :           Cash Book Listing report - done while in AUS
--2004.4.0      :29/07/08 - Added tt.Transaction_Code AS [TypeCode] for report 2
-------------------------------------------------------------------------------

CREATE               VIEW vw_RPT_AB_Cash_Book_Transactions

AS

    SELECT
    	t.AB_Cash_Book_Transactions_ID AS [ID],
        t.AW_Company_Banks_ID AS [BankID],
        b.[Description] AS [Bank],
    	tt.[Description] AS [Type],
    	tt.Transaction_Code AS [TypeCode],
        CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [Date],
    	m.[Description] AS [Month],
    	y.[Description] AS [Year],
    	t.Reference_No AS [Ref No],
    	t.Transaction_Description AS [Description],
    	t.Amount AS [Total],
    	t.Date_Captured AS [Captured],
    	u.UserName AS [User],
    	a.[Description] AS [GL Account],
    	a.Account_Number AS [GL Acc No],
    	td.Tax_Amount AS [Tax],
    	td.Amount AS [Amount],
        td.Net_Amount AS [Net],
    	td.Comments,
    	cb.Account_Name AS [Bank Acc Name],
    	cb.Account_Number AS [Bank Acc No],
        t.AW_User_Companies_ID
    FROM AB_Cash_Book_Transactions t 
        INNER JOIN  Slu_AW_Months m
            ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID 
        LEFT OUTER JOIN AB_Accounts a 
        RIGHT OUTER JOIN  AB_Cash_Book_Transaction_Details td
            ON a.AB_Accounts_ID = td.AB_Accounts_ID
            ON  t.AB_Cash_Book_Transactions_ID = td.AB_Cash_Book_Transactions_ID 
        LEFT OUTER JOIN Slu_AW_Years y
            ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID 
        LEFT OUTER JOIN AW_Users u
            ON t.User_ID = u.AW_Users_ID 
        LEFT OUTER JOIN Sys_AB_Transaction_Types tt
            ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID 
        LEFT OUTER JOIN Slu_AW_Banks b
        INNER JOIN AW_Company_Banks cb
            ON b.Slu_AW_Banks_ID = cb.Slu_AW_Banks_ID
            ON t.AW_Company_Banks_ID = cb.AW_Company_Banks_ID













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE  VIEW dbo.vw_RPT_AS_Transactions_Transaction_Details

AS

SELECT
    ISNULL(t.AS_Transactions_ID, 0) AS tID, ISNULL(t.Transaction_Number, '') AS tTransactionNumber, ISNULL(t.Amount, 0) AS tAmount, 
    ISNULL(t.Total_Tax_Amount, 0) AS tTotalTaxAmount, ISNULL(t.Total_Discount_Amount, 0) AS tTotalDiscountAmount, ISNULL(t.Total_Amount, 0) 
    AS tTotalAmount, ISNULL(t.Payment_Amount, 0) AS tPaymentAmount, ISNULL(t.Transaction_Date, 0) AS tStartDate, ISNULL(t.Transaction_Date, 0) 
    AS tEndDate, ISNULL(t.Expiry_Date, 0) AS tExpiryDate, ISNULL(t.Version_Number, 0) AS tVersion, ISNULL(t.Customer_Reference, '') 
    AS tCustomerReference, ISNULL(t.Sys_AW_Transaction_Types_ID, 0) AS tTransactionTypeID, ISNULL(tt.Description, '') AS tTransactionType, 
    ISNULL(t.Lup_AW_Stores_ID, 0) AS tStoreID, ISNULL(s.Description, '') AS tStore, ISNULL(t.Lup_AS_Reps_ID, 0) AS tRepID, ISNULL(r.Description, '') 
    AS tRep, ISNULL(td.Quantity, 0) AS tdQty, ISNULL(td.Unit_Cost, 0) AS tdUnitCost, ISNULL(td.Unit_Price, 0) AS tdUnitPrice, ISNULL(td.Original_Price, 0) 
    AS tdOriginalPrice, ISNULL(td.Discount_Amount, 0) AS tdDiscountAmount, ISNULL(td.Tax_Amount, 0) AS tdTaxAmount, ISNULL(td.Extended_Amount, 0) 
    AS tdExtendedAmount, ISNULL(td.Commission_Amount, 0) AS tdCommissionAmount, ISNULL(cust.AC_Customers_ID, 0) AS tCustomerID, 
    ISNULL(cust.Surname, '') + ISNULL(', ' + cust.Initials, '') AS tCustomer, ISNULL(cust.Surname, '') AS tCustomerSurname, ISNULL(cust.Initials, '') 
    AS tCustomerInitials, ISNULL(cust.Customer_Number, '') AS tCustomerNo, ISNULL(cust.Credit_Limit, 0) AS cCustomerCreditLimit, 
    ISNULL(td.AS_Transaction_Details_ID, 0) AS TransactionDetailsID, ISNULL(prod.Description, '') AS pProduct, ISNULL(prod.AP_Products_ID, 0) 
    AS pProductID, ISNULL(pm.Lup_AP_Product_Manufacturers_ID, 0) AS pManufacturerID, ISNULL(pm.Description, '') AS pManufacturer, 
    ISNULL(pt.Lup_AP_Product_Types_ID, 0) AS pProductTypeID, ISNULL(pt.Description, '') AS pProductType, ISNULL(pg.Lup_AP_Product_Groups_ID, 0) 
    AS pProductGroupID, ISNULL(pg.Description, '') AS pProductGroup, ISNULL(pd.Lup_AP_Product_Departments_ID, 0) AS pProductDepartmentID, 
    ISNULL(pd.Description, '') AS pProductDepartment, ISNULL(pl.Lup_AP_Product_Locations_ID, 0) AS pProductLocationID, ISNULL(pl.Description, '') 
    AS pProductLocation, ISNULL(t.Date_Captured, 0) AS tDate, ISNULL(sat.Description, '') AS cAccountType, ISNULL(t.Cashed_Up, 0) AS tCashedUpDate, 
    ISNULL(till.Lup_AS_Tills_ID, 0) AS tTillID, ISNULL(till.Description, '') AS tTill, ISNULL(t.Lup_AS_Cashiers_ID, '0') AS tCashierID, ISNULL(u.Surname, '') 
    + ISNULL(', ' + u.FirstName, '') AS tCashier, ISNULL(t.Day_End, 0) AS tDayEnd, ISNULL(t.AW_User_Companies_ID, 0) AS tCompanyID
FROM dbo.Sys_AW_Transaction_Types tt
    RIGHT OUTER JOIN dbo.vw_AS_Transactions t
    INNER JOIN dbo.Lup_AS_Tills till
        ON t.Lup_AS_Tills_ID = till.Lup_AS_Tills_ID
    INNER JOIN dbo.AW_Users u
        ON t.Lup_AS_Cashiers_ID = u.AW_Users_ID
        ON tt.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
    LEFT OUTER JOIN dbo.Lup_AW_Stores s
        ON t.Lup_AW_Stores_ID = s.Lup_AW_Stores_ID
    LEFT OUTER JOIN dbo.Sys_AC_Account_Types sat
    RIGHT OUTER JOIN dbo.AC_Customers cust
        ON sat.Sys_AC_Account_Types_ID = cust.Sys_AC_Account_Types_ID
        ON t.AC_Customers_ID = cust.AC_Customers_ID
    LEFT OUTER JOIN dbo.Lup_AS_Reps r
        ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
    LEFT OUTER JOIN dbo.AS_Transaction_Details td
        ON t.AS_Transactions_ID = td.AS_Transactions_ID
    LEFT OUTER JOIN dbo.AP_Products prod
        ON td.AP_Products_ID = prod.AP_Products_ID
    LEFT OUTER JOIN dbo.Lup_AP_Product_Locations pl
        ON prod.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID
    LEFT OUTER JOIN dbo.Lup_AP_Product_Groups pg
        ON prod.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID
    LEFT OUTER JOIN dbo.Lup_AP_Product_Departments pd
        ON prod.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID
    LEFT OUTER JOIN dbo.Lup_AP_Product_Types pt
        ON prod.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
    LEFT OUTER JOIN dbo.Lup_AP_Product_Manufacturers pm
        ON prod.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE VIEW dbo.vw_RPT_GL_Accounts
AS
SELECT     j.AB_Journals_ID AS ID, j.Journal_Date AS Date, j.Journal_Reference AS Reference, j.Journal_Narration AS Narration, a.Description AS Account, 
                      jd.Amount, jd.Notes, m.Description AS Month, y.Description AS Year
FROM         dbo.AB_Accounts a RIGHT OUTER JOIN
                      dbo.AB_Journal_Details jd ON a.AB_Accounts_ID = jd.AB_Accounts_ID RIGHT OUTER JOIN
                      dbo.AB_Journals j ON jd.AB_Journals_ID = j.AB_Journals_ID LEFT OUTER JOIN
                      dbo.Slu_AW_Years y ON j.Slu_AW_Years_ID = y.Slu_AW_Years_ID LEFT OUTER JOIN
                      dbo.Slu_AW_Months m ON j.Slu_AW_Months_ID = m.Slu_AW_Months_ID





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE VIEW dbo.vw_AP_Product_Links
AS
SELECT     s1.Description AS Make, s2.Description AS Model, s3.Description AS [Year], s1.AP_Switch1_ID AS S1_ID, s2.AP_Switch2_ID AS S2_ID, 
                      s3.AP_Switch3_ID AS S3_ID, ps3.AP_Products_Switch3_ID AS ID, ps3.AP_Products_ID AS ProductID
FROM         dbo.AP_Switch1 s1 INNER JOIN
                      dbo.AP_Switch2 s2 ON s1.AP_Switch1_ID = s2.AP_Switch1_ID INNER JOIN
                      dbo.AP_Switch3 s3 ON s2.AP_Switch2_ID = s3.AP_Switch2_ID INNER JOIN
                      dbo.AP_Products_Switch3 ps3 ON s3.AP_Switch3_ID = ps3.AP_Switch3_ID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_DB_Transfer_Customer_Ageing
--Purpose       :Inserts ONE Customer Journal into ADV2004..AS_Transactions
--Functionality :Called from sp_AA_ADV2004_Step3_DB_Transfer_Customer_Catalog
--Parameters    :
--Date          :2004/08/25
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AA_ADV2004_DB_Transfer_Customer_Ageing
	(
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
		@GLAccountID int,
		@Month int, 
		@Year int,
		@TransactionType int,
		@CustomerID int,
		@CompanyID int,
		@UserID int
	)
AS     

SET NOCOUNT ON

	INSERT ADV2004..AS_Transactions 
		(
            AC_Customers_ID,
            Transaction_Number,
            Transaction_Date,
            [Amount],
            Total_Tax_Amount,
            Total_Amount,
            AB_Accounts_ID,
            Comment,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            AW_User_Companies_ID,
            [User_ID]
		)
	VALUES
		(
            @CustomerID,
            LEFT(LTRIM(RTRIM(@RefNo)),19),
            @Date,
            @Amount,
            @Tax,
            @Total,
            @GLAccountID,
            LEFT(LTRIM(RTRIM(@Comment)),20),
            @TransactionType,
            @Date,
            @CompanyID,
            @UserID
		)


SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step0_DB_Transfer
--Run From      :NB NB NB Highlight each SP and run in SEQUENCE in SQL Query Analyzer
--Purpose       :Transfers accounting data to NEW ADV2004 DB
--Date          :2004/08/29
--Authors       :TB
-------------------------------------------------------------------------------
--              :NB. NB. Run AFTER Period Procedure for current month is COMPLETED
--              :
--Instructions  :    1.    UPGRADE existing ADV2004 DB to release 2004.1.0
--              :    2.    PRINT (at least) the following reports in existing ADV2004:
--              :              Customer Age Analysis
--              :              Stock Valuation
--              :              Supplier Age Analysis
--              :              Trial Balance
--              :    3.    DETACH ADV2004 database
--              :    4.    RENAME ADV2004 database to ADV2004OLD
--              :    5.    COPY the NEW release 2004.1.0 DB into SQL Server\MSSQL\Data
--              :    6.    ATTACH BOTH databases
--              :    7.    FIRST: Run sp_AA_ADV2004_Wipe_Customer_Table FROM ADV2004
--              :              with an input parameter of 1 e.g.
--              :    8.    SECOND: Run this SP in SQL Query Analyzer FROM ADV2004OLD
--              :              with an input parameter of 1 e.g.
--              :              EXEC sp_AA_ADV2004_DB_Transfer_Customer_Catalog 1
--              :    9.    DETACH ADV2004OLD database
--              :   10.    CHANGE ADV2004OLD.* file attributes to Read-only
--              :   11.    ATTACH ADV2004OLD database (as Read-only)
--              :
--Functionality :    1.    Transfers Inventory, Costs, MSL etc. to NEW ADV2004
--              :    2.    Transfers LAST 7 Period Procedures to NEW ADV2004
--              :    3.    Transfers ALL Customers and Ageing to NEW ADV2004
--              :    4.    
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AA_ADV2004_Step0_DB_Transfer

AS  

-------------------------------
-- NB NB : Run from  ADV2004
-------------------------------
EXEC sp_AA_ADV2004_Step1_DB_Transfer_Inventory 1

EXEC sp_AA_ADV2004_Step2_Wipe_Customer_Table

EXEC sp_AA_ADV2004_Step4_Wipe_GL_Tables

EXEC sp_AA_ADV2004_Step5_DB_Transfer_GL


-------------------------------
-- NB NB : Run from  ADV2004OLD
-------------------------------
EXEC sp_AA_ADV2004_Step3_DB_Transfer_Customer_Catalog 1










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-- **********************************************************************
--
-- Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004
--
-- **********************************************************************





-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step1_DB_Transfer_Inventory
--Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004
--Purpose       :Creates a BLANK AP_Inventory_Adjustments table and
--              :    Transfers Stock On Hand and Cost Prices into AP_Products
--Parameters    :@CompanyID
--Date          :2004/08/29
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AA_ADV2004_Step1_DB_Transfer_Inventory
	(
        @CompanyID int
	)

AS   

SET NOCOUNT ON

    DECLARE @ProductID int,
            @TargetProductID int,
            @ProductCode varchar(20),
            @LastCost money,
            @AverageCost money,
            @OnHand decimal(9,3),
            @MinStockLevel decimal(9,3),
            @MinOrderQty decimal(9,3),
            @MaxOrderQty decimal(9,3),
            @AdjustmentType tinyint,
            @Note varchar(70),
            @UserID int


    SET @AdjustmentType = 1    --Intialize as 'Adjustment' type
    SET @Note = 'Opening Stock Transfer by System'
    SET @UserID = 1


    ------------------------------------------------------------------------------
    --> WIPE the Inventory Adjustments table
    ------------------------------------------------------------------------------
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Adjustments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Adjustments]

    
    CREATE TABLE [dbo].[AP_Inventory_Adjustments] (
    	[AP_Inventory_Adjustments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Sys_AP_Adjustment_Types_ID] [tinyint] NULL ,
    	[Previous_Last_Cost] [money] NOT NULL ,
    	[Previous_Average_Cost] [money] NULL ,
    	[Previous_On_Hand] [decimal](9, 3) NULL ,
    	[Previous_Job_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Quote_Reserved] [decimal](9, 3) NULL ,
    	[New_Last_Cost] [money] NULL ,
    	[New_Average_Cost] [money] NULL ,
    	[New_On_Hand] [decimal](9, 3) NULL ,
    	[New_Job_Reserved] [decimal](9, 3) NULL ,
    	[New_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[New_Quote_Reserved] [decimal](9, 3) NULL ,
    	[Note] [varchar] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Inventory_Adjustments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Adjustments] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Adjustments_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Adjustments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Adjustments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Adjustments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Sys_AP_Adjustment_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Adjustments].[User_ID]'

    
    setuser




    ------------------------------------------------------------------------------
    --> Transfer the Stock On Hand
    ------------------------------------------------------------------------------
    	DECLARE Product_Cursor CURSOR FOR
            (
                SELECT AP_Products_ID,
                       Product_Code,
                       Last_Cost,
                       Average_Cost,
                       On_Hand,
                       Min_Stock_Level,
                       Min_Order_Qty,
                       Max_Order_Qty
                FROM ADV2004OLD..AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            )
    
    	OPEN Product_Cursor
    
        	FETCH NEXT FROM Product_Cursor 
        	INTO
                @ProductID,
                @ProductCode,
                @LastCost,
                @AverageCost,
            	@OnHand,
                @MinStockLevel,
                @MinOrderQty,
                @MaxOrderQty


        	WHILE @@FETCH_STATUS = 0
        	BEGIN


                IF EXISTS 
                    (
                        SELECT AP_Products_ID
                        FROM AP_Products
                        WHERE Product_Code = @ProductCode
                    )
                    BEGIN

                        SELECT @TargetProductID = AP_Products_ID
                        FROM AP_Products
                        WHERE Product_Code = @ProductCode

                    	UPDATE AP_Products
                        SET Last_Cost = @LastCost,
                            Average_Cost = @AverageCost,
                            On_Hand = @OnHand,
                            Min_Stock_Level = @MinStockLevel,
                            Min_Order_Qty = @MinOrderQty,
                            Max_Order_Qty = @MaxOrderQty
                    	WHERE AP_Products_ID = @TargetProductID

                    	INSERT AP_Inventory_Adjustments
                            (
                    			AP_Products_ID,
                                Sys_AP_Adjustment_Types_ID,
                    			Previous_Last_Cost,
                                Previous_Average_Cost,
                    			Previous_On_Hand,
                    			Previous_Job_Reserved,
                    			Previous_Sales_Order_Reserved,
                    			Previous_Quote_Reserved,
                    			New_Last_Cost,
                                New_Average_Cost,
                    			New_On_Hand,                    			New_Job_Reserved,
                    			New_Sales_Order_Reserved,
                    			New_Quote_Reserved,
                    			Note,
                    			Date_Captured,
                    			[User_ID],
                    			AW_User_Companies_ID
                            )
                    	VALUES
                            (
                                @TargetProductID,
                                @AdjustmentType,
                    			@LastCost,
                                @AverageCost,
                    			@OnHand ,
                    		    0,
                    			0,
                    		    0,
                    			@LastCost,
                                @AverageCost,
                    			@OnHand,
                    			0 ,
                    			0,
                    			0,
                    			@Note,
                    			getdate(),
                    			@UserID,
                    			@CompanyID
                            )
                    END
        
        
        
            	FETCH NEXT FROM Product_Cursor 
            	INTO
                    @ProductID,
                    @ProductCode,
                    @LastCost,
                    @AverageCost,
                	@OnHand,
                    @MinStockLevel,
                    @MinOrderQty,
                    @MaxOrderQty

            END
        	
    	CLOSE Product_Cursor

    	DEALLOCATE Product_Cursor




SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-- **********************************************************************
--
-- Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004
--
-- **********************************************************************





-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step2_Wipe_Customer_Table
--Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004
--Purpose       :Creates a BLANK AC_Customers table 
--Parameters    :
--Date          :2004/08/31
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AA_ADV2004_Step2_Wipe_Customer_Table

AS


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Customers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Customers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures]

    
    CREATE TABLE [dbo].[AC_Customers] (
    	[AC_Customers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Surname] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Firstnames] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Initials] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Titles_ID] [tinyint] NULL ,
    	[Contact_Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Languages_ID] [smallint] NULL ,
    	[IDReg_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Street_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Street_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Suburb] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Head_Office] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AC_Customer_Types_ID] [smallint] NULL ,
    	[Lup_AC_Customer_Groups_ID] [smallint] NULL ,
    	[Sys_AC_Account_Status_ID] [tinyint] NULL ,
    	[AW_YesNo_Pre_Notify_ID] [tinyint] NULL ,
    	[AW_YesNo_Post_Notify_ID] [tinyint] NULL ,
    	[Lup_AC_Discount_Categories_ID] [smallint] NULL ,
    	[Credit_Limit] [money] NOT NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Sys_AC_Credit_Term_Types_ID] [int] NULL ,
    	[Sys_AC_Account_Types_ID] [tinyint] NULL ,
    	[Credit_Insurers_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Credit_Insurers_Limit] [money] NULL ,
    	[AW_YesNo_Charge_Interest_ID] [tinyint] NULL ,
    	[Slu_AW_Controllers_ID] [int] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Lup_AC_Sales_Areas_ID] [smallint] NULL ,
    	[Slu_AW_Countries_ID] [smallint] NULL ,
    	[Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Fax_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Web_Site_URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Firstname] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Birthday] [smalldatetime] NULL ,
    	[Principal_Contact_Method_ID] [tinyint] NULL ,
    	[Principal_Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Orders_URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Notes] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Balance] [money] NOT NULL ,
    	[Current_Balance] [money] NULL ,
    	[Days_30] [money] NULL ,
    	[Days_60] [money] NULL ,
    	[Days_90] [money] NULL ,
    	[Days_120] [money] NULL ,
    	[Days_150] [money] NULL ,
    	[Days_180] [money] NULL ,
    	[Sys_AW_Delivery_Methods_ID] [tinyint] NULL ,
    	[Sys_AC_Use_Assets_ID] [tinyint] NULL ,
    	[AW_YesNo_Send_Email_ID] [tinyint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions] (
    	[AS_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total_Cost] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Discount_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Expiry_Date] [smalldatetime] NULL ,
    	[Version_Number] [smallint] NULL ,
    	[Customer_Reference] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Lup_AS_Marketing_Indicators_ID] [int] NULL ,
    	[Lup_AW_Stores_ID] [smallint] NULL ,
    	[Lup_AW_Workstations_ID] [smallint] NULL ,
    	[Lup_AS_Tills_ID] [smallint] NULL ,
    	[Lup_AS_Cashiers_ID] [smallint] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Slu_AW_Currencies_ID] [smallint] NULL ,
    	[Old_Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Cancelled_User_ID] [int] NULL ,
    	[Cancelled_DateTime] [datetime] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Transmitted] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AW_Period_Procedures] (
    	[AW_Period_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AW_Period_Procedure_Types_ID] [int] NULL ,
    	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Month] [tinyint] NULL ,
    	[Year] [smallint] NULL ,
    	[Month_End_Date] [datetime] NULL ,
    	[Year_End_Date] [datetime] NULL ,
    	[Stock_Valuation] [money] NULL ,
    	[Date_Captured] [smalldatetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Customers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Customers] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Customers_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AW_Period_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_ID]
    	)  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transactions] ON [dbo].[AS_Transactions]([AC_Customers_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [PK_AS_Transactions] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transactions_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Transactions_Date_Captured] ON [dbo].[AS_Transactions]([Date_Captured]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Transactions_Transaction_Type] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID]) ON [PRIMARY]

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Account_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Customers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Charge_Interest_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Post_Notify_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Pre_Notify_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Send_Email_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Credit_Insurers_Limit]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Credit_Limit]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Current_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Customers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_120]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_150]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_180]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_30]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_60]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_90]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Customer_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Customer_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Discount_Categories_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Sales_Areas_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AS_Reps_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Two]', N'[AC_Customers].[Principal_Contact_Method_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Customers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Controllers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Country]', N'[AC_Customers].[Slu_AW_Countries_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Credit_Terms_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Customers].[Slu_AW_Languages_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Titles_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Customers].[Start_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Account_Status_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Account_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Credit_Term_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Customers].[Sys_AC_Use_Assets_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Two]', N'[AC_Customers].[Sys_AW_Delivery_Methods_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Customers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Cashiers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Reps_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Tills_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Stores_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Workstations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Payment_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Transaction_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions].[User_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Version_Number]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Period_Procedures].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Period_Procedures].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Period_Procedures].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Period_Procedures].[Stock_Valuation]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Period_Procedures].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [FK_AS_Transactions_AW_Comments] FOREIGN KEY 
    	(
    		[AW_Comments_ID]
    	) REFERENCES [dbo].[AW_Comments] (
    		[AW_Comments_ID]
    	) NOT FOR REPLICATION ,
    	CONSTRAINT [FK_AS_Transactions_Lup_AS_Tills] FOREIGN KEY 
    	(
    		[Lup_AS_Tills_ID]
    	) REFERENCES [dbo].[Lup_AS_Tills] (
    		[Lup_AS_Tills_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Stores] FOREIGN KEY 
    	(
    		[Lup_AW_Stores_ID]
    	) REFERENCES [dbo].[Lup_AW_Stores] (
    		[Lup_AW_Stores_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Workstations] FOREIGN KEY 
    	(
    		[Lup_AW_Workstations_ID]
    	) REFERENCES [dbo].[Lup_AW_Workstations] (
    		[Lup_AW_Workstations_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Sys_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    
    alter table [dbo].[AS_Transactions] nocheck constraint [FK_AS_Transactions_AW_Comments]



    
        














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-- *************************************************************************
--
-- Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004OLD
--
-- *************************************************************************




------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step3_DB_Transfer_Customer_Catalog
--Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004OLD
--Purpose       :Copies Customer Account Balances to a NEW ADV2004 database
--              :from an EXISTING ADV2004 database
--Parameters    :@CompanyID
--Date          :2004/08/25
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AA_ADV2004_Step3_DB_Transfer_Customer_Catalog
	(
        @CompanyID int
	)

AS

SET NOCOUNT ON

	DECLARE @LastPeriodProcedureDate DateTime,
            @CustomerID int,
            @AccountBalance money,
            @Now datetime,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime,
            @AgePayment money,
            @AgeAmount money,
            @AgeCurrent money,
            @Age30Days money,
            @Age60Days money,
            @Age90Days money,
            @Age120Days money,
            @Age150Days money,
            @Age180Days money,

            @TransactionType int, 
            @TransactionNo int, 
            @TransactionNumber varchar(15),
    		@RefNo varchar(20),
    		@Date DateTime,
    		@Comment varchar(50),
    		@Amount money,
    		@Tax money,
    		@Total money,
            @Tax_Rate Decimal(5,2),
    		@ABAccountID int,    --AB_Accounts_ID
    		@Month int, 
    		@Year int,
    		@UserID int,
    		@TransactionDate DateTime,
            @ReturnCode int

	SET @Now = getdate()
    SET @TransactionType = 5
    SET @TransactionNo = 0
    SET @UserID = 1

    SET @ReturnCode = 0            --0 = Unsuccessful


------------------------------------------------------------------------------
    --> Get the Accounting Period ??????
------------------------------------------------------------------------------

    IF EXISTS
        (
            SELECT TOP 1 Month_End_Date
            FROM AW_Period_Procedures
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  AW_User_Companies_ID = @CompanyID
            ORDER BY Month_End_Date DESC
        )
        BEGIN
            SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date,
                         @Month = [Month],
                         @Year = [Year] 
            FROM AW_Period_Procedures
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  AW_User_Companies_ID = @CompanyID
            ORDER BY Month_End_Date DESC
        END
    ELSE
        BEGIN
            SET @Month = CONVERT(int, DATEPART(mm, getdate()))
        
            SELECT @Year = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE [Description] = CONVERT(varchar(10), DATEPART(yyyy, getdate()))
        END

    SET @Month = @Month + 1

    IF @Month > 12
        BEGIN
            SET @Month = 1
            SET @Year = @Year + 1
        END

------------------------------------------------------------------------------
    --> Get the STANDARD VAT rate
------------------------------------------------------------------------------

    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

    SET @Tax_Rate = @Tax_Rate / 100

------------------------------------------------------------------------------
    --> If ADV2004OLD exists then DO IT
------------------------------------------------------------------------------

    IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'ADV2004OLD')

        BEGIN

        ------------------------------------------------------------------------------
        --> Step 1: Transfer the last 7 Period Procedures
        ------------------------------------------------------------------------------
            INSERT ADV2004..AW_Period_Procedures
                (
                    Sys_AW_Period_Procedure_Types_ID,
                    [Description],
                    [Month],
                    [Year],
                    Month_End_Date,
                    Year_End_Date,
                    Stock_Valuation,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID,
                    Slu_AW_Active_ID
                )
            SELECT TOP 7
                Sys_AW_Period_Procedure_Types_ID,
                [Description],
                [Month],
                [Year],
                Month_End_Date,
                Year_End_Date,
                Stock_Valuation,
                Date_Captured,
                [User_ID],
                AW_User_Companies_ID,
                Slu_AW_Active_ID
            FROM AW_Period_Procedures
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  AW_User_Companies_ID = @CompanyID
            ORDER BY Month_End_Date DESC
            

        ------------------------------------------------------------------------------
        --> Step 2: Get the last 7 Month-End from newly inserted Period Procedures
        ------------------------------------------------------------------------------


            EXEC sp_AW_Period_Procedures_Select
                    @Now,
                    @D1 OUTPUT,
                    @D2 OUTPUT,
                    @D3 OUTPUT,
                    @D4 OUTPUT,
                    @D5 OUTPUT,
                    @D6 OUTPUT,
                    @D7 OUTPUT,
                    1,
                    @CompanyID


        ------------------------------------------------------------------------------
        --> Step 3: Transfer the Customers
        ------------------------------------------------------------------------------

            SET IDENTITY_INSERT ADV2004..AC_Customers ON

            
            INSERT ADV2004..AC_Customers
                (
                    AC_Customers_ID,
                    Surname,
                    Firstnames,
                    Initials,
                    Slu_AW_Titles_ID,
                    Contact_Name,
                    Slu_AW_Languages_ID,
                    IDReg_Number,
                    Customer_Number,
                    Old_Customer_Number,
                    Post_Box,
                    Post_Office,
                    Post_Code,
                    Street_Address,
                    Suburb,
                    City,
                    Street_Post_Code,
                    Delivery_Address,
                    Delivery_Suburb,
                    Delivery_City,
                    Delivery_Post_Code,
                    Head_Office,
                    Lup_AC_Customer_Types_ID,
                    Lup_AC_Customer_Groups_ID,
                    Sys_AC_Account_Status_ID,
                    AW_YesNo_Pre_Notify_ID,
                    AW_YesNo_Post_Notify_ID,
                    Lup_AC_Discount_Categories_ID,
                    Credit_Limit,
                    Slu_AW_Credit_Terms_ID,
                    Sys_AC_Credit_Term_Types_ID,
                    Sys_AC_Account_Types_ID,
                    Credit_Insurers_Reference,
                    Credit_Insurers_Limit,
                    AW_YesNo_Charge_Interest_ID,
                    Slu_AW_Controllers_ID,
                    Lup_AS_Reps_ID,
                    Lup_AC_Sales_Areas_ID,
                    Slu_AW_Countries_ID,
                    Cell_No,
                    Home_Tel_No,
                    Work_Tel_No,
                    Fax_No,
                    Web_Site_URL,
                    Principal_Name,
                    Principal_Firstname,
                    Principal_Birthday,
                    Principal_Contact_Method_ID,
                    Principal_Cell_No,
                    Orders_URL,
                    Home_Email,
                    Work_Email,
                    Start_Date,
                    Sys_AW_Tax_Codes_ID,
                    Tax_Number,
                    Notes,
                    Account_Balance,
                    Current_Balance,
                    Days_30,
                    Days_60,
                    Days_90,
                    Days_120,
                    Days_150,
                    Days_180,
                    Sys_AW_Delivery_Methods_ID,
                    Sys_AC_Use_Assets_ID,
                    AW_YesNo_Send_Email_ID,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID,
                    Slu_AW_Active_ID
                )
            SELECT
                AC_Customers_ID,
                Surname,
                Firstnames,
                Initials,
                Slu_AW_Titles_ID,
                Contact_Name,
                Slu_AW_Languages_ID,
                IDReg_Number,
                Customer_Number,
                Old_Customer_Number,
                Post_Box,
                Post_Office,
                Post_Code,
                Street_Address,
                Suburb,
                City,
                Street_Post_Code,
                Delivery_Address,
                Delivery_Suburb,
                Delivery_City,
                Delivery_Post_Code,
                Head_Office,
                Lup_AC_Customer_Types_ID,
                Lup_AC_Customer_Groups_ID,
                Sys_AC_Account_Status_ID,
                AW_YesNo_Pre_Notify_ID,
                AW_YesNo_Post_Notify_ID,
                Lup_AC_Discount_Categories_ID,
                Credit_Limit,
                Slu_AW_Credit_Terms_ID,
                Sys_AC_Credit_Term_Types_ID,
                Sys_AC_Account_Types_ID,
                Credit_Insurers_Reference,
                Credit_Insurers_Limit,
                AW_YesNo_Charge_Interest_ID,
                Slu_AW_Controllers_ID,
                Lup_AS_Reps_ID,
                Lup_AC_Sales_Areas_ID,
                Slu_AW_Countries_ID,
                Cell_No,
                Home_Tel_No,
                Work_Tel_No,
                Fax_No,
                Web_Site_URL,
                Principal_Name,
                Principal_Firstname,
                Principal_Birthday,
                Principal_Contact_Method_ID,
                Principal_Cell_No,
                Orders_URL,
                Home_Email,
                Work_Email,
                Start_Date,
                Sys_AW_Tax_Codes_ID,
                Tax_Number,
                Notes,
                Account_Balance,
                Current_Balance,
                Days_30,
                Days_60,
                Days_90,
                Days_120,
                Days_150,
                Days_180,
                Sys_AW_Delivery_Methods_ID,
                Sys_AC_Use_Assets_ID,
                AW_YesNo_Send_Email_ID,
                Date_Captured,
                [User_ID],
                AW_User_Companies_ID,
                Slu_AW_Active_ID
            FROM AC_Customers
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AC_Customers_ID


            SET IDENTITY_INSERT ADV2004..AC_Customers OFF


        ------------------------------------------------------------------------------
        --> Step 4: Transfer the Ageing
        ------------------------------------------------------------------------------
            	DECLARE Customer_Cursor CURSOR FOR
                    (
                        SELECT DISTINCT
                            c.AC_Customers_ID
                        FROM AC_Customers c
                            INNER JOIN AS_Transactions t
                                ON c.AC_Customers_ID = t.AC_Customers_ID
                        WHERE c.AW_User_Companies_ID = @CompanyID
                    )
            
            	OPEN Customer_Cursor
            
                	FETCH NEXT FROM Customer_Cursor 
                	INTO
                        @CustomerID
                	
                	WHILE @@FETCH_STATUS = 0
                	BEGIN
            
                		SELECT
                            @AgePayment = Payment,
                            @AgeAmount = Amount,
                            @AgeCurrent = [Current],
                            @Age30Days = [30 Days],
                            @Age60Days = [60 Days],
                            @Age90Days = [90 Days],
                            @Age120Days = [120 Days],
                            @Age150Days = [150 Days],
                            @Age180Days = [180+ Days]
                		FROM dbo.fn_AC_Customer_Ageing_Values
                            (
                                @CustomerID,
                                @Now,
                                @D1,
                                @D2,
                                @D3,
                                @D4,
                                @D5,
                                @D6,
                                @D7
                            )
        
                    --> Update the Account Balance
                        SET @AccountBalance = @AgeCurrent + 
                                              @Age30Days + 
                                              @Age60Days + 
                                              @Age90Days + 
                                              @Age120Days + 
                                              @Age150Days + 
                                              @Age180Days


                        UPDATE ADV2004..AC_Customers
                        SET Account_Balance = @AccountBalance
                        WHERE AC_Customers_ID = @CustomerID
        
        
        
                        IF @AgeCurrent <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

--                                 SET @TransactionDate = DATEADD(m, -1, @LastPeriodProcedureDate)
--                                 SET @TransactionDate = @LastPeriodProcedureDate
                                SET @TransactionDate = @Now
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf Current Ageing'
                                SET @Amount = ROUND(@AgeCurrent / (1 + @Tax_Rate), 2)
                                SET @Tax = @AgeCurrent - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@AgeCurrent,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Age30Days <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

        --                        SET @TransactionDate = DATEADD(m, -1, @LastPeriodProcedureDate)
                                SET @TransactionDate = @LastPeriodProcedureDate
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf 30 Days Ageing'
                                SET @Amount = ROUND(@Age30Days / (1 + @Tax_Rate), 2)
                                SET @Tax = @Age30Days - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Age30Days,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Age60Days <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

                                SET @TransactionDate = DATEADD(m, -1, @LastPeriodProcedureDate)
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf 60 Days Ageing'
                                SET @Amount = ROUND(@Age60Days / (1 + @Tax_Rate), 2)
                                SET @Tax = @Age60Days - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Age60Days,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Age90Days <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

                                SET @TransactionDate = DATEADD(m, -2, @LastPeriodProcedureDate)
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf 90 Days Ageing'
                                SET @Amount = ROUND(@Age90Days / (1 + @Tax_Rate), 2)
                                SET @Tax = @Age90Days - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Age90Days,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Age120Days <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

                                SET @TransactionDate = DATEADD(m, -3, @LastPeriodProcedureDate)
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf 120 Days Ageing'
                                SET @Amount = ROUND(@Age120Days / (1 + @Tax_Rate), 2)
                                SET @Tax = @Age120Days - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Age120Days,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Age150Days <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

                                SET @TransactionDate = DATEADD(m, -4, @LastPeriodProcedureDate)
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf 150 Days Ageing'
                                SET @Amount = ROUND(@Age150Days / (1 + @Tax_Rate), 2)
                                SET @Tax = @Age150Days - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Age150Days,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Age180Days <> 0
                            BEGIN
                                SET @TransactionNo = @TransactionNo + 1
                                SET @RefNo = CONVERT(varchar(15), @TransactionNo) 

                                SET @TransactionDate = DATEADD(m, -5, @LastPeriodProcedureDate)
                                SET @TransactionDate = DATEADD(hh, -1, @TransactionDate)

                                SET @Comment = 'Trf 180 Days Ageing'
                                SET @Amount = ROUND(@Age180Days / (1 + @Tax_Rate), 2)
                                SET @Tax = @Age180Days - @Amount
                            
                                EXEC sp_AA_ADV2004_DB_Transfer_Customer_Ageing
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Age180Days,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
        
                    --> Clear the Ageing Balances of THIS Customer
                    --> In the event that the next Customers has ZERO ageing
                        SET @AgePayment = 0
                        SET @AgeAmount = 0
                        SET @AgeCurrent = 0
                        SET @Age30Days = 0
                        SET @Age60Days = 0
                        SET @Age90Days = 0
                        SET @Age120Days = 0
                        SET @Age150Days = 0
                        SET @Age180Days = 0
        
                    	FETCH NEXT FROM Customer_Cursor 
                    	INTO
                            @CustomerID
            
                	END
            	
            	CLOSE Customer_Cursor
            
            	DEALLOCATE Customer_Cursor


        ------------------------------------------------------------------------------
        --> Step 4: Update the JOURNAL transaction numbers
        ------------------------------------------------------------------------------

            UPDATE ADV2004..Sys_AW_Transaction_Numbers
            SET Last_Number = @TransactionNo
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Transaction_Types_ID = @TransactionType


            SET @ReturnCode = 1


        END    --IF EXISTS ADV2004OLD        



SET NOCOUNT OFF


RETURN @ReturnCode
































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step4_DB_Transfer_GL
--Run From      :NB NB NB Highlight each SP and run in SEQUENCE in SQL Query Analyzer
--Purpose       :Transfers accounting data to NEW ADV2004 DB
--Date          :2004/08/30
--Authors       :TB
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AA_ADV2004_Step4_DB_Transfer_GL

AS


    SET IDENTITY_INSERT AB_Accounts ON

    INSERT AB_Accounts
        (
            AB_Accounts_ID,
            Description,
            Account_Number,
            Sys_AB_Account_Categories_ID,
            Sys_AW_Tax_Codes_ID,
            Lup_AB_Cost_Centers_ID,
            AB_Account_Balance,
            Opening_Balance,
            Opening_Date,
            Opening_Month,
            Opening_Year,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Accounts_ID,
        Description,
        Account_Number,
        Sys_AB_Account_Categories_ID,
        Sys_AW_Tax_Codes_ID,
        Lup_AB_Cost_Centers_ID,
        AB_Account_Balance,
        Opening_Balance,
        Opening_Date,
        Opening_Month,
        Opening_Year,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Accounts

    SET IDENTITY_INSERT AB_Accounts OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Budgets ON

    INSERT AB_Budgets
        (
            AB_Budgets_ID,
            AB_Accounts_ID,
            Slu_AW_Years_ID,
            Slu_AW_Months_ID,
            Budget_Amount,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Budgets_ID,
        AB_Accounts_ID,
        Slu_AW_Years_ID,
        Slu_AW_Months_ID,
        Budget_Amount,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Budgets

    SET IDENTITY_INSERT AB_Budgets OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Control_Accounts ON

    INSERT AB_Control_Accounts
        (
            AB_Control_Accounts_ID,
            Control_Number,
            Description,
            User_Description,
            AB_Accounts_ID,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Control_Accounts_ID,
        Control_Number,
        Description,
        User_Description,
        AB_Accounts_ID,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Control_Accounts

    SET IDENTITY_INSERT AB_Control_Accounts OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AW_Company_Banks ON

    INSERT AW_Company_Banks
        (
            AW_Company_Banks_ID,
            AW_User_Companies_ID,
            Slu_AW_Banks_ID,
            AB_Accounts_ID,
            Bank_Branch,
            Bank_Branch_Code,
            Account_Name,
            Account_Number,
            Date_Opened,
            Date_Captured,
            Slu_AW_Active_ID
        )
    SELECT
        AW_Company_Banks_ID,
        AW_User_Companies_ID,
        Slu_AW_Banks_ID,
        AB_Accounts_ID,
        Bank_Branch,
        Bank_Branch_Code,
        Account_Name,
        Account_Number,
        Date_Opened,
        Date_Captured,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AW_Company_Banks

    SET IDENTITY_INSERT AW_Company_Banks OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Cash_Book_Transactions ON

    INSERT AB_Cash_Book_Transactions
        (
            AB_Cash_Book_Transactions_ID,
            AW_Company_Banks_ID,
            Sys_AB_Transaction_Types_ID,
            Transaction_Date,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Reference_No,
            Transaction_Description,
            Amount,
            Recon_Amount,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Cash_Book_Transactions_ID,
        AW_Company_Banks_ID,
        Sys_AB_Transaction_Types_ID,
        Transaction_Date,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        Reference_No,
        Transaction_Description,
        Amount,
        Recon_Amount,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Cash_Book_Transactions

    SET IDENTITY_INSERT AB_Cash_Book_Transactions OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Cash_Book_Transaction_Details ON

    INSERT AB_Cash_Book_Transaction_Details
        (
            AB_Cash_Book_Transaction_Details_ID,
            AB_Cash_Book_Transactions_ID,
            AB_Accounts_ID,
            Sys_AW_Tax_Methods_ID,
            Amount,
            Sys_AW_Tax_Codes_ID,
            Tax_Amount,
            Net_Amount,
            Comments,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Cash_Book_Transaction_Details_ID,
        AB_Cash_Book_Transactions_ID,
        AB_Accounts_ID,
        Sys_AW_Tax_Methods_ID,
        Amount,
        Sys_AW_Tax_Codes_ID,
        Tax_Amount,
        Net_Amount,
        Comments,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Cash_Book_Transaction_Details

    SET IDENTITY_INSERT AB_Cash_Book_Transaction_Details OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_GL_Transactions ON

    INSERT AB_GL_Transactions
        (
            AB_GL_Transactions_ID,
            Description,
            Sys_AB_Transaction_Types_ID,
            AB_Accounts_ID,
            AB_Transaction_Date,
            AB_Source_Ref,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            AB_Transaction_Ref,
            AB_Transaction_Amount,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_GL_Transactions_ID,
        Description,
        Sys_AB_Transaction_Types_ID,
        AB_Accounts_ID,
        AB_Transaction_Date,
        AB_Source_Ref,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        AB_Transaction_Ref,
        AB_Transaction_Amount,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_GL_Transactions

    SET IDENTITY_INSERT AB_GL_Transactions OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Journal_Details ON

    INSERT AB_Journal_Details
        (
            AB_Journal_Details_ID,
            AB_Journals_ID,
            AB_Accounts_ID,
            Amount,
            Notes,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Journal_Details_ID,
        AB_Journals_ID,
        AB_Accounts_ID,
        Amount,
        Notes,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Journal_Details

    SET IDENTITY_INSERT AB_Journal_Details OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Journals ON

    INSERT AB_Journals
        (
            AB_Journals_ID,
            Journal_Date,
            Journal_Reference,
            Journal_Narration,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Journals_ID,
        Journal_Date,
        Journal_Reference,
        Journal_Narration,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Journals

    SET IDENTITY_INSERT AB_Journals OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Recurring_Details ON

    INSERT AB_Recurring_Details
        (
            AB_Recurring_Details_ID,
            AB_Recurring_ID,
            AB_Accounts_ID,
            Amount,
            Notes,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Recurring_Details_ID,
        AB_Recurring_ID,
        AB_Accounts_ID,
        Amount,
        Notes,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Recurring_Details

    SET IDENTITY_INSERT AB_Recurring_Details OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Recurring ON

    INSERT AB_Recurring
        (
            AB_Recurring_ID,
            Recurring_Date,
            Recurring_Reference,
            Recurring_Narration,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Recurring_ID,
        Recurring_Date,
        Recurring_Reference,
        Recurring_Narration,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Recurring

    SET IDENTITY_INSERT AB_Recurring OFF




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-- **********************************************************************
--
-- Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004
--
-- **********************************************************************





-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step2_Wipe_Customer_Table
--Run From      :NB NB NB Run this SP in SQL Query Analyzer FROM ADV2004
--Purpose       :Creates a BLANK AC_Customers table 
--Parameters    :
--Date          :2004/08/25
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AA_ADV2004_Step4_Wipe_GL_Tables

AS


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_End_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_End_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_Start_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_Start_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Transactions_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_GL_Transactions] DROP CONSTRAINT FK_AB_Transactions_AB_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Prior_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Month_Account_Actuals] DROP CONSTRAINT FK_AB_Prior_AB_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Budget_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Month_Account_Budgets] DROP CONSTRAINT FK_AB_Budget_AB_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Accounts

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Journals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Journals

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Recurring]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Recurring

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transactions_AW_Company_Banks]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] DROP CONSTRAINT FK_AB_Cash_Book_Transactions_AW_Company_Banks

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Accounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Budgets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Control_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Control_Accounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_GL_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journal_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journal_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Company_Banks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Company_Banks]

    
    CREATE TABLE [dbo].[AB_Accounts] (
    	[AB_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AB_Account_Categories_ID] [int] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Lup_AB_Cost_Centers_ID] [int] NULL ,
    	[AB_Account_Balance] [money] NULL ,
    	[Opening_Balance] [money] NULL ,
    	[Opening_Date] [datetime] NULL ,
    	[Opening_Month] [tinyint] NULL ,
    	[Opening_Year] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Budgets] (
    	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Slu_AW_Years_ID] [int] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Budget_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transaction_Details] (
    	[AB_Cash_Book_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transactions] (
    	[AB_Cash_Book_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Reference_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Recon_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Control_Accounts] (
    	[AB_Control_Accounts_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Control_Number] [smallint] NOT NULL ,
    	[Description] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[User_Description] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_GL_Transactions] (
    	[AB_GL_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[AB_Transaction_Date] [datetime] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Transaction_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journal_Details] (
    	[AB_Journal_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journals] (
    	[AB_Journals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Journal_Date] [datetime] NULL ,
    	[Journal_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Journal_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Recurring] (
    	[AB_Recurring_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Recurring_Date] [datetime] NULL ,
    	[Recurring_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Recurring_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Recurring_Details] (
    	[AB_Recurring_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Recurring_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AW_Company_Banks] (
    	[AW_Company_Banks_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Slu_AW_Banks_ID] [smallint] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Bank_Branch] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Branch_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Date_Opened] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AB_Accounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Accounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Accounts_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Budgets_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transaction_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transaction_Details_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_GL_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_GL_Transactions_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journal_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Journal_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journal_Details_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journals] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Journals] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journals_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Recurring] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Recurring_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_Details_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AW_Company_Banks] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Company_Bankers] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Company_Banks_ID]
    	)  ON [PRIMARY] 

    
     CREATE  UNIQUE  CLUSTERED  INDEX [idx_Control_Accounts_Control_No] ON [dbo].[AB_Control_Accounts]([Control_Number]) ON [PRIMARY]

    
     CREATE  UNIQUE  INDEX [PK_AB_Control_Accounts] ON [dbo].[AB_Control_Accounts]([AB_Control_Accounts_ID]) ON [PRIMARY]

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[AB_Account_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Accounts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Accounts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Cost_Centers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Accounts].[Opening_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Month]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Year]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Accounts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Sys_AB_Account_Categories_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Accounts].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[AB_Accounts_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transaction_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transaction_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transaction_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Methods_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transaction_Details].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transactions].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Transactions].[Slu_AW_Months_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Transactions].[Slu_AW_Years_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transactions].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Control_Accounts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Control_Accounts].[Control_Number]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Control_Accounts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Control_Accounts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Control_Accounts].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Ref]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_GL_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_GL_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_GL_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_GL_Transactions].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Journal_Details].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journal_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journal_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journal_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journal_Details].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journals].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journals].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journals].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journals].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Recurring_Details].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring_Details].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Company_Banks].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Company_Banks].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Company_Banks].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Company_Banks].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AB_Accounts] ADD 
    	CONSTRAINT [FK_AB_Accounts_Lup_AB_Cost_Centers] FOREIGN KEY 
    	(
    		[Lup_AB_Cost_Centers_ID]
    	) REFERENCES [dbo].[Lup_AB_Cost_Centers] (
    		[Lup_AB_Cost_Centers_ID]
    	),
    	CONSTRAINT [FK_AB_Accounts_Lup_AW_Tax_Codes] FOREIGN KEY 
    	(
    		[Sys_AW_Tax_Codes_ID]
    	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
    		[Sys_AW_Tax_Codes_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions] FOREIGN KEY 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) REFERENCES [dbo].[AB_Cash_Book_Transactions] (
    		[AB_Cash_Book_Transactions_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transactions_AW_Company_Banks] FOREIGN KEY 
    	(
    		[AW_Company_Banks_ID]
    	) REFERENCES [dbo].[AW_Company_Banks] (
    		[AW_Company_Banks_ID]
    	)

    
    ALTER TABLE [dbo].[AB_GL_Transactions] ADD 
    	CONSTRAINT [FK_AB_GL_Transactions_Lup_AB_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AB_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AB_Transaction_Types] (
    		[Sys_AB_Transaction_Types_ID]
    	),
    	CONSTRAINT [FK_AB_Transactions_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Journal_Details] ADD 
    	CONSTRAINT [FK_AB_Journal_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Journal_Details_AB_Journals] FOREIGN KEY 
    	(
    		[AB_Journals_ID]
    	) REFERENCES [dbo].[AB_Journals] (
    		[AB_Journals_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Recurring_Details] ADD 
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Recurring] FOREIGN KEY 
    	(
    		[AB_Recurring_ID]
    	) REFERENCES [dbo].[AB_Recurring] (
    		[AB_Recurring_ID]
    	)

    






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AA_ADV2004_Step4_DB_Transfer_GL
--Run From      :NB NB NB Highlight each SP and run in SEQUENCE in SQL Query Analyzer
--Purpose       :Transfers accounting data to NEW ADV2004 DB
--Date          :2004/08/30
--Authors       :TB
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AA_ADV2004_Step5_DB_Transfer_GL

AS


    SET IDENTITY_INSERT AB_Accounts ON

    INSERT AB_Accounts
        (
            AB_Accounts_ID,
            Description,
            Account_Number,
            Sys_AB_Account_Categories_ID,
            Sys_AW_Tax_Codes_ID,
            Lup_AB_Cost_Centers_ID,
            AB_Account_Balance,
            Opening_Balance,
            Opening_Date,
            Opening_Month,
            Opening_Year,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Accounts_ID,
        Description,
        Account_Number,
        Sys_AB_Account_Categories_ID,
        Sys_AW_Tax_Codes_ID,
        Lup_AB_Cost_Centers_ID,
        AB_Account_Balance,
        Opening_Balance,
        Opening_Date,
        Opening_Month,
        Opening_Year,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Accounts

    SET IDENTITY_INSERT AB_Accounts OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Budgets ON

    INSERT AB_Budgets
        (
            AB_Budgets_ID,
            AB_Accounts_ID,
            Slu_AW_Years_ID,
            Slu_AW_Months_ID,
            Budget_Amount,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Budgets_ID,
        AB_Accounts_ID,
        Slu_AW_Years_ID,
        Slu_AW_Months_ID,
        Budget_Amount,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Budgets

    SET IDENTITY_INSERT AB_Budgets OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Control_Accounts ON

    INSERT AB_Control_Accounts
        (
            AB_Control_Accounts_ID,
            Control_Number,
            Description,
            User_Description,
            AB_Accounts_ID,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Control_Accounts_ID,
        Control_Number,
        Description,
        User_Description,
        AB_Accounts_ID,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Control_Accounts

    SET IDENTITY_INSERT AB_Control_Accounts OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AW_Company_Banks ON

    INSERT AW_Company_Banks
        (
            AW_Company_Banks_ID,
            AW_User_Companies_ID,
            Slu_AW_Banks_ID,
            AB_Accounts_ID,
            Bank_Branch,
            Bank_Branch_Code,
            Account_Name,
            Account_Number,
            Date_Opened,
            Date_Captured,
            Slu_AW_Active_ID
        )
    SELECT
        AW_Company_Banks_ID,
        AW_User_Companies_ID,
        Slu_AW_Banks_ID,
        AB_Accounts_ID,
        Bank_Branch,
        Bank_Branch_Code,
        Account_Name,
        Account_Number,
        Date_Opened,
        Date_Captured,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AW_Company_Banks

    SET IDENTITY_INSERT AW_Company_Banks OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Cash_Book_Transactions ON

    INSERT AB_Cash_Book_Transactions
        (
            AB_Cash_Book_Transactions_ID,
            AW_Company_Banks_ID,
            Sys_AB_Transaction_Types_ID,
            Transaction_Date,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Reference_No,
            Transaction_Description,
            Amount,
            Recon_Amount,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Cash_Book_Transactions_ID,
        AW_Company_Banks_ID,
        Sys_AB_Transaction_Types_ID,
        Transaction_Date,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        Reference_No,
        Transaction_Description,
        Amount,
        Recon_Amount,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Cash_Book_Transactions

    SET IDENTITY_INSERT AB_Cash_Book_Transactions OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Cash_Book_Transaction_Details ON

    INSERT AB_Cash_Book_Transaction_Details
        (
            AB_Cash_Book_Transaction_Details_ID,
            AB_Cash_Book_Transactions_ID,
            AB_Accounts_ID,
            Sys_AW_Tax_Methods_ID,
            Amount,
            Sys_AW_Tax_Codes_ID,
            Tax_Amount,
            Net_Amount,
            Comments,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Cash_Book_Transaction_Details_ID,
        AB_Cash_Book_Transactions_ID,
        AB_Accounts_ID,
        Sys_AW_Tax_Methods_ID,
        Amount,
        Sys_AW_Tax_Codes_ID,
        Tax_Amount,
        Net_Amount,
        Comments,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Cash_Book_Transaction_Details

    SET IDENTITY_INSERT AB_Cash_Book_Transaction_Details OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_GL_Transactions ON

    INSERT AB_GL_Transactions
        (
            AB_GL_Transactions_ID,
            Description,
            Sys_AB_Transaction_Types_ID,
            AB_Accounts_ID,
            AB_Transaction_Date,
            AB_Source_Ref,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            AB_Transaction_Ref,
            AB_Transaction_Amount,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_GL_Transactions_ID,
        Description,
        Sys_AB_Transaction_Types_ID,
        AB_Accounts_ID,
        AB_Transaction_Date,
        AB_Source_Ref,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        AB_Transaction_Ref,
        AB_Transaction_Amount,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_GL_Transactions

    SET IDENTITY_INSERT AB_GL_Transactions OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Journals ON

    INSERT AB_Journals
        (
            AB_Journals_ID,
            Journal_Date,
            Journal_Reference,
            Journal_Narration,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Journals_ID,
        Journal_Date,
        Journal_Reference,
        Journal_Narration,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Journals

    SET IDENTITY_INSERT AB_Journals OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Journal_Details ON

    INSERT AB_Journal_Details
        (
            AB_Journal_Details_ID,
            AB_Journals_ID,
            AB_Accounts_ID,
            Amount,
            Notes,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Journal_Details_ID,
        AB_Journals_ID,
        AB_Accounts_ID,
        Amount,
        Notes,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Journal_Details

    SET IDENTITY_INSERT AB_Journal_Details OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Recurring ON

    INSERT AB_Recurring
        (
            AB_Recurring_ID,
            Recurring_Date,
            Recurring_Reference,
            Recurring_Narration,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Recurring_ID,
        Recurring_Date,
        Recurring_Reference,
        Recurring_Narration,
        Slu_AW_Months_ID,
        Slu_AW_Years_ID,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Recurring

    SET IDENTITY_INSERT AB_Recurring OFF

--------------------------------------------------------------------

    SET IDENTITY_INSERT AB_Recurring_Details ON

    INSERT AB_Recurring_Details
        (
            AB_Recurring_Details_ID,
            AB_Recurring_ID,
            AB_Accounts_ID,
            Amount,
            Notes,
            Date_Captured,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT
        AB_Recurring_Details_ID,
        AB_Recurring_ID,
        AB_Accounts_ID,
        Amount,
        Notes,
        Date_Captured,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM ADV2004OLD..AB_Recurring_Details

    SET IDENTITY_INSERT AB_Recurring_Details OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[sp_AA_DB_Size_Ver]
    (
            @DB_Name varchar(50),
            @Msg            varchar(500)    OUTPUT,
            @DB_Version     varchar(20)		OUTPUT
    )
AS

SET NOCOUNT ON

Declare @DB_Size        int

Set @Msg = ''

SELECT 
  @DB_Size = (size*8)/1024
FROM 
  sysfiles
WHERE 
  filename Like '%.mdf'

SELECT @DB_Version = Cast( SERVERPROPERTY('productversion') As Varchar)
--SELECT @DB_Size
If SUBSTRING(@DB_Version,1,2) = '8.' --2000
Begin
  If @DB_Size > 1700
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
End

If SUBSTRING(@DB_Version,1,2) = '9.' --2005
Begin
  If @DB_Size > 3400
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
End

If SUBSTRING(@DB_Version,1,2) = '10' --2008
Begin
  If SUBSTRING(@DB_Version,1,4) = '10.0'
  Begin
    If @DB_Size > 3400
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
  End
  
If SUBSTRING(@DB_Version,1,4) = '10.5'
  Begin
    If @DB_Size > 6800
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
  End
End

If SUBSTRING(@DB_Version,1,2) = '11' --2012
Begin
  If @DB_Size > 10200
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
End

Select @Msg

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AA_Insert_Ageing_Journal
--Purpose       :Inserts ONE Customer Journals
--Functionality :Used in Customer Journals
--Parameters    :
--Date          :7 APR 2002
--Authors       :TB
--Version       :1
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AA_Insert_Ageing_Journal
	(
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
		@Account int,    --AB_Accounts_ID
		@Month int, 
		@Year int,
		@TransactionType int,
		@FKID int,
		@CompanyID int,
		@UserID int
	)
AS     

SET NOCOUNT ON

	INSERT AS_Transactions 
		(
	         Transaction_Number,
	         Date_Captured ,
		     Transaction_Date,
	         [Amount] ,
	         Total_Tax_Amount,
	         Total_Amount,
	         AB_Accounts_ID ,
	         Comment,
	         Sys_AW_Transaction_Types_ID ,
	         AC_Customers_ID ,	
		     AW_User_Companies_ID,
		     [User_ID]
		)
	VALUES
		(
			LEFT(LTRIM(RTRIM(@RefNo)),19),
			@Date,
			@Date,
			@Amount,
			@Tax,
			@Total,
			@Account,
			LEFT(LTRIM(RTRIM(@Comment)),20),
			@TransactionType ,
			@FKID,	
			@CompanyID,
			@UserID
		)

-- 3	AS_Transactions_ID	int	4	0
-- 0	AC_Customers_ID	int	4	1
-- 0	AB_Accounts_ID	int	4	1
-- 0	Transaction_Number	varchar	19	1
-- 0	Total_Cost	money	8	1
-- 0	Amount	money	8	1
-- 0	Total_Tax_Amount	money	8	1
-- 0	Total_Discount_Amount	money	8	1
-- 0	Total_Amount	money	8	1
-- 0	Payment_Amount	money	8	1
-- 0	Transaction_Date	datetime	8	1
-- 0	Expiry_Date	smalldatetime	4	1
-- 0	Version_Number	smallint	2	1
-- 0	Customer_Reference	varchar	15	1
-- 0	Comment	varchar	20	1
-- 0	AW_Comments_ID	int	4	1
-- 0	Sys_AW_Transaction_Types_ID	tinyint	1	1
-- 0	Lup_AS_Marketing_Indicators_ID	int	4	1
-- 0	Lup_AW_Stores_ID	smallint	2	1
-- 0	Lup_AW_Workstations_ID	smallint	2	1
-- 0	Lup_AS_Tills_ID	smallint	2	1
-- 0	Lup_AS_Cashiers_ID	smallint	2	1
-- 0	Lup_AS_Reps_ID	smallint	2	1
-- 0	Slu_AW_Currencies_ID	smallint	2	1
-- 0	Old_Sys_AW_Transaction_Types_ID	tinyint	1	1
-- 0	Cancelled_User_ID	int	4	1
-- 0	Cancelled_DateTime	datetime	8	1
-- 0	Cashed_Up	smalldatetime	4	1
-- 0	Day_End	smalldatetime	4	1
-- 0	Transmitted	datetime	8	1
-- 0	Date_Captured	datetime	8	1
-- 0	User_ID	int	4	1
-- 0	AW_User_Companies_ID	int	4	0
-- 0	Touched	timestamp	8	1
-- 0	Slu_AW_Active_ID	tinyint	1	1


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AA_Insert_Suppliers_Ageing_Journal
--Purpose       :Inserts ONE Suppliers Journal
--Functionality :Used in Suppliers Journals
--Date          :03 MAR 2008
--Authors       :TB
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AA_Insert_Suppliers_Ageing_Journal
	(
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
		@Account int,    --AB_Accounts_ID
		@Month int, 
		@Year int,
		@TransactionType int,
		@FKID int,
		@CompanyID int,
		@UserID int
	)
AS     

SET NOCOUNT ON

	INSERT AO_Transactions 
		(
            Document_Number,
            Date_Captured ,
            Document_Date,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Net_Amount,
            Total_Tax_Amount,
            Total_Amount,
            AB_Accounts_ID ,
            Comment,
            Sys_AW_Transaction_Types_ID ,
            AO_Suppliers_ID ,	
            AW_User_Companies_ID,
            [User_ID]
		)
	VALUES
		(
			LEFT(LTRIM(RTRIM(@RefNo)),19),
			@Date,
			@Date,
            @Month,
            @Year,
			@Amount,
			@Tax,
			@Total,
			@Account,
			LEFT(LTRIM(RTRIM(@Comment)),20),
			@TransactionType ,
			@FKID,	
			@CompanyID,
			@UserID
		)


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AA_Step1_Create_AC_Customers_From_XSQSMAS
--Purpose       :Convert UNIX SQSMAS Debtors Master into INSERT Statements:
--Functionality :Tables: Advantage.XSQSMAS into Advantage.AC_Customers
--Parameters    :
--Date          :7 APR 2002
--Authors       :TB
--Version       :1.0.0
--MODS          :14/06/04 - Added new Customer table defs
--              :31/07/04 - Added new Customer table defs - [Start_Date] default
--              :           and new field Lup_AC_Customer_Groups_ID
-------------------------------------------------------------------------------
--Alternatively run this: 'ALTER  AC_Customer INSERT statements from UNIX.sql' 
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AA_Step1_Create_AC_Customers_From_XSQSMAS

AS

SET NOCOUNT ON

    DECLARE
        @TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15),
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
        @Tax_Rate Decimal(5,2),
		@ABAccountID int,    --AB_Accounts_ID
		@Month int, 
		@Year int,
		@FKID int,
		@UserID int,
		@TransactionDate DateTime

    SET @TransactionType = 5
    SET @ABAccountID = 1    --The MATCHING GL entry for Debtors Control
    SET @CompanyID = 1
    SET @UserID = 1

--> Initialize the appropriate TABLES (MUST BE DONE HERE BEFORE TRANSACTIONS sp)
    EXEC sp_AW_9900    --Wipe all SALES Transaction tables
    EXEC sp_AW_9950    --Clear all System Transaction Number tables
    EXEC sp_AW_9960    --Wipe all CUSTOMER Transaction tables

-------------------------------------------------------------------------------
--> CREATE NEW AC_Customers table




    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Customers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Customers]

    
    CREATE TABLE [dbo].[AC_Customers] (
    	[AC_Customers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Surname] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Firstnames] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Initials] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Titles_ID] [tinyint] NULL ,
    	[Contact_Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Languages_ID] [smallint] NULL ,
    	[IDReg_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Street_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Street_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Suburb] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Head_Office] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AC_Customer_Types_ID] [smallint] NULL ,
    	[Lup_AC_Customer_Groups_ID] [smallint] NULL ,
    	[Sys_AC_Account_Status_ID] [tinyint] NULL ,
    	[AW_YesNo_Pre_Notify_ID] [tinyint] NULL ,
    	[AW_YesNo_Post_Notify_ID] [tinyint] NULL ,
    	[Lup_AC_Discount_Categories_ID] [smallint] NULL ,
    	[Credit_Limit] [money] NOT NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Sys_AC_Credit_Term_Types_ID] [int] NULL ,
    	[Sys_AC_Account_Types_ID] [tinyint] NULL ,
    	[Credit_Insurers_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Credit_Insurers_Limit] [money] NULL ,
    	[AW_YesNo_Charge_Interest_ID] [tinyint] NULL ,
    	[Slu_AW_Controllers_ID] [int] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Lup_AC_Sales_Areas_ID] [smallint] NULL ,
    	[Slu_AW_Countries_ID] [smallint] NULL ,
    	[Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Fax_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Web_Site_URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Firstname] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Birthday] [smalldatetime] NULL ,
    	[Principal_Contact_Method_ID] [tinyint] NULL ,
    	[Principal_Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Orders_URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Notes] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Balance] [money] NOT NULL ,
    	[Current_Balance] [money] NULL ,
    	[Days_30] [money] NULL ,
    	[Days_60] [money] NULL ,
    	[Days_90] [money] NULL ,
    	[Days_120] [money] NULL ,
    	[Days_150] [money] NULL ,
    	[Days_180] [money] NULL ,
    	[Sys_AW_Delivery_Methods_ID] [tinyint] NULL ,
    	[Sys_AC_Use_Assets_ID] [tinyint] NULL ,
    	[AW_YesNo_Send_Email_ID] [tinyint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Customers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Customers] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Customers_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Account_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Customers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Charge_Interest_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Post_Notify_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Pre_Notify_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Send_Email_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Credit_Insurers_Limit]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Credit_Limit]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Current_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Customers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_120]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_150]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_180]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_30]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_60]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_90]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Customer_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Customer_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Discount_Categories_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Sales_Areas_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AS_Reps_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Two]', N'[AC_Customers].[Principal_Contact_Method_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Customers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Controllers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Country]', N'[AC_Customers].[Slu_AW_Countries_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Credit_Terms_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Customers].[Slu_AW_Languages_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Titles_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Customers].[Start_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Account_Status_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Account_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Credit_Term_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Customers].[Sys_AC_Use_Assets_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Two]', N'[AC_Customers].[Sys_AW_Delivery_Methods_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Customers].[User_ID]'

    
    setuser





-------------------------------------------------------------------------------
--> INSERT THE FIRST RECORD (CASH SALES)
    INSERT AC_Customers
        (
            Surname,
            Slu_AW_Titles_ID,
            Slu_AW_Languages_ID,
            Lup_AC_Customer_Types_ID,
            Sys_AC_Account_Status_ID,
            Credit_Limit,
            Slu_AW_Credit_Terms_ID,
            Sys_AC_Account_Types_ID,
            AW_YesNo_Charge_Interest_ID,
            Lup_AS_Reps_ID,
            Lup_AC_Sales_Areas_ID,
            Slu_AW_Countries_ID,
            Sys_AW_Tax_Codes_ID
        )
    VALUES
        (
            ' < ** CASUAL SALES ** >',
            1,
            3,
            2,
            1,
            0,
            1,
            1,
            0,
            1,
            1,
            193,
            1
        )

-------------------------------------------------------------------------------
--> INSERT THE REST FROM XSQSMAS
    INSERT AC_Customers
        (
            Customer_Number,
            Old_Customer_Number,
            Surname,
            Initials,
            Work_Tel_No,
            Fax_No,
            Sys_AC_Account_Status_ID,
            Post_Box,
            Post_Office,
            City,
            Post_Code,
            Contact_Name,
            Lup_AS_Reps_ID,
            Sys_AW_Tax_Codes_ID,
            Slu_AW_Languages_ID,
            Credit_Limit,
            Account_Balance,
            Current_Balance,
            Days_30,
            Days_60,
            Days_90,
            Days_120,
            Days_150,
            Notes,
            Lup_AC_Customer_Types_ID,
            Slu_AW_Credit_Terms_ID,
            Sys_AC_Credit_Term_Types_ID,
            Sys_AC_Account_Types_ID
        )
    
    SELECT
        left(ltrim(rtrim(Old_Customer_Number)),10),
        left(ltrim(rtrim(Old_Customer_Number)),10),
        left(ltrim(rtrim(Surname)),40),
        left(ltrim(rtrim(Initials)),10),
        left(ltrim(rtrim(Work_Tel_No)),16),
        left(ltrim(rtrim(Fax_Tel_No)),16),
        CASE
            WHEN Status IS NULL
                THEN 1
            WHEN Status = '0'
                THEN 1
            WHEN Status = '1'
                THEN 1
            WHEN Status = '2'
                THEN 1
            WHEN Status = '3'
                THEN 1
            WHEN Status = '4'
                THEN 1
            WHEN Status = '5'
                THEN 1
            ELSE 1
        END,
--             Sys_AC_Account_Status_ID
--             ------------------------
--             1=Active
--             2=Suspended
--             3=Handed Over
--             4=Closed
--             5=Other
        left(ltrim(rtrim(Add1)),20),
        left(ltrim(rtrim(Add2)),30),
        left(ltrim(rtrim(Add3)),30),
        left(ltrim(rtrim(Post_Code)),10),
        left(ltrim(rtrim(Contact)),30),
        1,        --Rep_Code,
        1,        --VAT (1 = Standard)
        CASE
            WHEN Lang IS NULL
                THEN 3
            WHEN Lang = 'A'
                THEN 2
            WHEN Lang = 'E'
                THEN 3
            ELSE 3
        END,
--             Slu_AW_Languages_ID
--             -------------------
--             1=<None>
--             2=Afrikaans
--             3=English
        convert(money,Credit_Limit),
            convert(money,Days_Current) +
            convert(money,Days_30) +
            convert(money,Days_60) +
            convert(money,Days_90) +
            convert(money,Days_120) +
            convert(money,Days_150),
        convert(money,Days_Current),
        convert(money,Days_30),
        convert(money,Days_60),
        convert(money,Days_90),
        convert(money,Days_120),
        convert(money,Days_150),
        'Discount allowed (from conversion): ' + Discount,
        1,    --Lup_AC_Customer_Types_ID:    1=<None>
        6,    --Slu_AW_Credit_Terms_ID:      6=30 Days
        2,    --Sys_AC_Credit_Term_Types_ID: 2=Statement
        2     --Sys_AC_Account_Types_ID:     2=Credit
    
    FROM XSQSMAS
    ORDER BY Surname


SET NOCOUNT OFF

----------------------------------------------------------------------------------
--    XSQSMAS
-------------
--     Old_Customer_Number	varchar	255	1
--     Surname	varchar	255	1
--     Initials	varchar	255	1
--     Title	varchar	255	1
--     Work_Tel_No	varchar	255	1
--     Fax_Tel_No	varchar	255	1
--     Status	varchar	255	1
--     Add1	varchar	255	1
--     Add2	varchar	255	1
--     Add3	varchar	255	1
--     Post_Code	varchar	255	1
--     Contact	varchar	255	1
--     Rep_Code	varchar	255	1
--     VAT	varchar	255	1
--     Lang	varchar	255	1
--     Credit_Limit	varchar	255	1
--     Max_Limit	varchar	255	1
--     Payment_Date	varchar	255	1
--     Last_Payment	varchar	255	1
--     Days_Current	varchar	255	1
--     Days_30	varchar	255	1
--     Days_60	varchar	255	1
--     Days_90	varchar	255	1
--     Days_120	varchar	255	1
--     Days_150	varchar	255	1
--     Discount	varchar	255	1
----------------------------------------------------------------------------------






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AA_Step2_Insert_Journal_For_Each_Age_Area
--Purpose       :Convert UNIX SQSMAS Debtors Master into Advantage from:
--Functionality :Tables: Advantage.XSQSMAS into Advantage.AC_Customers
--Parameters    :
--Date          :7 APR 2002
--Authors       :TB
--Version       :1.0.0
--RUN: exec sp_AA_Step2_Insert_Journal_For_Each_Age_Area '2002/03/28 23:59:01'
--MODS          :The COMMENTED setup at the end of the sp
--              : is suitable to importing IF CURRENT trans prior to a M/E
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AA_Step2_Insert_Journal_For_Each_Age_Area

    (
        @Last_Month_End_Date datetime
    )

AS

--SET NOCOUNT ON

    DECLARE
        @TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15),
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
        @Tax_Rate Decimal(5,2),
		@ABAccountID int,    --AB_Accounts_ID
		@Month int, 
		@Year int,
		@FKID int,
		@UserID int,
		@TransactionDate DateTime

    SET @TransactionType = 5
    SET @ABAccountID = 1    --The MATCHING GL entry for Debtors Control
    SET @CompanyID = 1
    SET @UserID = 1
    SET @Month = MONTH(@Last_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@Last_Month_End_Date)))

-------------------------------------------------------------------------------
--> CREATE AS_Transaction (Customer Journal) for each Ageing Amount
-------------------------------------------------------------------------------

--> Get the STANDARD VAT rate
    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

    SET @Tax_Rate = @Tax_Rate / 100

--> SET UP a CURSOR for each AC_Customers with a balance
    DECLARE
        @CustomerID int,
        @BalACC money,
        @BalCUR money,
        @Bal30 money,
        @Bal60 money,
        @Bal90 money,
        @Bal120 money,
        @Bal150 money,
        @Bal180 money
    
    DECLARE CustomerBalances CURSOR FOR
        (
            SELECT
                AC_Customers_ID,
                Account_Balance,
                Current_Balance,
                Days_30,
                Days_60,
                Days_90,
                Days_120,
                Days_150,
                Days_180
            FROM AC_Customers
--            WHERE Account_Balance <> 0
            WHERE (Current_Balance + Days_30 + Days_60 + 
                    Days_90 + Days_120 + Days_150 + Days_180) <> 0
        )
    
    OPEN CustomerBalances
    
        FETCH NEXT FROM CustomerBalances
        INTO
            @CustomerID,
            @BalACC,
            @BalCUR,
            @Bal30,
            @Bal60,
            @Bal90,
            @Bal120,
            @Bal150,
            @Bal180
    
    	WHILE @@FETCH_STATUS = 0
        	BEGIN
                IF @BalCUR <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
--                        SET @TransactionDate = DATEADD(m, -1, @Last_Month_End_Date)
                        SET @TransactionDate = @Last_Month_End_Date
                        SET @Comment = 'Current Ageing'
                        SET @Amount = ROUND(@BalCUR / (1 + @Tax_Rate), 2)
                        SET @Tax = @BalCUR - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@BalCUR,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

                IF @Bal30 <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
--                        SET @TransactionDate = DATEADD(m, -1, @Last_Month_End_Date)
                        SET @TransactionDate = @Last_Month_End_Date
                        SET @Comment = '30 Days Ageing'
                        SET @Amount = ROUND(@Bal30 / (1 + @Tax_Rate), 2)
                        SET @Tax = @Bal30 - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@Bal30,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

                IF @Bal60 <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
                        SET @TransactionDate = DATEADD(m, -1, @Last_Month_End_Date)
                        SET @Comment = '60 Days Ageing'
                        SET @Amount = ROUND(@Bal60 / (1 + @Tax_Rate), 2)
                        SET @Tax = @Bal60 - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@Bal60,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

                IF @Bal90 <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
                        SET @TransactionDate = DATEADD(m, -2, @Last_Month_End_Date)
                        SET @Comment = '90 Days Ageing'
                        SET @Amount = ROUND(@Bal90 / (1 + @Tax_Rate), 2)
                        SET @Tax = @Bal90 - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@Bal90,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

                IF @Bal120 <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
                        SET @TransactionDate = DATEADD(m, -3, @Last_Month_End_Date)
                        SET @Comment = '120 Days Ageing'
                        SET @Amount = ROUND(@Bal120 / (1 + @Tax_Rate), 2)
                        SET @Tax = @Bal120 - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@Bal120,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

                IF @Bal150 <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
                        SET @TransactionDate = DATEADD(m, -4, @Last_Month_End_Date)
                        SET @Comment = '150 Days Ageing'
                        SET @Amount = ROUND(@Bal150 / (1 + @Tax_Rate), 2)
                        SET @Tax = @Bal150 - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@Bal150,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

                IF @Bal180 <> 0
                    BEGIN
                        EXEC sp_AW_Get_Next_Transaction_Number
                                @TransactionType,
                                @CompanyID,
                                @RefNo OUTPUT    --varchar(15)
                    
                        SET @TransactionDate = DATEADD(m, -5, @Last_Month_End_Date)
                        SET @Comment = '180 Days Ageing'
                        SET @Amount = ROUND(@Bal180 / (1 + @Tax_Rate), 2)
                        SET @Tax = @Bal180 - @Amount
                    
                        EXEC sp_AA_Insert_Ageing_Journal
                        		@RefNo,
                        		@TransactionDate,
                        		@Comment,
                        		@Amount,
                        		@Tax,
                        		@Bal180,
                        		@ABAccountID,    --AB_Accounts_ID
                        		@Month, 
                        		@Year,
                        		@TransactionType,
                        		@CustomerID,
                        		@CompanyID,
                        		@UserID
                    END

        
            --> GET NEXT Customer
                FETCH NEXT FROM CustomerBalances
                INTO
                    @CustomerID,
                    @BalACC,
                    @BalCUR,
                    @Bal30,
                    @Bal60,
                    @Bal90,
                    @Bal120,
                    @Bal150,
                    @Bal180
        	END
    
    CLOSE CustomerBalances
    
    DEALLOCATE CustomerBalances








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AA_UNIX_Wipe_AS_Transactions_Table
--Purpose       :INSERT Take-On Period Procedures
--Parameters    :Possible @DoCurrent values:
--              :    0 = No
--              :    1 = Yes
--Date          :2005/05/31
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------
CREATE           PROCEDURE sp_AA_Step3_Insert_Take_On_Period_Procedures
    (
        @DropTable tinyint,
        @DoCurrent tinyint,
        @Date datetime
    )

AS

    DECLARE @Today datetime,
            @Last_Month_End_Date datetime,
            @New_Month_End_Date datetime,
            @ME_Description1 varchar(100),
            @ME_Description2 varchar(100),
            @Month tinyint,
            @Year smallint


    SET @ME_Description1 = 'Take-On Customers Month-End ' --e.g. 'Take-On Customers Month-End FEB 2005'
    SET @Today = '2005/05/28 18:00:00'



---------------------------------------------------------

    IF @DropTable = 1
        BEGIN

            if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
            drop table [dbo].[AW_Period_Procedures]
        
            
            CREATE TABLE [dbo].[AW_Period_Procedures] (
            	[AW_Period_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
            	[Sys_AW_Period_Procedure_Types_ID] [int] NULL ,
            	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            	[Month] [tinyint] NULL ,
            	[Year] [smallint] NULL ,
            	[Month_End_Date] [datetime] NULL ,
            	[Year_End_Date] [datetime] NULL ,
            	[Stock_Valuation] [money] NULL ,
            	[Date_Captured] [smalldatetime] NULL ,
            	[User_ID] [int] NULL ,
            	[AW_User_Companies_ID] [int] NULL ,
            	[Touched] [timestamp] NULL ,
            	[Slu_AW_Active_ID] [tinyint] NULL 
            ) ON [PRIMARY]
        
            
            ALTER TABLE [dbo].[AW_Period_Procedures] WITH NOCHECK ADD 
            	CONSTRAINT [PK_AW_Period_Procedures] PRIMARY KEY  CLUSTERED 
            	(
            		[AW_Period_Procedures_ID]
            	)  ON [PRIMARY] 
        
            
            setuser
            EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Period_Procedures].[AW_User_Companies_ID]'
            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Period_Procedures].[Date_Captured]'
            EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Period_Procedures].[Slu_AW_Active_ID]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Period_Procedures].[Stock_Valuation]'
            EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Period_Procedures].[User_ID]'
            setuser

        END

---------------------------------------------------------





---------------------------------------------------------
-- 180+ DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -6, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        ) 
---------------------------------------------------------
-- 150 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -5, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )

---------------------------------------------------------
-- 120 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -4, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- 90 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -3, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- 60 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -2, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- 30 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -1, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- CURRENT
---------------------------------------------------------
    IF @DoCurrent = 1    -- ONLY insert a Month-End if CLOSING Month-End was NOT done
        BEGIN

            SET @New_Month_End_Date = @Today
            SET @Month = MONTH(@New_Month_End_Date)
        
            SELECT @Year = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))
        
            SET @ME_Description2 = @ME_Description1 +
                                   LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                                   DATENAME(year, @New_Month_End_Date)
        
            INSERT AW_Period_Procedures
                (
                    Sys_AW_Period_Procedure_Types_ID,
                    [Description],
                    [Month],
                    [Year],
                    Month_End_Date
                )
            VALUES
                (
                    1,
                    @ME_Description2,
                    @Month,
                    @Year,
                    @New_Month_End_Date
                )
        END
----------------------------------------------------------------------------------------




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AA_Step1_Create_AC_Customers_From_XSQSMAS
--Purpose       :Convert UNIX SQSMAS Debtors Master into INSERT Statements:
--Functionality :Tables: Advantage.XSQSMAS into Advantage.AC_Customers
--Parameters    :
--Date          :7 APR 2002
--Authors       :TB
--Version       :1.0.0
--MODS          :14/06/04 - Added new Customer table defs
--              :31/07/04 - Added new Customer table defs - [Start_Date] default
--              :           and new field Lup_AC_Customer_Groups_ID
--              :27/02/05 - Set default 30-day terms as ID=12 not ID=6
-------------------------------------------------------------------------------
--Alternatively run this: 'ALTER  AC_Customer INSERT statements from UNIX.sql' 
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AA_UNIX_Step1_Create_AC_Customers_From_XSQSMAS

AS

SET NOCOUNT ON

    DECLARE
        @TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15),
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
        @Tax_Rate Decimal(5,2),
		@ABAccountID int,    --AB_Accounts_ID
		@Month int, 
		@Year int,
		@FKID int,
		@UserID int,
		@TransactionDate DateTime

    SET @TransactionType = 5
    SET @ABAccountID = 1    --The MATCHING GL entry for Debtors Control
    SET @CompanyID = 1
    SET @UserID = 1

--> Initialize the appropriate TABLES (MUST BE DONE HERE BEFORE TRANSACTIONS sp)
    EXEC sp_AW_9900    --Wipe all SALES Transaction tables
    EXEC sp_AW_9950    --Clear all System Transaction Number tables
    EXEC sp_AW_9960    --Wipe all CUSTOMER Transaction tables

-------------------------------------------------------------------------------
--> CREATE NEW AC_Customers table




    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Customers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Customers]

    
    CREATE TABLE [dbo].[AC_Customers] (
    	[AC_Customers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Surname] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Firstnames] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Initials] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Titles_ID] [tinyint] NULL ,
    	[Contact_Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Languages_ID] [smallint] NULL ,
    	[IDReg_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Street_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Street_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Suburb] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Head_Office] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AC_Customer_Types_ID] [smallint] NULL ,
    	[Lup_AC_Customer_Groups_ID] [smallint] NULL ,
    	[Sys_AC_Account_Status_ID] [tinyint] NULL ,
    	[AW_YesNo_Pre_Notify_ID] [tinyint] NULL ,
    	[AW_YesNo_Post_Notify_ID] [tinyint] NULL ,
    	[Lup_AC_Discount_Categories_ID] [smallint] NULL ,
    	[Credit_Limit] [money] NOT NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Sys_AC_Credit_Term_Types_ID] [int] NULL ,
    	[Sys_AC_Account_Types_ID] [tinyint] NULL ,
    	[Credit_Insurers_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Credit_Insurers_Limit] [money] NULL ,
    	[AW_YesNo_Charge_Interest_ID] [tinyint] NULL ,
    	[Slu_AW_Controllers_ID] [int] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Lup_AC_Sales_Areas_ID] [smallint] NULL ,
    	[Slu_AW_Countries_ID] [smallint] NULL ,
    	[Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Fax_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Web_Site_URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Firstname] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Birthday] [smalldatetime] NULL ,
    	[Principal_Contact_Method_ID] [tinyint] NULL ,
    	[Principal_Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Orders_URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Notes] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Balance] [money] NOT NULL ,
    	[Current_Balance] [money] NULL ,
    	[Days_30] [money] NULL ,
    	[Days_60] [money] NULL ,
    	[Days_90] [money] NULL ,
    	[Days_120] [money] NULL ,
    	[Days_150] [money] NULL ,
    	[Days_180] [money] NULL ,
    	[Sys_AW_Delivery_Methods_ID] [tinyint] NULL ,
    	[Sys_AC_Use_Assets_ID] [tinyint] NULL ,
    	[AW_YesNo_Send_Email_ID] [tinyint] NULL ,
    	[Default_Settlement_Discount] [decimal](7, 2) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Customers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Customers] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Customers_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Account_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Customers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Charge_Interest_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Post_Notify_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Pre_Notify_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Send_Email_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Credit_Insurers_Limit]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Credit_Limit]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Current_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Customers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_120]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_150]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_180]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_30]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_60]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Days_90]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[Default_Settlement_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Customer_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Customer_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Discount_Categories_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AC_Sales_Areas_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Lup_AS_Reps_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Two]', N'[AC_Customers].[Principal_Contact_Method_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Customers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Controllers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Country]', N'[AC_Customers].[Slu_AW_Countries_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Credit_Terms_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Customers].[Slu_AW_Languages_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AW_Titles_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Customers].[Start_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Account_Status_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Account_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AC_Credit_Term_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Customers].[Sys_AC_Use_Assets_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Two]', N'[AC_Customers].[Sys_AW_Delivery_Methods_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Customers].[User_ID]'

    
    setuser











-------------------------------------------------------------------------------
--> INSERT THE FIRST RECORD (CASH SALES)
    INSERT AC_Customers
        (
            Surname,
            Slu_AW_Titles_ID,
            Slu_AW_Languages_ID,
            Lup_AC_Customer_Types_ID,
            Sys_AC_Account_Status_ID,
            Credit_Limit,
            Slu_AW_Credit_Terms_ID,
            Sys_AC_Account_Types_ID,
            AW_YesNo_Charge_Interest_ID,
            Lup_AS_Reps_ID,
            Lup_AC_Sales_Areas_ID,
            Slu_AW_Countries_ID,
            Sys_AW_Tax_Codes_ID
        )
    VALUES
        (
            ' < ** CASUAL SALES ** >',
            1,
            3,
            2,
            1,
            0,
            1,
            1,
            0,
            1,
            1,
            193,
            1
        )

-------------------------------------------------------------------------------
--> INSERT THE REST FROM XSQSMAS
    INSERT AC_Customers
        (
            Customer_Number,
            Old_Customer_Number,
            Surname,
            Initials,
            Work_Tel_No,
            Fax_No,
            Sys_AC_Account_Status_ID,
            Post_Box,
            Post_Office,
            City,
            Post_Code,
            Contact_Name,
            Lup_AS_Reps_ID,
            Sys_AW_Tax_Codes_ID,
            Slu_AW_Languages_ID,
            Credit_Limit,
            Account_Balance,
            Current_Balance,
            Days_30,
            Days_60,
            Days_90,
            Days_120,
            Days_150,
            Notes,
            Lup_AC_Customer_Types_ID,
            Slu_AW_Credit_Terms_ID,
            Sys_AC_Credit_Term_Types_ID,
            Sys_AC_Account_Types_ID
        )
    
    SELECT
        left(ltrim(rtrim(Old_Customer_Number)),10),
        left(ltrim(rtrim(Old_Customer_Number)),10),
        left(ltrim(rtrim(Surname)),40),
        left(ltrim(rtrim(Initials)),10),
        left(ltrim(rtrim(Work_Tel_No)),16),
        left(ltrim(rtrim(Fax_Tel_No)),16),
        CASE
            WHEN Status IS NULL
                THEN 1
            WHEN Status = '0'
                THEN 1
            WHEN Status = '1'
                THEN 1
            WHEN Status = '2'
                THEN 1
            WHEN Status = '3'
                THEN 1
            WHEN Status = '4'
                THEN 1
            WHEN Status = '5'
                THEN 1
            ELSE 1
        END,
--             Sys_AC_Account_Status_ID
--             ------------------------
--             1=Active
--             2=Suspended
--             3=Handed Over
--             4=Closed
--             5=Other
        left(ltrim(rtrim(Add1)),20),
        left(ltrim(rtrim(Add2)),30),
        left(ltrim(rtrim(Add3)),30),
        left(ltrim(rtrim(Post_Code)),10),
        left(ltrim(rtrim(Contact)),30),
        1,        --Rep_Code,
        1,        --VAT (1 = Standard)
        CASE
            WHEN Lang IS NULL
                THEN 3
            WHEN Lang = 'A'
                THEN 2
            WHEN Lang = 'E'
                THEN 3
            ELSE 3
        END,
--             Slu_AW_Languages_ID
--             -------------------
--             1=<None>
--             2=Afrikaans
--             3=English
        convert(money,Credit_Limit),
            convert(money,Days_Current) +
            convert(money,Days_30) +
            convert(money,Days_60) +
            convert(money,Days_90) +
            convert(money,Days_120) +
            convert(money,Days_150),
        convert(money,Days_Current),
        convert(money,Days_30),
        convert(money,Days_60),
        convert(money,Days_90),
        convert(money,Days_120),
        convert(money,Days_150),
        'Discount allowed (from conversion): ' + Discount,
        1,    --Lup_AC_Customer_Types_ID:    1=<None>
        12,    --Slu_AW_Credit_Terms_ID:     12=30 Days
        2,    --Sys_AC_Credit_Term_Types_ID: 2=Statement
        2     --Sys_AC_Account_Types_ID:     2=Credit
    
    FROM XSQSMAS
    ORDER BY Surname


SET NOCOUNT OFF

----------------------------------------------------------------------------------
--    XSQSMAS
-------------
--     Old_Customer_Number	varchar	255	1
--     Surname	varchar	255	1
--     Initials	varchar	255	1
--     Title	varchar	255	1
--     Work_Tel_No	varchar	255	1
--     Fax_Tel_No	varchar	255	1
--     Status	varchar	255	1
--     Add1	varchar	255	1
--     Add2	varchar	255	1
--     Add3	varchar	255	1
--     Post_Code	varchar	255	1
--     Contact	varchar	255	1
--     Rep_Code	varchar	255	1
--     VAT	varchar	255	1
--     Lang	varchar	255	1
--     Credit_Limit	varchar	255	1
--     Max_Limit	varchar	255	1
--     Payment_Date	varchar	255	1
--     Last_Payment	varchar	255	1
--     Days_Current	varchar	255	1
--     Days_30	varchar	255	1
--     Days_60	varchar	255	1
--     Days_90	varchar	255	1
--     Days_120	varchar	255	1
--     Days_150	varchar	255	1
--     Discount	varchar	255	1
----------------------------------------------------------------------------------
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






-------------------------------------------------------------------------------
-- NB NB NB - If final Month-End procedure HAS NOT BEEN COMPLETED (value = 1)
--            then the FINAL PERIOD PROCEDURE must be run in the SYSTEM menu
--            BEFORE the system goes LIVE
-------------------------------------------------------------------------------

-------------------------------------------------------------------------------
--Description   :sp_AA_Step2_Insert_Journal_For_Each_Age_Area
--Purpose       :Convert UNIX SQSMAS Debtors Master into Advantage from:
--Functionality :Tables: Advantage.XSQSMAS into Advantage.AC_Customers
--              :
--              :Pass in Date as e.g. '2006/03/28 17:00:00'
--              :
--Date          :7 APR 2002
--Authors       :TB
--Version       :1.0.0
--RUN           :EXEC sp_AA_Step2_Insert_Journal_For_Each_Age_Area '2005/02/28 20:00:00', 2
--MODS          :27/02/05 - Added @ME_Status input parameter to specify if the
--              :           final Month-End procedure has been completed (value = 2)
--              :           or
--              :           final Month-End procedure has NOT been completed (value = 1)
--              :27/02/05 - Added WIPE AS_Transactions table
--              :27/02/05 - Added WIPE and INSERT Period Procedures
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AA_UNIX_Step2_Insert_Journal_For_Each_Age_Area

    (
        @Today datetime,
        @ME_Status tinyint = 2
    )

AS

--SET NOCOUNT ON

    DECLARE
        @TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15),
		@RefNo varchar(20),
		@Date datetime,
		@Comment varchar(50),
		@Amount money,
		@Tax money,
		@Total money,
        @Tax_Rate Decimal(5,2),
		@ABAccountID int,    --AB_Accounts_ID
		@Month int, 
		@Year int,
		@FKID int,
		@UserID int,
		@TransactionDate datetime,
        @Last_Month_End_Date datetime,
        @New_Month_End_Date datetime,
        @ME_Description1 varchar(100),
        @ME_Description2 varchar(100),
        @MonthID tinyint,
        @YearID smallint

----------------------------------------------------------------------------------------
-- WIPE THE AS_Transactions
----------------------------------------------------------------------------------------
    EXEC sp_AA_UNIX_Wipe_AS_Transactions_Table
----------------------------------------------------------------------------------------


    SET @TransactionType = 5
--    SET @ABAccountID = 1    --The MATCHING GL entry for Debtors Control
    SET @CompanyID = 1
    SET @UserID = 1
    SET @Last_Month_End_Date = @Today


    IF @ME_Status = 2
        BEGIN
            SET @Last_Month_End_Date = DATEADD(m, -1, @Today)
        END


    SET @Month = MONTH(@Last_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@Last_Month_End_Date)))


--> GET DEBTORS CONTROL ID
	SELECT @ABAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 101    --Debtors Control

-------------------------------------------------------------------------------
--> CREATE AS_Transaction (Customer Journal) for each Ageing Amount
-------------------------------------------------------------------------------

--> Get the STANDARD VAT rate
    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

    SET @Tax_Rate = @Tax_Rate / 100

--> SET UP a CURSOR for each AC_Customers with a balance
    DECLARE
        @CustomerID int,
        @BalACC money,
        @BalCUR money,
        @Bal30 money,
        @Bal60 money,
        @Bal90 money,
        @Bal120 money,
        @Bal150 money,
        @Bal180 money
    
    DECLARE CustomerBalances CURSOR FOR
        (
            SELECT
                AC_Customers_ID,
                Account_Balance,
                Current_Balance,
                Days_30,
                Days_60,
                Days_90,
                Days_120,
                Days_150,
                Days_180
            FROM AC_Customers
--            WHERE Account_Balance <> 0
            WHERE (Current_Balance + Days_30 + Days_60 + 
                    Days_90 + Days_120 + Days_150 + Days_180) <> 0
        )
    
    OPEN CustomerBalances
    
        FETCH NEXT FROM CustomerBalances
        INTO
            @CustomerID,
            @BalACC,
            @BalCUR,
            @Bal30,
            @Bal60,
            @Bal90,
            @Bal120,
            @Bal150,
            @Bal180
    
    	WHILE @@FETCH_STATUS = 0
        	BEGIN

----------------------------------------------------------------------------------------
-- AFTER FINAL Month-End HAS BEEN COMPLETED
----------------------------------------------------------------------------------------

                IF @ME_Status = 2
                    BEGIN
                        IF @BalCUR <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = @Last_Month_End_Date
                                SET @Comment = 'Current Ageing'
                                SET @Amount = ROUND(@BalCUR / (1 + @Tax_Rate), 2)
                                SET @Tax = @BalCUR - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@BalCUR,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal30 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -1, @Last_Month_End_Date)
--                                SET @TransactionDate = @Last_Month_End_Date
                                SET @Comment = '30 Days Ageing'
                                SET @Amount = ROUND(@Bal30 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal30 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal30,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal60 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
--                                SET @TransactionDate = DATEADD(m, -1, @Last_Month_End_Date)
                                SET @TransactionDate = DATEADD(m, -2, @Last_Month_End_Date)
                                SET @Comment = '60 Days Ageing'
                                SET @Amount = ROUND(@Bal60 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal60 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal60,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal90 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
--                                SET @TransactionDate = DATEADD(m, -2, @Last_Month_End_Date)
                                SET @TransactionDate = DATEADD(m, -3, @Last_Month_End_Date)
                                SET @Comment = '90 Days Ageing'
                                SET @Amount = ROUND(@Bal90 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal90 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal90,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal120 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,        
                                        @RefNo OUTPUT    --varchar(15)
                            
--                                SET @TransactionDate = DATEADD(m, -3, @Last_Month_End_Date)
                                SET @TransactionDate = DATEADD(m, -4, @Last_Month_End_Date)
                                SET @Comment = '120 Days Ageing'
                                SET @Amount = ROUND(@Bal120 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal120 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal120,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal150 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
--                                SET @TransactionDate = DATEADD(m, -4, @Last_Month_End_Date)
                                SET @TransactionDate = DATEADD(m, -5, @Last_Month_End_Date)
                                SET @Comment = '150 Days Ageing'
                                SET @Amount = ROUND(@Bal150 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal150 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal150,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal180 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
--                                SET @TransactionDate = DATEADD(m, -5, @Last_Month_End_Date)
                                SET @TransactionDate = DATEADD(m, -6, @Last_Month_End_Date)
                                SET @Comment = '180 Days Ageing'
                                SET @Amount = ROUND(@Bal180 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal180 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal180,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
                    END

----------------------------------------------------------------------------------------
-- BEFORE FINAL Month-End HAS BEEN COMPLETED
----------------------------------------------------------------------------------------

                ELSE
                IF @ME_Status = 1
                    BEGIN
                        IF @BalCUR <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = @Today
                                SET @Comment = 'Current Ageing'
                                SET @Amount = ROUND(@BalCUR / (1 + @Tax_Rate), 2)
                                SET @Tax = @BalCUR - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@BalCUR,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal30 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -1, @Today)
                                SET @Comment = '30 Days Ageing'
                                SET @Amount = ROUND(@Bal30 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal30 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal30,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal60 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -2, @Today)
                                SET @Comment = '60 Days Ageing'
                                SET @Amount = ROUND(@Bal60 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal60 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal60,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal90 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -3, @Today)
                                SET @Comment = '90 Days Ageing'
                                SET @Amount = ROUND(@Bal90 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal90 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal90,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal120 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,        
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -4, @Today)
                                SET @Comment = '120 Days Ageing'
                                SET @Amount = ROUND(@Bal120 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal120 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal120,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal150 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -5, @Today)
                                SET @Comment = '150 Days Ageing'
                                SET @Amount = ROUND(@Bal150 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal150 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal150,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
        
                        IF @Bal180 <> 0
                            BEGIN
                                EXEC sp_AW_Get_Next_Transaction_Number
                                        @TransactionType,
                                        @CompanyID,
                                        @RefNo OUTPUT    --varchar(15)
                            
                                SET @TransactionDate = DATEADD(m, -6, @Today)
                                SET @Comment = '180 Days Ageing'
                                SET @Amount = ROUND(@Bal180 / (1 + @Tax_Rate), 2)
                                SET @Tax = @Bal180 - @Amount
                            
                                EXEC sp_AA_Insert_Ageing_Journal
                                		@RefNo,
                                		@TransactionDate,
                                		@Comment,
                                		@Amount,
                                		@Tax,
                                		@Bal180,
                                		@ABAccountID,    --AB_Accounts_ID
                                		@Month, 
                                		@Year,
                                		@TransactionType,
                                		@CustomerID,
                                		@CompanyID,
                                		@UserID
                            END
                    END

        
            --> GET NEXT Customer
                FETCH NEXT FROM CustomerBalances
                INTO
                    @CustomerID,
                    @BalACC,
                    @BalCUR,
                    @Bal30,
                    @Bal60,
                    @Bal90,
                    @Bal120,
                    @Bal150,
                    @Bal180
        	END
    
    CLOSE CustomerBalances
    
    DEALLOCATE CustomerBalances


----------------------------------------------------------------------------------------
-- INSERT THE PERIOD PROCEDURES 
----------------------------------------------------------------------------------------

    EXEC sp_AA_UNIX_Wipe_Period_Procedure_Table

    SET @ME_Description1 = 'Take-On Customers Month-End ' --e.g. 'Take-On Customers Month-End FEB 2005'



---------------------------------------------------------
-- 180+ DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -6, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        ) 
---------------------------------------------------------
-- 150 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -5, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )

---------------------------------------------------------
-- 120 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -4, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- 90 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -3, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- 60 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -2, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- 30 DAYS
---------------------------------------------------------
    SET @New_Month_End_Date = DATEADD(m, -1, @Today)
    SET @Month = MONTH(@New_Month_End_Date)

    SELECT @Year = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))

    SET @ME_Description2 = @ME_Description1 +
                           LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                           DATENAME(year, @New_Month_End_Date)

    INSERT AW_Period_Procedures
        (
            Sys_AW_Period_Procedure_Types_ID,
            [Description],
            [Month],
            [Year],
            Month_End_Date
        )
    VALUES
        (
            1,
            @ME_Description2,
            @Month,
            @Year,
            @New_Month_End_Date
        )
---------------------------------------------------------
-- CURRENT
---------------------------------------------------------
    IF @ME_Status = 2    -- ONLY insert a Month-End if Month-End procedure has been completed
        BEGIN

            SET @New_Month_End_Date = @Today
            SET @Month = MONTH(@New_Month_End_Date)
        
            SELECT @Year = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE [Description] = LTRIM(RTRIM(YEAR(@New_Month_End_Date)))
        
            SET @ME_Description2 = @ME_Description1 +
                                   LEFT(UPPER(DATENAME(month, @New_Month_End_Date)), 3) + ' ' +
                                   DATENAME(year, @New_Month_End_Date)
        
            INSERT AW_Period_Procedures
                (
                    Sys_AW_Period_Procedure_Types_ID,
                    [Description],
                    [Month],
                    [Year],
                    Month_End_Date
                )
            VALUES
                (
                    1,
                    @ME_Description2,
                    @Month,
                    @Year,
                    @New_Month_End_Date
                )
        END
----------------------------------------------------------------------------------------







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AA_UNIX_Wipe_AS_Transactions_Table
--Purpose       :Creates a BLANK AS_Transactions table 
--Date          :2005/02/27
--Authors       :TB
--MODS          :05/05/06 - Updated with 2004.2.8 definitions
--2004.3.6      :26/06/07 - Updated with 2004.3.6 definitions
--2004.3.7      :09/11/07 - Updated with 2004.3.7 definitions
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AA_UNIX_Wipe_AS_Transactions_Table

AS
  


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions]

    
    CREATE TABLE [dbo].[AS_Transactions] (
    	[AS_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total_Cost] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Discount_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Expiry_Date] [smalldatetime] NULL ,
    	[Version_Number] [smallint] NULL ,
    	[Customer_Reference] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Lup_AS_Marketing_Indicators_ID] [int] NULL ,
    	[Lup_AW_Stores_ID] [smallint] NULL ,
    	[Lup_AW_Workstations_ID] [smallint] NULL ,
    	[Lup_AS_Tills_ID] [smallint] NULL ,
    	[Lup_AS_Cashiers_ID] [smallint] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Slu_AW_Currencies_ID] [smallint] NULL ,
    	[Old_Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Cancelled_User_ID] [int] NULL ,
    	[Cancelled_DateTime] [datetime] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Transmitted] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transactions] ON [dbo].[AS_Transactions]([AC_Customers_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [PK_AS_Transactions] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transactions_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Transactions_Date_Captured] ON [dbo].[AS_Transactions]([Date_Captured]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Transactions_Transaction_Type] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Transactions_Comment] ON [dbo].[AS_Transactions]([Comment]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_ActiveJobSalesOrders] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID], [Slu_AW_Active_ID]) ON [PRIMARY]

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Cashiers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Reps_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Tills_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Stores_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Workstations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Payment_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Transaction_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions].[User_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Version_Number]'

    
    setuser

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [FK_AS_Transactions_AW_Comments] FOREIGN KEY 
    	(
    		[AW_Comments_ID]
    	) REFERENCES [dbo].[AW_Comments] (
    		[AW_Comments_ID]
    	) NOT FOR REPLICATION ,
    	CONSTRAINT [FK_AS_Transactions_Lup_AS_Tills] FOREIGN KEY 
    	(
    		[Lup_AS_Tills_ID]
    	) REFERENCES [dbo].[Lup_AS_Tills] (
    		[Lup_AS_Tills_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Stores] FOREIGN KEY 
    	(
    		[Lup_AW_Stores_ID]
    	) REFERENCES [dbo].[Lup_AW_Stores] (
    		[Lup_AW_Stores_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Workstations] FOREIGN KEY 
    	(
    		[Lup_AW_Workstations_ID]
    	) REFERENCES [dbo].[Lup_AW_Workstations] (
    		[Lup_AW_Workstations_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Sys_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    
    alter table [dbo].[AS_Transactions] nocheck constraint [FK_AS_Transactions_AW_Comments]





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AA_UNIX_Wipe_Period_Procedure_Table
--Purpose       :Creates a BLANK AW_Period_Procedures table 
--Date          :2005/02/27
--Authors       :TB
--MODS          :
--2004.3.6      :26/06/07 - Updated with 2004.3.6 definitions
--2004.3.7      :09/11/07 - Updated with 2004.3.7 definitions
--2004.3.8      :01/06/08 - Updated with 2004.3.8 definitions
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AA_UNIX_Wipe_Period_Procedure_Table

AS
  

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures]

    
    CREATE TABLE [dbo].[AW_Period_Procedures] (
    	[AW_Period_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AW_Period_Procedure_Types_ID] [int] NULL ,
    	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Month] [tinyint] NULL ,
    	[Year] [smallint] NULL ,
    	[Month_End_Date] [datetime] NULL ,
    	[Year_End_Date] [datetime] NULL ,
    	[Stock_Valuation] [money] NULL ,
    	[Date_Captured] [smalldatetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AW_Period_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Period_Procedures].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Period_Procedures].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Period_Procedures].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Period_Procedures].[Stock_Valuation]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Period_Procedures].[User_ID]'

    
    setuser

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    SET QUOTED_IDENTIFIER OFF 

    SET ANSI_NULLS ON 






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_1100
--Purpose       :GL BUDGET GENERATOR 1
--Parameters    :
--Date          :2002/12/09
--Authors       :TB
--MODS:         :08/04/03 - Fixed Option 2 retrieving correct fiscal period
--              :           actuals when generating the budget for the target period
--2004.2.7      :09/03/06 - Replaced Option 1 DROP AB_Budgets with DELETE @YearID
--              :09/03/06 - Added Option 4 DROP AB_Budgets table
--2004.5.5      :10/11/11 - Added @GLAccountID parameter to delete budget delete for
--              :           one selected GL Account
--              :10/11/11 - Added @UserID parameter to UPDATE the USER of cleared budgets
--              :10/11/11 - Added @Option 5 to delete budget delete for one selected Account Category
--              :10/11/11 - Added @Option 6 to delete budget delete for one selected GL Account
--              :10/11/11 - Reworked @Option 1 completely to SET budget = 0 instead of deleting it
--RL	V6.0	2014-10-14 - Checked if year end month = 12, If so do not add 1 to year end
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_1100]
    (
        @Option int,
        @Year int,
        @CompanyID int,
        @GLAccountID int,
        @GLCategoryID int,
        @UserID int
    )

AS

    DECLARE @YearID int,
            @MonthID int,
            @RetCode int,
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


    SET @RetCode = 0


    --> Get the Slu_AW_Years_ID for the Fiscal Year
    IF @Option = 0
        BEGIN
            SELECT @YearID = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE [Description] = @Year

            SET @RetCode = @YearID
        END

    --> Clear ALL Budgets for a Fiscal Year
    ELSE
    IF @Option = 1
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            EXEC sp_AB_Get_Fiscal_Span
                                @CompanyID,
                                @YearEndMonthID OUTPUT,
                                @StartMonthID OUTPUT,
                                @StartYearID OUTPUT,
                                @MonthID OUTPUT,
                                @YearID OUTPUT


            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            UPDATE AB_Budgets
            SET Budget_Amount = 0,
                [User_ID] = @UserID
            WHERE AW_User_Companies_ID = @CompanyID AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod

            SET @RetCode = 1
        END

    --> Get the ID and Account Balance of ALL GL Accounts in ONE Category
    ELSE
    IF @Option = 2
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            -- NEW 06/03/03----------------------------------
            EXEC sp_AB_Get_Fiscal_Span
                                @CompanyID,
                                @YearEndMonthID OUTPUT,
                                @StartMonthID OUTPUT,
                                @StartYearID OUTPUT,
                                @MonthID OUTPUT,
                                @YearID OUTPUT
        
            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            ------------------------------------------------
        
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

            SELECT a.AB_Accounts_ID AS [ID],
                  (
                      SELECT ISNULL(SUM(AB_Transaction_Amount), 0)
                      FROM AB_GL_Transactions
                      WHERE AW_User_Companies_ID = @CompanyID AND
                            AB_Accounts_ID = a.AB_Accounts_ID AND
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @StartPeriod AND
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod AND
                            Sys_AB_Transaction_Types_ID <> 16
                  ) AS [Current]
            FROM AB_Accounts a
                LEFT JOIN Sys_AB_Account_Categories b
                    ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
            WHERE a.Sys_AB_Account_Categories_ID = @GLCategoryID
            ORDER BY [ID]

            SET @RetCode = 1
        END

    --> Get the ID and Account Balance of ALL Income Statement Accounts
    ELSE
    IF @Option = 3
        BEGIN
            SELECT @YearID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

            SET @RetCode = @YearID
        END

    --> DROP AB_Budgets table (Clear ALL Budgets)
    ELSE
    IF @Option = 4
        BEGIN
            if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
            drop table [dbo].[AB_Budgets]

            CREATE TABLE [dbo].[AB_Budgets] (
            	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
            	[AB_Accounts_ID] [int] NOT NULL ,
            	[Slu_AW_Years_ID] [int] NOT NULL ,
            	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
            	[Budget_Amount] [money] NULL ,
            	[Date_Captured] [datetime] NULL ,
            	[User_ID] [int] NULL ,
            	[AW_User_Companies_ID] [int] NOT NULL ,
            	[Touched] [timestamp] NULL ,
            	[Slu_AW_Active_ID] [tinyint] NULL 
            ) ON [PRIMARY]

            ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
            	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
            	(
            		[AB_Budgets_ID]
            	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

            setuser

            EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'

            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'

            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'

            EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'

            EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'

            setuser

            SET @RetCode = 1
        END

    --> Clear ALL Budgets for a Account Category for a Fiscal Year
    ELSE
    IF @Option = 5
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            EXEC sp_AB_Get_Fiscal_Span
                                @CompanyID,
                                @YearEndMonthID OUTPUT,
                                @StartMonthID OUTPUT,
                                @StartYearID OUTPUT,
                                @MonthID OUTPUT,
                                @YearID OUTPUT


            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            UPDATE b
            SET b.Budget_Amount = 0,
                b.[User_ID] = @UserID
            FROM AB_Budgets b
                INNER JOIN AB_Accounts g
                    ON b.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE b.AW_User_Companies_ID = @CompanyID AND
                  g.Sys_AB_Account_Categories_ID = @GLCategoryID AND
                  dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= @EndPeriod

            SET @RetCode = 1
        END

    --> Clear ALL Budgets for a GL Account for a Fiscal Year
    ELSE
    IF @Option = 6
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            EXEC sp_AB_Get_Fiscal_Span
                                @CompanyID,
                                @YearEndMonthID OUTPUT,
                                @StartMonthID OUTPUT,
                                @StartYearID OUTPUT,
                                @MonthID OUTPUT,
                                @YearID OUTPUT

            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            UPDATE AB_Budgets
            SET Budget_Amount = 0,
                [User_ID] = @UserID
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AB_Accounts_ID = @GLAccountID AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod

            SET @RetCode = 1
        END
RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_1110
--Purpose       :GL BUDGET GENERATOR 2
--Functionality :INSERTS A NEW BUDGET FOR ONE MONTH FOR A GL ACCOUNT
--Date          :2002/12/09
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_1110
    (
    	@GLAccountID int,
        @YearID int,
        @MonthID tinyint,
    	@Amount money,
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    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
            DELETE AB_Budgets
        END

    BEGIN
        INSERT AB_Budgets
            (
                AB_Accounts_ID,
                Slu_AW_Years_ID,
                Slu_AW_Months_ID,
                Budget_Amount,
                AW_User_Companies_ID,
                [User_ID]
            )
        VALUES
            (
            	@GLAccountID,
                @YearID,
                @MonthID,
            	@Amount,
                @CompanyID,
                @UserID
            )
    END


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




-------------------------------------------------------------------------------
--Description   :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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_1200
--Purpose       :Get the Fiscal Year from the Slu_AW_Years_ID
--Parameters    :
--Date          :2002/12/09
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_1200
    (
        @YearID int
    )

AS

    DECLARE @Year int,
            @ReturnID int


    SELECT @Year = [Description]
    FROM Slu_AW_Years
    WHERE Slu_AW_Years_ID = @YearID

    SET @ReturnID = @Year

    RETURN @ReturnID    









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AB_9000
--Purpose       :Financial Ratios
--Functionality :All items from GL transactions
--Date          :2002/12/14
--Authors       :TB
--Version       :1.0.0
--MODS:         :17/12/02 - Current Inventory (CI) modified to fetch only amounts > 0
--              :           (Closing Stock valuations) for a SPECIFIED month/year
--              :17/12/02 - Cost of Sales (COS) modified to fetch only amounts
--              :           for a SPECIFIED month/year
--              :17/12/02 - Net Income (NI) modified to Profit/(Loss) for the Period
--              :19/12/02 - Added Cash Flow (Net Cash)
--              :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :09/09/03 - Modified Option 15 (CURRENT INVENTORY) to use Month-End
--              :           inventory valuation from the Customers Period Procedure
-------------------------------------------------------------------------------

CREATE                       PROCEDURE sp_AB_9000
    (
        @CompanyID int,
        @Option tinyint,
        @MonthID int,
        @YearID int
    )

--     SET @CompanyID = 1
--     SET @Option = 8
--     SET @MonthID = 12
--     SET @YearID = 3

AS

SET NOCOUNT ON

    DECLARE @EndPeriod varchar(6),
            @TempMoney money,
            @CurrentMonth tinyint,
            @CurrentYear int

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

-------------------------------------------------------------------------------
-- 1  = NP  -   Net Profit (BS=Accumulated P/L) (IS=Net P/L for the period)
-- 2  = CA	-	Current Assets: Accounts Receivable, Inventory, Cash, etc.
-- 3  = CL	-	Current Liabilities: Accounts Payable, Overdraft, Tax, etc.
-- 4  = FA	-	Fixed Assets: Property, Vehicles, Plant, Machinery, etc.
-- 5  = LTL	-	Long Term Liabilities:	Long Term Loans, etc.
-- 6  = TL	-	Total Liabilities:		CA + FA + OE
-- 7  = TA	-	Total Assets:		CA + LTL
-- 8  = OE	-	Owners Equity:		TA - TL
-- 9  = S	-	Sales
-- 10 = COS	-	Cost of Sales:		Direct costs related to goods sold
-- 11 = E	-	Expenses:		Indirect costs related to business activities
-- 12 = NI	-	Net Income:		S - E = Operating Profit - (Interest + Tax)

-- 13 = OI	-	Opening Inventory
-- 14 = CI	-	Closing Inventory
-- 15 = AI	- 	Average Inventory	(OI + CI) / 2
-------------------------------------------------------------------------------

    --Net Profit
    IF @Option = 1
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [NP]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_Account_Types_ID > 2 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END
    
    --Current Assets
    ELSE
    IF @Option = 2
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [CA]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B2_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Current Liabilities
    ELSE
    IF @Option = 3
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [CL]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B2_ID = 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Fixed Assets
    IF @Option = 4
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [FA]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B3_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Long Term Liabilities
    IF @Option = 5
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [LTL]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B2_ID = 40 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Total Liabilities (CA + FA + OE)
    IF @Option = 6
        BEGIN
            SELECT
                (
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 20 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                +
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B3_ID = 10 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                +
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 30 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                ) AS [TL]
        END

    --Total Assets (CA + LTL)
    IF @Option = 7
        BEGIN
            SELECT
                (
                    --CA
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 20 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                +
                    --LTL
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 40 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                ) AS [TA]
        END

    -- Owners Equity (TA - TL)
    IF @Option = 8
        BEGIN
            SELECT
                --Total Assets (CA + LTL)
                (
                    --CA
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 20 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                +
                    --LTL
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 40 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                )
            -
                (
                    --CA
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 20 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                +
                    --FA
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B3_ID = 10 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                +
                    --OE
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 30 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                           a.Slu_AW_Months_ID <= @MonthID AND
--                           a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                ) AS [OE]
        END

    --Sales
    IF @Option = 9
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [S]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END


    --Cost of Sales
    IF @Option = 10
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [COS]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID

        END

    --Expenses
    IF @Option = 11
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [E]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_Account_Types_ID = 4 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Net Income
    IF @Option = 12
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [NI]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I1_ID = 1 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Long-term debt
    IF @Option = 13
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [LTD]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B2_ID = 40 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Equity and Liabilities
    IF @Option = 14
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [EL]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B1_ID = 2 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                   a.Slu_AW_Months_ID <= @MonthID AND
--                   a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Current Inventory
    IF @Option = 15

--------------------------------------------------------------------------------------
        --> this is INCORRECT. It fetched aggregated values from Closing Stock account
--------------------------------------------------------------------------------------
--         BEGIN
--             SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [CI]
--             FROM AB_GL_Transactions a
--                 INNER JOIN AB_Accounts b
--                     ON a.AB_Accounts_ID = b.AB_Accounts_ID
--                 INNER join Sys_AB_Account_Categories c
--                     ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
--             WHERE c.Sys_AB_B3_ID = 60 AND
--                   dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
-- --                   a.Slu_AW_Months_ID <= @MonthID AND
-- --                   a.Slu_AW_Years_ID <= @YearID AND
--                   a.Slu_AW_Active_ID = 1 AND
--                   a.AB_Transaction_Amount > 0 AND
--                   a.AW_User_Companies_ID = @CompanyID
--         END
--------------------------------------------------------------------------------------

        BEGIN

        --> Get the CURRENT ACCOUNTING PERIOD
            SELECT @CurrentMonth = Slu_AW_Months_ID,
                   @CurrentYear = Slu_AW_Years_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

        --> Get a TEST VALUE of M/E Inventory ID Period Procedure EXISTS
            SELECT @TempMoney = ISNULL(Stock_Valuation, 0)
            FROM AW_Period_Procedures
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  [Month] = @MonthID AND
                  [Year] = @YearID

        --> If no Period Procedure (M/E Inventory) yet done for the CURRENT MONTH
            IF (@TempMoney = 0 OR @TempMoney IS NULL) AND
               @MonthID = @CurrentMonth AND
               @YearID = @CurrentYear

            --> Get the CURRENT Inventory valuation
                BEGIN
                	SELECT ISNULL(SUM(On_Hand * Last_Cost), 0) AS [CI]
                	FROM AP_Products
                    WHERE On_Hand <> 0 AND
                          AW_User_Companies_ID = @CompanyID
                END
            ELSE
            --> Re-fetch the Inventory valuation from the Period Procedure
                BEGIN
                    SELECT ISNULL(Stock_Valuation, 0) AS [CI]
                    FROM AW_Period_Procedures
                    WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                          [Month] = @MonthID AND
                          [Year] = @YearID
                END
        END        


    --Stock on hand now
    IF @Option = 16
        BEGIN
        	SELECT ISNULL(SUM(On_Hand * Last_Cost), 0) AS [SOH]
        	FROM AP_Products
            WHERE On_Hand <> 0 AND
                  AW_User_Companies_ID = @CompanyID
        END

    --Cash
    IF @Option = 17
        BEGIN
            SELECT
                (
                    --CL
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 50 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                            a.Slu_AW_Months_ID <= @MonthID AND
--                            a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                 )
                +
                 (
                    --NCL
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 40 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                            a.Slu_AW_Months_ID <= @MonthID AND
--                            a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                 )
                +
                 (
                    --OE
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 30 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                            a.Slu_AW_Months_ID <= @MonthID AND
--                            a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                 )
                +
                 (
                    --AR
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B3_ID = 70 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                            a.Slu_AW_Months_ID <= @MonthID AND
--                            a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                 )
                +
                 (

                    --CI
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B3_ID = 60 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                            a.Slu_AW_Months_ID <= @MonthID AND
--                            a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AB_Transaction_Amount > 0 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                 )
                +
                 (
                    --NCA
                    ISNULL(
                    (SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0)
                     FROM AB_GL_Transactions a
                         INNER JOIN AB_Accounts b
                             ON a.AB_Accounts_ID = b.AB_Accounts_ID
                         INNER join Sys_AB_Account_Categories c
                             ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                     WHERE c.Sys_AB_B2_ID = 10 AND
                           dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                            a.Slu_AW_Months_ID <= @MonthID AND
--                            a.Slu_AW_Years_ID <= @YearID AND
                           a.Slu_AW_Active_ID = 1 AND
                           a.AW_User_Companies_ID = @CompanyID) , 0)
                ) AS [Cash]
        END

    --Actual Sales
    IF @Option = 18
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [S]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END


    --Actual Cost of Sales
    IF @Option = 19
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [COS]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID

        END

    --Actual Expenses
    IF @Option = 20
        BEGIN
            SELECT ISNULL(SUM(a.AB_Transaction_Amount), 0) AS [E]
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_Account_Types_ID = 4 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END


    --Sales Budget
    IF @Option = 21
        BEGIN
            SELECT ISNULL(SUM(a.Budget_Amount), 0) AS [SB]
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --COS Budget
    IF @Option = 22
        BEGIN
            SELECT ISNULL(SUM(a.Budget_Amount), 0) AS [COSB]
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Expense Budget
    IF @Option = 23
        BEGIN
            SELECT ISNULL(SUM(a.Budget_Amount), 0) AS [EB]
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I3_ID > 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

    --Other Income Budget
    IF @Option = 24
        BEGIN
            SELECT ISNULL(SUM(a.Budget_Amount), 0) AS [OIB]
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I3_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
--                    a.Slu_AW_Months_ID <= @MonthID AND
--                    a.Slu_AW_Years_ID <= @YearID AND
                  a.Slu_AW_Active_ID = 1 AND
                  a.AW_User_Companies_ID = @CompanyID
        END

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_9100
--Purpose       :Manager Console
--Functionality :
--Date          :2002/12/23
--Authors       :TB
--MODS:         :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :01/01/03 - Added option 18 = Last Month Turnover
--              :13/01/03 - Initialize LAST Day-End date if no Day-End exists
--              :06/03/03 - Added Option 19 & 20 Trade Debtors Control total
--              :           and Trade Creditors Control total
--              :30/07/03 - Added Option 21 - Turnover YESTERDAY (Last Day-End)
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--              :07/05/05 - Added option 22, 23, 24 = GL Clearing Account TOTALS
--2004.2.4      :04/06/05 - Added option 25 Daily Summary
--2004.2.7      :02/04/06 - Changed option 7 Stock Valuation to use SysOptions setting
--2004.2.9      :14/04/06 - Replaced vw_AS_Transactions with AS_Transactions in
--              :           options 11 through 16 to improve speed
--2004.3.2      :02/09/06 - Added option 26 V.A.T. Control Account
--2004.3.5      :24/06/07 - Replaced Trade Creditors Control account balance
--              :           with SUM(GL Transactions)
--2004.3.8      :25/05/08 - Added transaction totals in Daily Summary
--              :25/05/08 - Added Inventory Adjustments, GL Inventories Control totals
--              :           and Opening Stock at the Last Customer Month-End
--              :29/05/08 - Added option 30 and 31 GL Trial Balance Total
--2004.3.9      :13/06/08 - Fixed NULL @DayEndTotal if there is ZERO AS_Transactions
--              :           causing a 0 Trade Debtors Control total in @Option = 19
--2004.4.0      :12/07/08 - Added Sales Orders and Open SO in Daily Summary section
--2004.4.1      :03/10/08 - Added Amount <> 0 in @Option 17 Cash Book Unreconciled items
--              :           to not count Cancelled Docs (Amount = 0 AND Recon_Amount = 0)
--              :12/10/08 - Removed GRV-Related and Stock Take-On Inventory Adjustments
--              :13/10/08 - Added new dbo.fn_AW_Get_YearID_From_Year in turnover option 10 and 18
--              :           to extract YearID from YEAR(h.Transaction_Date)
--2004.4.2      :25/10/08 - Added new Standard Cost Inventory Valuation method
--              :01/11/08 - Modified Option 8 Turnover Today added 'h.Day_End IS NULL'
--              :           and removed 'h.Transaction_Date > @LastDayEnd' - AW Silver
--              :09/11/08 - Added Secondary Costing method to Stock Valuation (theoretical now)
--              :29/12/08 - Commented to fetch ONLY OPEN Sales Orders and Job Cards for TODAY.
--              :           Now fetch ALL OPEN Sales Orders and Job Cards
--2004.4.5      :19/06/09 - Replaced using AS_Transactions to using AS_Day_Ends in Option 6, 8 and 21
--              :05/07/09 - Switched sequence in WHERE clause of Option 9 to match new INDEX
--2004.4.7      :26/08/09 - Added Stock-In-Transit Control total
--              :26/08/09 - Added EXCLUDE INTER-COMPANY in Customer and Supplier Age Analysis
--              :           Turnover, and Daily Summary sections
--2004.4.8      :02/11/09 - Added Turnover performance with new @PriorPeriodProcedureDate
--              :02/11/09 - Added Turnover performance replacing fn_AW_Get_YearID_From_Year with new @LastYear 
--              :11/11/09 - Replaced Transaction_Date with Date_Captured in WHERE CLAUSES
--              :           for ALL Turnover queries. Transaction_Date IS NOT INDEXED !!!!
--              :16/07/10 - Modified Option 5 Cash Book Balance (SUM of ALL the company bank accounts)
--              :           to fetch ACTIVE Accounts ONLY
--2004.5.2      :08/07/11 - Modified GL Inventory Controls (SUM of ALL the 'Inventories' Category accounts)
--              :           This is REQUIRED if SPLIT Continuous Inventory is used) (Added 2005.5.2)
--V6.2	RL	2015-06-28	:Option 7 - Rounded results to 2 decimal places
--V6.2	RL	2015-07-23	:Option 7 - Removed Consignment stock when calculating Inventory valuation
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_9100]
    (
        @CompanyID int,
        @Option tinyint,
        @NoInterCo tinyint,
        @MonthID int,
        @YearID int,
    	@M1 tinyint = 0,
    	@Y1 int = 0,
    	@M2 tinyint = 0,
    	@Y2 int = 0,
    	@M3 tinyint = 0,
    	@Y3 int = 0,
    	@M4 tinyint = 0,
    	@Y4 int = 0,
    	@M5 tinyint = 0,
    	@Y5 int = 0,
    	@M6 tinyint = 0,
    	@Y6 int = 0,
    	@M7 tinyint = 0,
    	@Y7 int = 0
    )

AS

SET NOCOUNT ON

    DECLARE @Now datetime,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime,
            @LastDayEnd datetime,
            @LastPeriodProcedureDate datetime,
            @LastPeriodProcedureMonthID tinyint,
            @LastPeriodProcedureYearID int,
            @LastPeriodProcedureStock money,
            @LastPeriodProcedureYear int,
            @PriorPeriodProcedureDate datetime,
            @PrevPeriodProcedureDate datetime,
            @LastMonthID int,
            @LastYearID int,
            @LastYear int,
            @GLControlAccount int,
            @DayEndTotal money,
            @GLAccountTotal money,
            @EndPeriod varchar(6),
            @Quotes int,
            @Jocards int,
            @SalesOrders int,
            @OpenJobs int,
            @OpenSO int,
            @Invoices int,
            @Refunds int,
            @Journals int,
            @QuoteTotal money,
            @JocardTotal money,
            @SalesOrderTotal money,
            @OpenJobTotal money,
            @OpenSOTotal money,
            @InvoiceTotal money,
            @RefundTotal money,
            @JournalTotal money,
            @SumPOSPayment money,
            @SumBOFPayment money,
            @SumEFTPayment money,
            @SumTotalCash money,
            @SumTotalCredit money,
            @SumTotalAmount money,
            @ValuationMethod smallint,
            @ZeroCostOverride smallint,
            @Adjust1 money,
            @Adjust2 money


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @LastPeriodProcedureStock = 0


--> Get the PREVIOUS Calendar YEAR from the @YearID - NEW 2004.4.8
    SELECT @LastYear = Description
    FROM Slu_AW_Years
    WHERE Slu_AW_Years_ID = @YearID - 1



--> Get the LAST Day-End Date - NEW 2004.4.8
	SELECT TOP 1 @LastDayEnd = Day_End
    FROM AS_Day_Ends
    WHERE AW_User_Companies_ID = @companyID
    ORDER BY Day_End DESC

	IF @LastDayEnd IS NULL 
        BEGIN
            SET @LastDayEnd = '1899/12/31 23:59:59'
        END



--> Get the date of the LAST CUSTOMER MONTH-END done
	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date,
                 @LastPeriodProcedureMonthID = [Month],
                 @LastPeriodProcedureYearID = [Year],
                 @LastPeriodProcedureStock = ISNULL(Stock_Valuation, 0)
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
	ORDER BY Month_End_Date DESC

    SELECT @LastPeriodProcedureYear = [Description]
    FROM Slu_AW_Years
    WHERE Slu_AW_Years_ID = @LastPeriodProcedureYearID


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @LastPeriodProcedureDate IS NULL 
        BEGIN
    		SET @LastPeriodProcedureDate = '1900/01/01'
        --> because UI increments month by 1
            SET @LastPeriodProcedureMonthID = MONTH(getdate()) - 1
            SET @LastPeriodProcedureYear = YEAR(getdate())

            IF @LastPeriodProcedureMonthID < 0
                SET @LastPeriodProcedureYear = @LastPeriodProcedureYear - 1
            
            SELECT @LastPeriodProcedureYearID = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE [Description] = @LastPeriodProcedureYear
        END


--> Get the date of the PRIOR CUSTOMER MONTH-END done
	SELECT TOP 1 @PriorPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          Month_End_Date <> @LastPeriodProcedureDate
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PriorPeriodProcedureDate IS NULL 
        BEGIN
    		SET @PriorPeriodProcedureDate = '1899/12/31'
        END


--> Get the date of the PREVIOUS CUSTOMER MONTH-END done
	SELECT TOP 1 @PrevPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          Month_End_Date <> @LastPeriodProcedureDate AND
          Month_End_Date <> @PriorPeriodProcedureDate
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PrevPeriodProcedureDate IS NULL 
        BEGIN
    		SET @PrevPeriodProcedureDate = '1899/12/31'
        END


    --> Get Primary Costing method
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID



    --> Get Secondary Costing method (Zero Primary Cost override)
    SELECT @ZeroCostOverride = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optZeroCostOverride' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID



    --Customer Ageing Totals
    IF @Option = 1
    	BEGIN

        --> Midnight tonight
            SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))
        
            EXEC sp_AW_Period_Procedures_Select
                     @Now,
                     @D1 OUTPUT,
                     @D2 OUTPUT,
                     @D3 OUTPUT,
                     @D4 OUTPUT,
                     @D5 OUTPUT,
                     @D6 OUTPUT,
                     @D7 OUTPUT,
                     1,
                     @CompanyID

            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
            		SELECT
            			SUM(Payment) AS [Payment],
            			SUM(Amount) AS [Amount],
            			SUM([Current]) AS [Current],
            			SUM([30 Days]) AS [30 Days],
            			SUM([60 Days]) AS [60 Days],
            			SUM([90 Days]) AS [90 Days],
            			SUM([120 Days]) AS [120 Days],
            			SUM([150 Days]) AS [150 Days],
            			SUM([180+ Days]) AS [180+ Days]
             		FROM dbo.fn_AC_Customer_Total_Ageing_No_InterCo
                        ( @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
                END
            ELSE                    --All Customers
                BEGIN 
        		    SELECT
            			SUM(Payment) AS [Payment],
            			SUM(Amount) AS [Amount],
            			SUM([Current]) AS [Current],
            			SUM([30 Days]) AS [30 Days],
            			SUM([60 Days]) AS [60 Days],
            			SUM([90 Days]) AS [90 Days],
            			SUM([120 Days]) AS [120 Days],
            			SUM([150 Days]) AS [150 Days],
            			SUM([180+ Days]) AS [180+ Days]
             		FROM dbo.fn_AC_Customer_Total_Ageing
                        ( @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 )
                END
    	END

    --Supplier Ageing Totals
    IF @Option = 2
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
            			SUM(Payment) AS [Payment],
            			SUM(Amount) AS [Amount],
            			SUM([Current]) AS [Current],
            			SUM([30 Days]) AS [30 Days],
            			SUM([60 Days]) AS [60 Days],
            			SUM([90 Days]) AS [90 Days],
            			SUM([120 Days]) AS [120 Days],
            			SUM([150 Days]) AS [150 Days],
            			SUM([180+ Days]) AS [180+ Days]
                    FROM dbo.fn_AO_Supplier_Total_Ageing_No_InterCo
                            (
                            	@M1, @Y1,
                            	@M2, @Y2,
                            	@M3, @Y3,
                            	@M4, @Y4,
                            	@M5, @Y5,
                            	@M6, @Y6,
                            	@M7, @Y7
                            ) 
                END
            ELSE
                BEGIN
                    SELECT
            			SUM(Payment) AS [Payment],
            			SUM(Amount) AS [Amount],
            			SUM([Current]) AS [Current],
            			SUM([30 Days]) AS [30 Days],
            			SUM([60 Days]) AS [60 Days],
            			SUM([90 Days]) AS [90 Days],
            			SUM([120 Days]) AS [120 Days],
            			SUM([150 Days]) AS [150 Days],
            			SUM([180+ Days]) AS [180+ Days]
                    FROM dbo.fn_AO_Supplier_Total_Ageing
                            (
                            	@M1, @Y1,
                            	@M2, @Y2,
                            	@M3, @Y3,
                            	@M4, @Y4,
                            	@M5, @Y5,
                            	@M6, @Y6,
                            	@M7, @Y7
                            ) 
                END
		END

    --Current Assets
    ELSE
    IF @Option = 3
        BEGIN
            SELECT SUM(ISNULL(b.AB_Account_Balance, 0)) AS [CA]
            FROM AB_Accounts b
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B2_ID = 20 AND
                  b.AW_User_Companies_ID = @CompanyID
        END

    --Current Liabilities
    ELSE
    IF @Option = 4
        BEGIN
            SELECT SUM(ISNULL(b.AB_Account_Balance, 0)) AS [CL]
            FROM AB_Accounts b
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_B2_ID = 50 AND
                  b.AW_User_Companies_ID = @CompanyID
        END

    --Cash Book Balance (SUM of ALL the company bank accounts)
    --Added  2004.4.8 - 16 JUL 2010 - ACTIVE Accounts ONLY
    ELSE
    IF @Option = 5
        BEGIN
            SELECT SUM(ISNULL(a.AB_Account_Balance, 0)) AS [CB]
            FROM AB_Accounts a
                LEFT join AW_Company_Banks b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
            WHERE b.AW_User_Companies_ID = @CompanyID AND
                  b.Slu_AW_Active_ID = 1

        END

    --Daily Takings (since last Day End)
    ELSE
    IF @Option = 6
        BEGIN
    		SELECT SUM(ISNULL(Total_Amount, 0)) as [Takings]
    		FROM AS_Transactions
    		WHERE AW_User_Companies_ID = @CompanyID AND
    			  Cashed_Up is null AND 
    			  Sys_AW_Transaction_Types_ID = 7 AND    -- Payments
                  Date_Captured > @LastDayEnd
        END

    --Stock Valuation (theoretical now)
    ELSE
    IF @Option = 7
        BEGIN
            --> NEW 2004.4.2 - Using Secondary Costing method
            --> NEW 2015.6.2 - Exclude Consignment Stock
            IF @ValuationMethod = 0
                BEGIN
                    IF @ZeroCostOverride = 0
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                    ELSE
                    IF @ZeroCostOverride = 1
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                    ELSE
                    IF @ZeroCostOverride = 2
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                END
            ELSE
            IF @ValuationMethod = 1
                BEGIN
                    IF @ZeroCostOverride = 0
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                    ELSE
                    IF @ZeroCostOverride = 1
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                    ELSE
                    IF @ZeroCostOverride = 2
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                END
            ELSE
            IF @ValuationMethod = 2
                BEGIN
                    IF @ZeroCostOverride = 0
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Average_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                    ELSE
                    IF @ZeroCostOverride = 1
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Last_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                    ELSE
                    IF @ZeroCostOverride = 2
                        BEGIN
                            SELECT SUM(CASE WHEN ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
                                            THEN ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            ELSE ROUND(ISNULL(Standard_Cost, 0) * ( ( ISNULL(On_Hand, 0) + dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID) ) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
                                            END) AS [Stock]
                        	FROM AP_Products
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                  On_Hand <> 0
                        END
                END
        END

    --Turnover Today ( > Last Day-End)
    ELSE
    IF @Option = 8
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%],
                        @LastDayEnd AS [LastDayEnd]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                           h.Day_End IS NULL AND
                           h.AW_User_Companies_ID = @CompanyID AND
                           c.Sys_AC_Account_Types_ID <> 3
                END
            ELSE
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%],
                        @LastDayEnd AS [LastDayEnd]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                           h.Day_End IS NULL AND
                           h.AW_User_Companies_ID = @CompanyID
                END
        END

    --Turnover this month
    ELSE
    IF @Option = 9
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%],
                        @LastPeriodProcedureMonthID AS [LastPPMonth],
                        @LastPeriodProcedureYear AS [LastPPYear],
                        @LastPeriodProcedureDate AS [LastPPDate]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
            		WHERE h.Date_Captured > @LastPeriodProcedureDate AND
                         (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                          h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                          h.AW_User_Companies_ID = @CompanyID AND
                          c.Sys_AC_Account_Types_ID <> 3
                END
            ELSE
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%],
                        @LastPeriodProcedureMonthID AS [LastPPMonth],
                        @LastPeriodProcedureYear AS [LastPPYear],
                        @LastPeriodProcedureDate AS [LastPPDate]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
            		WHERE h.Date_Captured > @LastPeriodProcedureDate AND
                         (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                          h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                          h.AW_User_Companies_ID = @CompanyID
                END
        END

    --Turnover this month LAST YEAR
    ELSE
    IF @Option = 10
        BEGIN

            SET @LastYearID = @YearID - 1

            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                           MONTH(h.Date_Captured) = @MonthID AND
                           YEAR(h.Date_Captured) = @LastYear AND
--                           dbo.fn_AW_Get_YearID_From_Year(YEAR(h.Date_Captured)) = @LastYearID AND
                           h.AW_User_Companies_ID = @CompanyID AND
                           c.Sys_AC_Account_Types_ID <> 3
                END
            ELSE
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                           MONTH(h.Date_Captured) = @MonthID AND
                           YEAR(h.Date_Captured) = @LastYear AND
--                           dbo.fn_AW_Get_YearID_From_Year(YEAR(h.Date_Captured)) = @LastYearID AND
                           h.AW_User_Companies_ID = @CompanyID
                END
        END


    --CUSTOMER UNALLOCATED: Payments Customers
    ELSE
    IF @Option = 11
        BEGIN
        	SELECT COUNT(DISTINCT AC_Customers_ID) AS [Customers]
        	FROM AS_Transactions
        	WHERE (Sys_AW_Transaction_Types_ID = 7 OR
                   Sys_AW_Transaction_Types_ID = 21 OR
                   Sys_AW_Transaction_Types_ID = 22) AND
                  (Total_Amount + Payment_Amount <> 0) AND
                   AW_User_Companies_ID = @CompanyID
        END

    --CUSTOMER UNALLOCATED: Payments Transactions
    ELSE
    IF @Option = 12
        BEGIN
        	SELECT COUNT(*) AS [Count]
        	FROM AS_Transactions
        	WHERE (Sys_AW_Transaction_Types_ID = 7 OR
                   Sys_AW_Transaction_Types_ID = 21 OR
                   Sys_AW_Transaction_Types_ID = 22) AND
                 (Total_Amount + Payment_Amount <> 0) AND
                  AW_User_Companies_ID = @CompanyID
        END

    --CUSTOMER UNALLOCATED: Journals Customers
    ELSE
    IF @Option = 13
        BEGIN
        	SELECT COUNT(DISTINCT AC_Customers_ID) AS [Customers]
        	FROM AS_Transactions
        	WHERE Sys_AW_Transaction_Types_ID = 5 AND
                 (Total_Amount + Payment_Amount <> 0) AND
                  AW_User_Companies_ID = @CompanyID
        END


    --CUSTOMER UNALLOCATED: Journals Transactions
    ELSE
    IF @Option = 14
        BEGIN
        	SELECT COUNT(*) AS [Count]
        	FROM AS_Transactions
        	WHERE Sys_AW_Transaction_Types_ID = 5 AND
                 (Total_Amount + Payment_Amount <> 0) AND
                  AW_User_Companies_ID = @CompanyID
        END


    --CUSTOMER UNALLOCATED: Credit Note Customers
    ELSE
    IF @Option = 15
        BEGIN
        	SELECT COUNT(DISTINCT AC_Customers_ID) AS [Customers]
        	FROM AS_Transactions
        	WHERE Sys_AW_Transaction_Types_ID = 4 AND
                 (Total_Amount + Payment_Amount <> 0) AND
                  AW_User_Companies_ID = @CompanyID
        END


    --CUSTOMER UNALLOCATED: Credit Note Transactions
    ELSE
    IF @Option = 16
        BEGIN
        	SELECT COUNT(*) AS [Count]
        	FROM AS_Transactions
        	WHERE Sys_AW_Transaction_Types_ID = 4 AND
                 (Total_Amount + Payment_Amount <> 0) AND
                  AW_User_Companies_ID = @CompanyID
        END


    --Cash Book Unreconciled items
    ELSE
    IF @Option = 17
        BEGIN
            --> 2004.4.1 - Added Amount <> 0 to not count items Amount = 0 AND Recon_Amount = 0 (Cancelled docs)
        	SELECT COUNT(*) AS [Count]
        	FROM AB_Cash_Book_Transactions
        	WHERE (Recon_Amount = 0 OR
                   Recon_Amount IS NULL) AND
                   Amount <> 0 AND
                   AW_User_Companies_ID = @CompanyID
        END


    --Turnover LAST month
    ELSE
    IF @Option = 18
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                          (h.Date_Captured >= @PriorPeriodProcedureDate AND
                           h.Date_Captured <= @LastPeriodProcedureDate) AND
                           h.AW_User_Companies_ID = @CompanyID AND
                           c.Sys_AC_Account_Types_ID <> 3
                END
            ELSE
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                          (h.Date_Captured >= @PriorPeriodProcedureDate AND
                           h.Date_Captured <= @LastPeriodProcedureDate) AND
                           h.AW_User_Companies_ID = @CompanyID
                END
        END


    --TRADE DEBTORS GL CONTROL
    ELSE
    IF @Option = 19
        BEGIN
            SELECT @DayEndTotal = ISNULL(SUM(ISNULL(Total_Amount, 0)), 0) + ISNULL(SUM(ISNULL(Payment_Amount, 0)), 0)
        	FROM AS_Transactions 
            WHERE Day_End IS NULL AND
                 (Sys_AW_Transaction_Types_ID = 3 OR       --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR       --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR       --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR       --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR      --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR      --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR      --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)        --EFT Payment

        --> DEBTORS GL CONTROL a/c
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 101 AND   --Trade Debtors Control
                  AW_User_Companies_ID = @CompanyID

            SELECT @GLAccountTotal = ISNULL(AB_Account_Balance, 0)
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @GLControlAccount

            SELECT ROUND(ISNULL(@GLAccountTotal, 0) + ISNULL(@DayEndTotal, 0), 2)

        END


    --TRADE CREDITORS GL CONTROL
    ELSE
    IF @Option = 20
        BEGIN

        --> DEBTORS GL CONTROL a/c
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 201 AND   --Trade Creditors Control
                  AW_User_Companies_ID = @CompanyID


            SELECT SUM(ISNULL(AB_Transaction_Amount, 0))
            FROM AB_GL_Transactions
            WHERE AB_Accounts_ID = @GLControlAccount

        END


    --Turnover Yesterday (= Last Day-End)
    ELSE
    IF @Option = 21
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%],
                        @LastDayEnd AS [LastDayEnd]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                           h.Day_End = @LastDayEnd AND
                           h.AW_User_Companies_ID = @CompanyID AND
                           c.Sys_AC_Account_Types_ID <> 3
                END
            ELSE
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%],
                        @LastDayEnd AS [LastDayEnd]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                           h.Day_End = @LastDayEnd AND
                           h.AW_User_Companies_ID = @CompanyID
                END
        END


    --GL CASH CONTROL
    ELSE
    IF @Option = 22
        BEGIN
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 206 AND   --Cash Control Account
                  AW_User_Companies_ID = @CompanyID

            SELECT ISNULL(AB_Account_Balance, 0)
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @GLControlAccount
        END


    --GL TRADE DEBTORS PAYMENT CLEARING
    ELSE
    IF @Option = 23
        BEGIN
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 105 AND   --Trade Debtors Payment Clearing
                  AW_User_Companies_ID = @CompanyID

            SELECT ISNULL(AB_Account_Balance, 0)
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @GLControlAccount
        END


    --GL TRADE CREDITORS PAYMENT CLEARING
    ELSE
    IF @Option = 24
        BEGIN
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 207 AND   --Trade Creditors Payment Clearing
                  AW_User_Companies_ID = @CompanyID

            SELECT ISNULL(AB_Account_Balance, 0)
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @GLControlAccount
        END


    --DAILY SUMMARY
    ELSE
    IF @Option = 25
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
            		SELECT @Quotes = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 1 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @Jocards = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 2 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @SalesOrders = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 16 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @OpenJobs = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Sys_AW_Transaction_Types_ID = 2 AND
                                                    h.Slu_AW_Active_ID = 1 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),

                           @Invoices = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 3 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @Refunds = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 4 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @Journals = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 5 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @OpenSO = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Sys_AW_Transaction_Types_ID = 16 AND
                                                    h.Slu_AW_Active_ID = 1 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),

                           @QuoteTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 1 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @JocardTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 2 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),

                           @SalesOrderTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 16 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @OpenJobTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Sys_AW_Transaction_Types_ID = 2 AND
                                                    h.Slu_AW_Active_ID = 1 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),

                           @InvoiceTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 3 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @RefundTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 4 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @JournalTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 5 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @OpenSOTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Sys_AW_Transaction_Types_ID = 16 AND
                                                    h.Slu_AW_Active_ID = 1 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),

                           @SumPOSPayment = ( SELECT ISNULL(SUM(Payment_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 7 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @SumBOFPayment = ( SELECT ISNULL(SUM(Payment_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 21 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),
                           @SumEFTPayment = ( SELECT ISNULL(SUM(Payment_Amount), 0)
                                              FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                              WHERE h.AW_User_Companies_ID = @companyID AND
                                                    h.Day_End IS NULL AND
                                                    h.Sys_AW_Transaction_Types_ID = 22 AND
                                                    c.Sys_AC_Account_Types_ID <> 3 ),

                           @SumTotalCash = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                             FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                             WHERE h.AW_User_Companies_ID = @companyID AND
                                                   ISNULL(h.Payment_Amount, 0) <> 0 AND
                                                   h.Day_End IS NULL AND
                                                  (h.Sys_AW_Transaction_Types_ID = 3  OR
                                                   h.Sys_AW_Transaction_Types_ID = 4) AND
                                                   c.Sys_AC_Account_Types_ID <> 3 ),
                           @SumTotalCredit = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                               FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                               WHERE h.AW_User_Companies_ID = @companyID AND
                                                     ISNULL(h.Payment_Amount, 0) = 0 AND
                                                     h.Day_End IS NULL AND
                                                    (h.Sys_AW_Transaction_Types_ID = 3  OR
                                                     h.Sys_AW_Transaction_Types_ID = 4) AND
                                                     c.Sys_AC_Account_Types_ID <> 3 ),
                           @SumTotalAmount = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                               FROM AS_Transactions h
                                                INNER JOIN AC_Customers c
                                                    ON h.AC_Customers_ID = c.AC_Customers_ID
                                               WHERE h.AW_User_Companies_ID = @companyID AND
                                                     h.Day_End IS NULL AND
                                                    (h.Sys_AW_Transaction_Types_ID = 3  OR
                                                     h.Sys_AW_Transaction_Types_ID = 4) AND
                                                     c.Sys_AC_Account_Types_ID <> 3 )
            		FROM AS_Transactions h
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
                    WHERE h.AW_User_Companies_ID = @companyID AND
                          h.Day_End IS NULL
                END
            ELSE                        --ALL Customers
                BEGIN
            		SELECT @Quotes = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 1 ),
                           @Jocards = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 2 ),
                           @SalesOrders = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 16 ),
                           @OpenJobs = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Sys_AW_Transaction_Types_ID = 2 AND
                                                    Slu_AW_Active_ID = 1 ),

                           @Invoices = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 3 ),
                           @Refunds = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 4 ),
                           @Journals = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 5 ),
                           @OpenSO = ( SELECT ISNULL(COUNT(*), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Sys_AW_Transaction_Types_ID = 16 AND
                                                    Slu_AW_Active_ID = 1 ),

                           @QuoteTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 1 ),
                           @JocardTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 2 ),

                           @SalesOrderTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 16 ),
                           @OpenJobTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Sys_AW_Transaction_Types_ID = 2 AND
                                                    Slu_AW_Active_ID = 1 ),

                           @InvoiceTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 3 ),
                           @RefundTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 4 ),
                           @JournalTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Day_End IS NULL AND
                                                    Sys_AW_Transaction_Types_ID = 5 ),
                           @OpenSOTotal = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                    Sys_AW_Transaction_Types_ID = 16 AND
                                                    Slu_AW_Active_ID = 1 ),

                           @SumPOSPayment = ( SELECT ISNULL(SUM(Payment_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                       Day_End IS NULL AND
                                                       Sys_AW_Transaction_Types_ID = 7 ),
                           @SumBOFPayment = ( SELECT ISNULL(SUM(Payment_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                       Day_End IS NULL AND
                                                       Sys_AW_Transaction_Types_ID = 21 ),
                           @SumEFTPayment = ( SELECT ISNULL(SUM(Payment_Amount), 0)
                                              FROM AS_Transactions
                                              WHERE AW_User_Companies_ID = @companyID AND
                                                       Day_End IS NULL AND
                                                       Sys_AW_Transaction_Types_ID = 22 ),

                           @SumTotalCash = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                             FROM AS_Transactions
                                             WHERE AW_User_Companies_ID = @companyID AND
                                                   ISNULL(Payment_Amount, 0) <> 0 AND
                                                   Day_End IS NULL AND
                                                  (Sys_AW_Transaction_Types_ID = 3  OR
                                                   Sys_AW_Transaction_Types_ID = 4) ),
                           @SumTotalCredit = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                               FROM AS_Transactions
                                               WHERE AW_User_Companies_ID = @companyID AND
                                                     ISNULL(Payment_Amount, 0) = 0 AND
                                                     Day_End IS NULL AND
                                                    (Sys_AW_Transaction_Types_ID = 3  OR
                                                     Sys_AW_Transaction_Types_ID = 4) ),
                           @SumTotalAmount = ( SELECT ISNULL(SUM(Total_Amount), 0)
                                               FROM AS_Transactions
                                               WHERE AW_User_Companies_ID = @companyID AND
                                                     Day_End IS NULL AND
                                                    (Sys_AW_Transaction_Types_ID = 3  OR
                                                     Sys_AW_Transaction_Types_ID = 4) )
            		FROM AS_Transactions
                    WHERE AW_User_Companies_ID = @companyID AND
                          Day_End IS NULL
                END


            SELECT @Quotes AS [Quotes],
                   @Jocards AS [Jocards],
                   @SalesOrders AS [SalesOrders],
                   @OpenJobs AS [OpenJobs],

                   @Invoices AS [Invoices],
                   @Refunds AS [Refunds],
                   @Journals AS [Journals],
                   @OpenSO AS [OpenSO],

                   @QuoteTotal AS [QuoteTotal],
                   @JocardTotal AS [JocardTotal],
                   @SalesOrderTotal AS [SOTotal],
                   @OpenJobTotal AS [OpenJobTotal],

                   @InvoiceTotal AS [InvoiceTotal],
                   @RefundTotal AS [RefundTotal],
                   @JournalTotal AS [JournalTotal],
                   @OpenSOTotal AS [OpenSOTotal],

                   @SumPOSPayment AS [POSPayment],
                   @SumBOFPayment AS [BOFPayment],
                   @SumEFTPayment AS [EFTPayment],

                   @SumTotalCash AS [TotalCash],
                   @SumTotalCredit AS [TotalCredit],
                   @SumTotalAmount AS [TotalAmount]

        END


    --GL V.A.T. CONTROL CONTROL
    ELSE
    IF @Option = 26
        BEGIN
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 401 AND   --V.A.T. Control Account
                  AW_User_Companies_ID = @CompanyID

            SELECT ISNULL(AB_Account_Balance, 0)
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @GLControlAccount
        END


    --STOCK ADJUSTMENTS
    ELSE
    IF @Option = 27
        BEGIN
            IF @ValuationMethod = 0
                BEGIN
            		SELECT @Adjust1 = SUM((ISNULL(New_Average_Cost, 0) * ISNULL(New_On_Hand, 0)) - (ISNULL(Previous_Average_Cost, 0) * ISNULL(Previous_On_Hand, 0)))
                                        FROM AP_Inventory_Adjustments
                                        WHERE AW_User_Companies_ID = @companyID AND
                                              Sys_AP_Adjustment_Types_ID = 1 AND
                                              Date_Captured >= @LastPeriodProcedureDate

            		SELECT @Adjust2 = SUM((ISNULL(New_Average_Cost, 0) * ISNULL(New_On_Hand, 0)) - (ISNULL(Previous_Average_Cost, 0) * ISNULL(Previous_On_Hand, 0)))
                                        FROM AP_Inventory_Adjustments
                                        WHERE AW_User_Companies_ID = @companyID AND
                                              Sys_AP_Adjustment_Types_ID = 3 AND
                                              Date_Captured >= @LastPeriodProcedureDate
                END
            ELSE
            IF @ValuationMethod = 1
                BEGIN
            		SELECT @Adjust1 = SUM((ISNULL(New_Last_Cost, 0) * ISNULL(New_On_Hand, 0)) - (ISNULL(Previous_Last_Cost, 0) * ISNULL(Previous_On_Hand, 0)))
                                        FROM AP_Inventory_Adjustments
                                        WHERE AW_User_Companies_ID = @companyID AND
                                              Sys_AP_Adjustment_Types_ID = 1 AND
                                              Date_Captured >= @LastPeriodProcedureDate

            		SELECT @Adjust2 = SUM((ISNULL(New_Last_Cost, 0) * ISNULL(New_On_Hand, 0)) - (ISNULL(Previous_Last_Cost, 0) * ISNULL(Previous_On_Hand, 0)))
                                        FROM AP_Inventory_Adjustments
                                        WHERE AW_User_Companies_ID = @companyID AND
                                              Sys_AP_Adjustment_Types_ID = 3 AND
                                              Date_Captured >= @LastPeriodProcedureDate
                END

            SELECT @Adjust1 AS [Adjust1],
                   @Adjust2 AS [Adjust2]

        END



    --GL Inventory Control (SUM of ALL the Inventories Category accounts)
--     ELSE
--     IF @Option = 28
--         BEGIN
--             SELECT SUM(ISNULL(AB_Account_Balance, 0))
--             FROM AB_Accounts
--             WHERE Sys_AB_Account_Categories_ID = 7 AND
--                   AW_User_Companies_ID = @companyID
--         END


    --GL Inventory Control        (Commented 2005.5.2)
--     ELSE
--     IF @Option = 28
--         BEGIN
-- 			SELECT @GLControlAccount = AB_Accounts_ID
--             FROM AB_Control_Accounts
--             WHERE Control_Number = 601 AND
--                   AW_User_Companies_ID = @CompanyID
-- 
--             SELECT SUM(ISNULL(AB_Transaction_Amount, 0))
--             FROM AB_GL_Transactions
--             WHERE AB_Accounts_ID = @GLControlAccount
--         END

    --GL Inventory Controls (SUM of ALL the 'Inventories' Category accounts)
    --    This is REQUIRED if SPLIT Continuous Inventory is used) (Added 2005.5.2)
    ELSE
    IF @Option = 28
        BEGIN
            SELECT SUM(ISNULL(t.AB_Transaction_Amount, 0))
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @companyID AND
                  g.Sys_AB_Account_Categories_ID = 7
        END


    --Stock Valuation at Last Customer Month-End
    ELSE
    IF @Option = 29
        BEGIN
            SELECT @LastPeriodProcedureStock
        END


    --GL Trial Balance - GL Transactions Total
    ELSE
    IF @Option = 30
        BEGIN
            SELECT SUM(ISNULL(AB_Transaction_Amount, 0))
            FROM AB_GL_Transactions
            WHERE AW_User_Companies_ID = @companyID
        END


    --GL Trial Balance - GL Accounts Total
    ELSE
    IF @Option = 31
        BEGIN
            SELECT SUM(ISNULL(AB_Account_Balance, 0))
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @companyID
        END


    --GL Stock-In-Transit Control
    ELSE
    IF @Option = 32
        BEGIN
			SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 602 AND
                  AW_User_Companies_ID = @CompanyID

            SELECT SUM(ISNULL(AB_Transaction_Amount, 0))
            FROM AB_GL_Transactions
            WHERE AB_Accounts_ID = @GLControlAccount
        END

    --Turnover PREVIOUS month
    ELSE
    IF @Option = 33
        BEGIN
            IF @NoInterCo = 1        --Exclude Inter-Company Customers
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                          (h.Date_Captured >= @PrevPeriodProcedureDate AND
                           h.Date_Captured <= @PriorPeriodProcedureDate) AND
                           h.AW_User_Companies_ID = @CompanyID AND
                           c.Sys_AC_Account_Types_ID <> 3
                END
            ELSE
                BEGIN
                    SELECT
                        ISNULL(SUM(d.Quantity), 0) AS [Qty],
                        ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                        ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                        ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                        ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                        ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                             ELSE 0.00
                             END AS [StdGP%],
                        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                             ELSE 0.00
                             END AS [ActGP%]
                    FROM AS_Transaction_Details d
                        INNER JOIN AS_Transactions h
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
            		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                           h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                          (h.Date_Captured >= @PrevPeriodProcedureDate AND
                           h.Date_Captured <= @PriorPeriodProcedureDate) AND
                           h.AW_User_Companies_ID = @CompanyID
                END
        END
    --Consignment Inventory Valuation
    ELSE
    IF @Option = 34
        BEGIN
            SELECT SUM(d.Qty_Left * d.Unit_Price) AS [Consignment]
			FROM AO_GRV m
				INNER JOIN AO_GRV_Details d
					ON m.AO_GRV_ID = d.AO_GRV_ID
			WHERE m.AW_User_Companies_ID = @CompanyID
			AND m.Sys_AW_Transaction_Types_ID IN (31,32,33,34,35)
			AND d.Qty_Left <> 0
        END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



-------------------------------------------------------------------------------
--Description   :sp_AB_9200
--Purpose       :Cash Flow Forecast
--Date          :2010/06/19
--Authors       :TB
--MODS:
-------------------------------------------------------------------------------


CREATE             PROCEDURE [dbo].[sp_AB_9200]
    (
        @CompanyID int,
        @Option tinyint,
        @ExcludeInterCo tinyint,
        @MonthID int,
        @YearID int
    )

AS

SET NOCOUNT ON


    DECLARE @Now datetime,
            @EndPeriod varchar(6),
            @StartPeriod varchar(6),
            @CreditAccount tinyint,
            @LastPeriodProcedureDate datetime,
            @PriorPeriodProcedureDate datetime,
            @PrevPeriodProcedureDate datetime,
            @Opening money,
            @Receipts money,
            @Payments money,
            @MonthNo datetime,
            @YearNo datetime,
            @LastMonthID int,
            @LastYearID int


    --> Midnight tonight
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))


    SET @LastMonthID = @MonthID - 1
    SET @LastYearID = @YearID

    IF @LastMonthID = 0
        BEGIN
            SET @LastMonthID = 12
            SET @LastYearID = @LastYearID - 1
        END

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@LastMonthID, @LastYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @CreditAccount = 0

    -------------------------------------------------------------------------------
    --> Get Customer Account Type setting to determine credit status
    -------------------------------------------------------------------------------
    SELECT @CreditAccount = CONVERT(tinyint, ISNULL(Control_Value, '0'))
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkCreditAccountType' AND
          AW_User_Companies_ID = @CompanyID


    -------------------------------------------------------------------------------
    --> Get the date of the LAST CUSTOMER MONTH-END done
    -------------------------------------------------------------------------------
	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @LastPeriodProcedureDate IS NULL 
        BEGIN
    		SET @LastPeriodProcedureDate = '1900/01/01'
        END

    -------------------------------------------------------------------------------
    --> Get the date of the PRIOR CUSTOMER MONTH-END done
    -------------------------------------------------------------------------------
	SELECT TOP 1 @PriorPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          Month_End_Date <> @LastPeriodProcedureDate
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PriorPeriodProcedureDate IS NULL 
        BEGIN
    		SET @PriorPeriodProcedureDate = '1900/01/01'
        END

    -------------------------------------------------------------------------------
    --> Get the date of the PREVIOUS CUSTOMER MONTH-END done
    -------------------------------------------------------------------------------
	SELECT TOP 1 @PrevPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          Month_End_Date <> @LastPeriodProcedureDate AND
          Month_End_Date <> @PriorPeriodProcedureDate
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PrevPeriodProcedureDate IS NULL 
        BEGIN
    		SET @PrevPeriodProcedureDate = '1900/01/01'
        END


    -------------------------------------------------------------------------------
    -- PROCEDURES
    -------------------------------------------------------------------------------


    --> LIST of ALL the CASH or OVERDRAFT Accounts - as at LAST MONTH END)
    ----------> Use: CASH ON HAND (beginning of month)
    IF @Option = 1
        BEGIN
            SELECT t.AB_Accounts_ID AS [GLID],
                   MAX(g.Description) AS [GLAccount],
                   ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [Balance]
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @StartPeriod
            GROUP BY t.AB_Accounts_ID
            ORDER BY [GLAccount]
        END


    --> LIST CB Receipts - GL Account Detail
    ----------> Use: CASH RECEIPTS (CURRENT month)
    ELSE
    IF @Option = 2
        BEGIN
            SELECT d.AB_Accounts_ID AS [GLID],
                   g.Description AS [GLAccount],
                   ISNULL(SUM(d.Amount), 0) AS [CBReceipt]
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) < 0
            GROUP BY d.AB_Accounts_ID, g.Description
            ORDER BY [GLAccount]
        END


    --> LIST CB Payments - GL Account Detail
    ----------> Use: CASH PAID OUT (CURRENT month)
    ELSE
    IF @Option = 3
        BEGIN
            SELECT d.AB_Accounts_ID AS [GLID],
                   g.Description AS [GLAccount],
                   ISNULL(SUM(d.Amount), 0) AS [CBPayment]
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
--                  (g.Sys_AB_Account_Categories_ID <> 10 AND          -- Cash and Cash Equivalents
--                   g.Sys_AB_Account_Categories_ID <> 52) AND         -- Bank Overdraft
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) >= 0
            GROUP BY d.AB_Accounts_ID, g.Description
            ORDER BY [GLAccount]
        END


    --> UNION of OPTION 1 to 3
    ----------> Use: CASH POSITION (end of month)
    ELSE
    IF @Option = 4
        BEGIN
            SELECT @Opening = ISNULL(SUM(t.AB_Transaction_Amount), 0)
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @StartPeriod

            SELECT @Receipts = ISNULL(SUM(d.Amount), 0)
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) < 0

            SELECT @Payments = ISNULL(SUM(d.Amount), 0)
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
--                  (g.Sys_AB_Account_Categories_ID <> 10 AND          -- Cash and Cash Equivalents
--                   g.Sys_AB_Account_Categories_ID <> 52) AND         -- Bank Overdraft
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) >= 0


-- PRINT CONVERT(varchar(30), @Opening)
-- PRINT CONVERT(varchar(30), @Receipts)
-- PRINT CONVERT(varchar(30), @Payments)
-- PRINT CONVERT(varchar(30), @Opening + @Receipts + @Payments)


            SELECT @Opening + @Receipts + @Payments AS [Closing]
        END



    --> LIST of ALL the CASH or OVERDRAFT Accounts - as at Now)
    ----------> Use: CASH ON HAND (beginning of month)
    IF @Option = 5
        BEGIN
            SELECT t.AB_Accounts_ID AS [GLID],
                   MAX(g.Description) AS [GLAccount],
                   ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [Balance]
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
            GROUP BY t.AB_Accounts_ID
            ORDER BY [GLAccount]
        END


    --> TOTAL of ALL the CASH or OVERDRAFT Accounts - Now)
    IF @Option = 6
        BEGIN
            SELECT SUM(ISNULL(AB_Account_Balance, 0)) AS [Cash]
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  Sys_AB_Account_Categories_ID = 52)          -- Bank Overdraft
        END


    --> LIST of ALL the CASH or OVERDRAFT Accounts - Now)
    IF @Option = 7
        BEGIN
            SELECT AB_Accounts_ID AS [GLID],
                   Description AS [GLAccount],
                   ISNULL(AB_Account_Balance, 0) AS [Balance]
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  Sys_AB_Account_Categories_ID = 52)          -- Bank Overdraft
            ORDER BY [GLAccount]
        END


    --> CASH Sales - Last Month
    ELSE
    IF @Option = 8
        BEGIN
            IF @CreditAccount = 1        --Using Account Type setting
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [CashSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                          c.Sys_AC_Account_Types_ID = 1 AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
            ELSE                         --Using Credit Limit setting
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [CashSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                          c.Credit_Limit = 0 AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
        END


    --> TOTAL Sales - Last Month
    ELSE
    IF @Option = 9
        BEGIN
            IF @ExcludeInterCo = 1            -- EXCLUDE Inter-Co
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [TotalSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                          c.Sys_AC_Account_Types_ID <> 3 AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
            ELSE                              -- INCLUDE Inter-Co
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [TotalSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
        END


    --> TOTAL CB Receipts
    ELSE
    IF @Option = 10
        BEGIN
            SELECT ISNULL(SUM(Amount), 0) AS [CBReceipts]
            FROM AB_Cash_Book_Transactions
            WHERE AW_User_Companies_ID = @companyID AND
                  Slu_AW_Months_ID = @MonthID AND
                  Slu_AW_Years_ID = @YearID AND
                  ISNULL(Amount, 0) > 0
        END


    --> TOTAL CB Payments
    ELSE
    IF @Option = 11
        BEGIN
            SELECT ISNULL(SUM(Amount), 0) AS [CBPayments]
            FROM AB_Cash_Book_Transactions
            WHERE AW_User_Companies_ID = @companyID AND
                  Slu_AW_Months_ID = @MonthID AND
                  Slu_AW_Years_ID = @YearID AND
                  ISNULL(Amount, 0) < 0
        END

SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AW_Generic_IF_EXISTS
--Purpose       :VALIDATE IF GL Account is a Subsidiary Ledger Control
--Date          :2005/05/23
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Account_Is_Sub_Control
    (
        @GLAccountID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Exists = dbo.fn_AB_Account_Is_Sub_Control(@GLAccountID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Account_Is_TB_Control
--Purpose       :VALIDATE IF GL Account is a trade debtor control account
--Date          :2017-05-15
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Account_Is_TB_Control]
    (
        @GLAccountID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

	SET @Exists = 0
	
	IF EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE Control_Number in (101, 105)
		AND AB_Accounts_ID = @GLAccountID
	)
	BEGIN
		SET @Exists = 1
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Account_Is_TC_Control
--Purpose       :VALIDATE IF GL Account is a trade creditor control account
--Date          :2017-05-15
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Account_Is_TC_Control]
    (
        @GLAccountID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

	SET @Exists = 0
	
	IF EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE Control_Number in (201, 207)
		AND AB_Accounts_ID = @GLAccountID
	)
	BEGIN
		SET @Exists = 1
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AB_Add_Column_Enterprise_Balance_Sheet
--Purpose       :ADD COLUMNS to AB_Enterprise_Balance_Sheet table
--Date          :2007/09/09
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Add_Column_Enterprise_Balance_Sheet
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AB_Enterprise_Balance_Sheet'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
--            SET @sql = ' ALTER TABLE AB_Enterprise_Balance_Sheet ADD ' + @ColumnName + ' money NULL GO '
            SET @sql = ' ALTER TABLE AB_Enterprise_Balance_Sheet ADD ' + @ColumnName + ' money NULL ' + ' '
--             SET @sql = @sql + ' EXEC sp_bindefault ' +
--                               'N' + '''' + '[dbo].[df_Numeric_Zero]' + '''' + ', N' + '''' +
--                               '[AB_Enterprise_Balance_Sheet].[' + @ColumnName + ']' + '''' + ' GO '
--             SET @sql = @sql + ' EXEC sp_bindefault ' +
--                               'N' + '''' + '[dbo].[df_Numeric_Zero]' + '''' + ', N' + '''' +
--                               '[AB_Enterprise_Balance_Sheet].[' + @ColumnName + ']' + '''' + ' '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AB_Add_Column_Enterprise_Income_Statement
--Purpose       :ADD COLUMNS to AB_Enterprise_Income_Statement table
--Date          :2007/09/05
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Add_Column_Enterprise_Income_Statement
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AB_Enterprise_Income_Statement'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
--            SET @sql = ' ALTER TABLE AB_Enterprise_Income_Statement ADD ' + @ColumnName + ' money NULL GO '
            SET @sql = ' ALTER TABLE AB_Enterprise_Income_Statement ADD ' + @ColumnName + ' money NULL ' + ' '
--             SET @sql = @sql + ' EXEC sp_bindefault ' +
--                               'N' + '''' + '[dbo].[df_Numeric_Zero]' + '''' + ', N' + '''' +
--                               '[AB_Enterprise_Income_Statement].[' + @ColumnName + ']' + '''' + ' GO '
--             SET @sql = @sql + ' EXEC sp_bindefault ' +
--                               'N' + '''' + '[dbo].[df_Numeric_Zero]' + '''' + ', N' + '''' +
--                               '[AB_Enterprise_Income_Statement].[' + @ColumnName + ']' + '''' + ' '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Add_Column_Enterprise_Management_Accounts
--Purpose       :ADD COLUMNS to AB_Enterprise_Management_Accounts table
--Date          :2015-08-20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Add_Column_Enterprise_Management_Accounts]
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @TableID int,
            @RetCode int,
            @DBName varchar(50)


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @DBName = @ColumnName
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AB_Enterprise_Management_Accounts'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
			SET @ColumnName = @DBName + '_Act'
            SET @sql = ' ALTER TABLE AB_Enterprise_Management_Accounts ADD ' + @ColumnName + ' money NULL ' + ' '
            EXEC (@sql)

			SET @ColumnName = @DBName + '_Bud'
            SET @sql = ' ALTER TABLE AB_Enterprise_Management_Accounts ADD ' + @ColumnName + ' money NULL ' + ' '
            EXEC (@sql)
            
			SET @ColumnName = @DBName + '_YTDAct'
            SET @sql = ' ALTER TABLE AB_Enterprise_Management_Accounts ADD ' + @ColumnName + ' money NULL ' + ' '
            EXEC (@sql)

			SET @ColumnName = @DBName + '_YTDBud'
            SET @sql = ' ALTER TABLE AB_Enterprise_Management_Accounts ADD ' + @ColumnName + ' money NULL ' + ' '
            EXEC (@sql)

            SET @RetCode = 1
        END

RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AB_Add_Column_Enterprise_Trial_Balance
--Purpose       :ADD COLUMNS to AB_Enterprise_Trial_Balance table
--Date          :2007/08/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Add_Column_Enterprise_Trial_Balance
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AB_Enterprise_Trial_Balance'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AB_Enterprise_Trial_Balance ADD ' + @ColumnName + ' money NULL ' + ' '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Annual_Budget_Export
--Purpose       :Annual Budget Export
--Parameters    :
--Date          :2011/10/19
--Authors       :TB
--MODS          :
--2004.5.7      :17/01/12 - Added Option to fetch ACTUALS or BUDGET
--RL	V6.4	:2018-05-14 - Changed ID to id. Excel thinks it is a SYLK file if it contains a capital ID 
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Annual_Budget_Export]
    (
        @Option tinyint,
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @M1 tinyint,
        @Y1 int,
        @M2 tinyint,
        @Y2 int,
        @M3 tinyint,
        @Y3 int,
        @M4 tinyint,
        @Y4 int,
        @M5 tinyint,
        @Y5 int,
        @M6 tinyint,
        @Y6 int,
        @M7 tinyint,
        @Y7 int,
        @M8 tinyint,
        @Y8 int,
        @M9 tinyint,
        @Y9 int,
        @M10 tinyint,
        @Y10 int,
        @M11 tinyint,
        @Y11 int,
        @M12 tinyint,
        @Y12 int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)

    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@M12, @Y12)

    IF @Option = 0
        BEGIN
            SET @sql = ' SELECT '
        
            SET @sql = @sql + ' a.AB_Accounts_ID AS [id], '
            SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Category], '
            SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M1) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y1)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M1) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M2) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y2)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M2) + '], '      
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M3) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y3)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M3) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M4) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y4)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M4) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M5) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y5)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M5) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M6) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y6)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M6) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M7) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y7)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M7) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M8) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y8)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M8) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M9) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y9)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M9) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M10) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y10)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M10) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M11) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y11)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M11) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M12) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y12)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M12) + '] '
        
            SET @sql = @sql + ' FROM AB_Accounts a '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
            SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
            SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
            SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
            SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
            SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
        
            SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '        --Only Income Statement accounts
        
            SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
            SET @sql = @sql + '          b.Sys_AB_I2_ID, '
            SET @sql = @sql + '          b.Sys_AB_I3_ID, '
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            SET @sql = @sql + '          a.Description   '
        END
    ELSE
    IF @Option = 1
        BEGIN
            SET @sql = ' SELECT '
        
            SET @sql = @sql + ' a.AB_Accounts_ID AS [ID], '
            SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Category], '
            SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M1) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y1)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M1) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M2) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y2)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M2) + '], '       
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M3) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y3)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M3) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M4) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y4)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M4) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M5) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y5)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M5) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M6) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y6)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M6) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M7) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y7)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M7) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M8) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y8)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M8) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M9) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y9)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M9) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M10) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y10)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M10) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M11) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y11)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M11) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M12) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y12)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M12) + '] '
        
            SET @sql = @sql + ' FROM AB_Accounts a '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
            SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
            SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
            SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
            SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
            SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
        
            SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '        --Only Income Statement accounts
        
            SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
            SET @sql = @sql + '          b.Sys_AB_I2_ID, '
            SET @sql = @sql + '          b.Sys_AB_I3_ID, '
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            SET @sql = @sql + '          a.Description   '
        END

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--------------------------------------------------------------------------
--Description   :sp_AB_Insert_GL_Transactions
--Purpose       :Inserts a Transaction into the General Ledger 
--Functionality :Insert
--Parameters    :
--Date          :2002/01/28
--Authors       :TB
--Version       :1.0.0
--------------------------------------------------------------------------

CREATE             Procedure sp_AB_Balance_GL_Transactions
    (
    	@Company_ID int
    )

AS 

BEGIN

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions_OOB]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_GL_Transactions_OOB]

    
    SELECT *

    INTO AB_GL_Transactions_OOB

    FROM AB_GL_Transactions
    WHERE LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)
          IN (
                 SELECT LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)
                 FROM AB_GL_Transactions
                 GROUP BY LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)
                 HAVING SUM(AB_Transaction_Amount) <> 0
             )
    ORDER BY LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)

END    
    






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





-------------------------------------------------------------------------------------------------------
--Description   : sp_AB_Cash_Book_Transactions_List
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/07/05
--Authors       : Charl
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE  PROCEDURE sp_AB_Cash_Book_Transactions_List
(
	@Company_Banks_ID int,
    @Transaction_Type_ID int,
	@Company_ID int
)
AS
SET NOCOUNT ON

	SELECT AB_Cash_Book_Transactions_ID as [ID], 
		Transaction_Description AS [Descriptions] 
	FROM AB_Cash_Book_Transactions 
	WHERE AW_Company_Banks_ID = @Company_Banks_ID AND 
		Sys_AB_Transaction_Types_ID = @Transaction_Type_ID AND 
		AW_User_Companies_ID = @Company_ID  





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Check_Existing_Transaction_No
--Purpose       :Determines if the transaction no already exists
--Version       :2002/02/12
--Authors       :TB
--MODS          :01/08/05 - Changed @Transaction_No datatype from int to varchar
--              :           causing error in Supplier Payments when next tran No
--              :           changed from numeric to alpha/numeric 
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Check_Existing_Transaction_No
    (
    	@Transaction_Type_ID int,
    	@Transaction_No int,
--    	@Transaction_No varchar(20),
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	DECLARE @CashBook_ID int


	SELECT @CashBook_ID = ISNULL(AB_Cash_Book_Transactions_ID, 0)
	FROM AB_Cash_Book_Transactions
	WHERE Sys_AB_Transaction_Types_ID = @Transaction_Type_ID AND
          Reference_No = @Transaction_No AND 
          AW_User_Companies_ID = @Company_ID


	RETURN @CashBook_ID
	

		







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_AB_Clear_Cash_Flows
--Purpose       :Drop Cash Flow tables
--Date          :8 FEB 2011
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Clear_Cash_Flows
    (
        @Option tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0


    IF @Option = 0
        BEGIN
            if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Inflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
            drop table [dbo].[AB_Cash_Inflow_Projections]

            CREATE TABLE [dbo].[AB_Cash_Inflow_Projections] (
            	[AB_Cash_Inflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
            	[Post] [bit] NULL ,
            	[Inflow_Date] [datetime] NULL ,
            	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
            	[Amount] [money] NULL ,
            	[Tax_Amount] [money] NULL ,
            	[Net_Amount] [money] NULL ,
            	[Date_Captured] [datetime] NULL ,
            	[User_ID] [int] NULL ,
            	[AW_User_Companies_ID] [int] NULL ,
            	[Touched] [timestamp] NULL ,
            	[Slu_AW_Active_ID] [tinyint] NULL 
                ) ON [PRIMARY]

            ALTER TABLE [dbo].[AB_Cash_Inflow_Projections] WITH NOCHECK ADD 
            	CONSTRAINT [PK_AB_Cash_Inflow_Projections] PRIMARY KEY  CLUSTERED 
            	(
            		[AB_Cash_Inflow_Projections_ID]
            	)  ON [PRIMARY] 

            setuser

            EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Inflow_Projections].[AW_User_Companies_ID]'
            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Date_Captured]'
            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Inflow_Date]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Amount]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Tax_Amount]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Net_Amount]'
            EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Inflow_Projections].[Description]'
            EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Inflow_Projections].[User_ID]'

            setuser

            SET @RetCode = 1
        END

    ELSE
    IF @Option = 1
        BEGIN
            if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Outflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
            drop table [dbo].[AB_Cash_Outflow_Projections]

            CREATE TABLE [dbo].[AB_Cash_Outflow_Projections] (
            	[AB_Cash_Outflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
            	[Post] [bit] NULL ,
            	[Outflow_Date] [datetime] NULL ,
            	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
            	[Amount] [money] NULL ,
            	[Tax_Amount] [money] NULL ,
            	[Net_Amount] [money] NULL ,
            	[Date_Captured] [datetime] NULL ,
            	[User_ID] [int] NULL ,
            	[AW_User_Companies_ID] [int] NULL ,
            	[Touched] [timestamp] NULL ,
            	[Slu_AW_Active_ID] [tinyint] NULL 
                ) ON [PRIMARY]

            ALTER TABLE [dbo].[AB_Cash_Outflow_Projections] WITH NOCHECK ADD 
            	CONSTRAINT [PK_AB_Cash_Outflow_Projections] PRIMARY KEY  CLUSTERED 
            	(
            		[AB_Cash_Outflow_Projections_ID]
            	)  ON [PRIMARY] 

            setuser

            EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Outflow_Projections].[AW_User_Companies_ID]'
            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Date_Captured]'
            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Outflow_Date]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Amount]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Tax_Amount]'
            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Net_Amount]'
            EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Outflow_Projections].[Description]'
            EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Outflow_Projections].[User_ID]'

            setuser

            SET @RetCode = 1
        END



RETURN @RetCode














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_Create_Cashflow_Forecast
--Purpose       :Creates a Cash Flow Forecast
--Date          :2011/02/22
--Authors       :TB
--MODS:
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Create_Cashflow_Forecast
    (
        @ExclCBForecast tinyint,
        @AvgMonths tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @SQL varchar(4000),
            @StartPeriod varchar(6),
            @AvgFrom varchar(6),
            @AvgTo varchar(6),
            @FromMonthID int,
            @FromYearID int,
            @ThisMonthID int,
            @ThisYearID int,
            @LastMonthID int,
            @LastYearID int,
        	@FromMonthNo int,
        	@ToMonthNo int,
            @M1 tinyint,
            @M2 tinyint,
            @M3 tinyint,
            @M4 tinyint,
            @M5 tinyint,
            @M6 tinyint,
            @SD1 datetime,
            @SD2 datetime,
            @SD3 datetime,
            @SD4 datetime,
            @SD5 datetime,
            @SD6 datetime,
            @ED1 datetime,
            @ED2 datetime,
            @ED3 datetime,
            @ED4 datetime,
            @ED5 datetime,
            @ED6 datetime,
            @P1 varchar(10),
            @P2 varchar(10),
            @P3 varchar(10),
            @P4 varchar(10),
            @P5 varchar(10),
            @P6 varchar(10),
            @V1 bigint,
            @V2 bigint,
            @V3 bigint,
            @V4 bigint,
            @V5 bigint,
            @V6 bigint,
            @Total bigint,
            @CFFID int,
            @Temp1 bigint

    -------------------------------------------------------------------------------
    --> Declare a TABLE variable
    -------------------------------------------------------------------------------
    DECLARE @CFF table
        (
	        [ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[N1] [tinyint] DEFAULT 0 NULL ,
        	[M1] [bigint] DEFAULT 0 NULL ,
        	[M2] [bigint] DEFAULT 0 NULL ,
        	[M3] [bigint] DEFAULT 0 NULL ,
        	[M4] [bigint] DEFAULT 0 NULL ,
        	[M5] [bigint] DEFAULT 0 NULL ,
        	[M6] [bigint] DEFAULT 0 NULL ,
        	[T1] [bigint] DEFAULT 0 NULL ,
        	[RowTypeID] [tinyint] DEFAULT 0 NULL ,
        	[StartDate] [datetime] DEFAULT getdate() NULL ,
        	[AW_User_Companies_ID] [int] DEFAULT 1 NULL
        )

    -------------------------------------------------------------------------------
    --> Get the Current Accouting Periods
    -------------------------------------------------------------------------------
    SELECT @ThisMonthID = Slu_AW_Months_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

    SELECT @ThisYearID = Slu_AW_Years_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID
    --------------------------------------------------------------------
    --> Set the Last Accounting Period
    SET @LastMonthID = @ThisMonthID - 1
    SET @LastYearID = @ThisYearID

    IF @LastMonthID = 0
        BEGIN
            SET @LastMonthID = 12
            SET @LastYearID = @LastYearID - 1
        END
    --------------------------------------------------------------------

    --> Set the GL fetch periods
    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@LastMonthID, @LastYearID)

    --------------------------------------------------------------------
    --> Set the Accounting Period span to AVERAGE CB Receipts and Payments
    IF @AvgMonths <= 0
        BEGIN
            SET @AvgMonths = 1
        END

    IF @AvgMonths > 12
        BEGIN
            SET @AvgMonths = 12
        END

    SET @FromMonthID = @LastMonthID - (@AvgMonths - 1)    --must be -1 otherwise span = 13 months
    SET @FromYearID = @LastYearID

    IF @FromMonthID < 0
        BEGIN
            SET @FromMonthID = (12 + @FromMonthID)
            SET @FromYearID = @FromYearID - 1
        END

    IF @FromMonthID = 0
        BEGIN
            SET @FromMonthID = 12
            SET @FromYearID = @FromYearID - 1
        END

    SET @AvgFrom = dbo.fn_AB_Get_Ending_GL_Period(@FromMonthID, @FromYearID)
    SET @AvgTo = dbo.fn_AB_Get_Ending_GL_Period(@LastMonthID, @LastYearID)
    --------------------------------------------------------------------

    --> Set Forecast span
    SET @FromMonthNo = dbo.fn_AS_Get_Month_Number(@FromDate)
    SET @ToMonthNo = dbo.fn_AS_Get_Month_Number(@ToDate)

    --> Set Month numbers - e.g. @M1 = 1
    SET @M1 = @ThisMonthID
    SET @M2 = @M1 + 1
    SET @M3 = @M2 + 1
    SET @M4 = @M3 + 1
    SET @M5 = @M4 + 1
    SET @M6 = @M5 + 1

    --> Set Forecast Month START dates - e.g. @SD1 = '2011/01/01', @SD6 = '2011/06/01'
    SET @SD1 = @FromDate
    SET @SD2 = DATEADD(mm, 1, @SD1)
    SET @SD3 = DATEADD(mm, 1, @SD2) 
    SET @SD4 = DATEADD(mm, 1, @SD3)
    SET @SD5 = DATEADD(mm, 1, @SD4)
    SET @SD6 = DATEADD(mm, 1, @SD5)
    
    --> ADD ONE MONTH to the FROMDATE to get the FIRST DAY ON NEXT MONTH (1 FEB, 1 MAR, 1 JUL etc.)
    SET @ED1 = DATEADD(mm, 1, @FromDate)
    SET @ED2 = DATEADD(mm, 1, @ED1)
    SET @ED3 = DATEADD(mm, 1, @ED2) 
    SET @ED4 = DATEADD(mm, 1, @ED3)
    SET @ED5 = DATEADD(mm, 1, @ED4)
    SET @ED6 = DATEADD(mm, 1, @ED5)
    
    --> Now DEDUCT ONE DAY from the result to get the LAST DAY OF PREVIOUS MONTH (31 JAN, 28 FEB, 30 JUN etc.)
    SET @ED1 = DATEADD(dd, -1, @ED1)
    SET @ED2 = DATEADD(dd, -1, @ED2)
    SET @ED3 = DATEADD(dd, -1, @ED3) 
    SET @ED4 = DATEADD(dd, -1, @ED4)
    SET @ED5 = DATEADD(dd, -1, @ED5)
    SET @ED6 = DATEADD(dd, -1, @ED6)

    --> Set Forecast Column names - e.g. @P1 = 'JAN 2011', @P6 = 'JUN 2011'
    SET @P1 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @SD1))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @SD1))
    SET @P2 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @SD2))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @SD2))
    SET @P3 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @SD3))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @SD3))
    SET @P4 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @SD4))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @SD4))
    SET @P5 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @SD5))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @SD5))
    SET @P6 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @SD6))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @SD6))


    -------------------------------------------------------------------------------
    -- PROCEDURES
    -------------------------------------------------------------------------------


    --> INSERT of ALL the CASH or OVERDRAFT Accounts - as at LAST MONTH END)
    ----------> Use: CASH ON HAND (beginning of month) - TOTAL
    INSERT INTO @CFF
    SELECT 'CASH ON HAND (beginning of month)',
           1 AS [N1],
           ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [M1],
           ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [M2],
           ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [M3],
           ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [M4],
           ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [M5],
           ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [M6],
           0 AS [T1],
           1 AS [RowTypeID],
           @FromDate AS [StartDate],
           @CompanyID AS [AW_User_Companies_ID]
    FROM AB_GL_Transactions t
        INNER JOIN AB_Accounts g
            ON t.AB_Accounts_ID = g.AB_Accounts_ID
    WHERE t.AW_User_Companies_ID = @CompanyID AND
         (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
          g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
          dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @StartPeriod


    -------------------------------------------------------------------------------


    --> INSERT CASH RECEIPTS HEADING
    INSERT INTO @CFF
    SELECT 'CASH RECEIPT PROJECTIONS',
           2,
           0,
           0,
           0,
           0,
           0,
           0,
           0,
           0,
           @FromDate AS [StartDate],
           @CompanyID AS [AW_User_Companies_ID]


    -------------------------------------------------------------------------------


    --> INSERT of ALL the CASH INFLOW PROJECTIONS per MONTH)
    ----------> Use: CASH INFLOW PROJECTIONS (per month)
    INSERT INTO @CFF
    SELECT Description AS [Description],
           2 AS [N1],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Inflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD1) AND dbo.fn_AS_Get_Month_Number(Inflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED1)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M1],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Inflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD2) AND dbo.fn_AS_Get_Month_Number(Inflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED2)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M2],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Inflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD3) AND dbo.fn_AS_Get_Month_Number(Inflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED3)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M3],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Inflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD4) AND dbo.fn_AS_Get_Month_Number(Inflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED4)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M4],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Inflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD5) AND dbo.fn_AS_Get_Month_Number(Inflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED5)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M5],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Inflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD6) AND dbo.fn_AS_Get_Month_Number(Inflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED6)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M6],
           0 AS [T1],
           1 AS [RowTypeID],
           @FromDate AS [StartDate],
           @CompanyID AS [AW_User_Companies_ID]
    FROM AB_Cash_Inflow_Projections
    WHERE AW_User_Companies_ID = @CompanyID AND
          Post = 1 AND
         (dbo.fn_AS_Get_Month_Number(Inflow_Date) >= @FromMonthNo AND
          dbo.fn_AS_Get_Month_Number(Inflow_Date) <= @ToMonthNo)


    -------------------------------------------------------------------------------

    --> INSERT CASH RECEIPTS HEADING
    IF @ExclCBForecast = 0
        BEGIN
            INSERT INTO @CFF
            SELECT 'CASH RECEIPTS (Cash Book Deposits)',
                   3,
                   0,
                   0,
                   0,
                   0,
                   0,
                   0,
                   0,
                   0,
                   @FromDate AS [StartDate],
                   @CompanyID AS [AW_User_Companies_ID]
        END    


    -------------------------------------------------------------------------------


    --> INSERT CB Receipts - GL Account Detail
    ----------> Use: CASH RECEIPTS (CURRENT month) (NB: REVERSE the SIGN of amount from CB)
    IF @ExclCBForecast = 0
        BEGIN
            INSERT INTO @CFF
            SELECT g.Description AS [GLAccount],
                   3 AS [N1],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M1],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M2],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M3],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M4],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M5],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M6],
                   0 AS [T1],
                   1 AS [RowTypeID],
                   @FromDate AS [StartDate],
                   @CompanyID AS [AW_User_Companies_ID]
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
                  dbo.fn_AB_Get_Ending_GL_Period(h.Slu_AW_Months_ID, h.Slu_AW_Years_ID) >= @AvgFrom AND
                  dbo.fn_AB_Get_Ending_GL_Period(h.Slu_AW_Months_ID, h.Slu_AW_Years_ID) <= @AvgTo AND
                  ISNULL(d.Amount, 0) < 0
            GROUP BY d.AB_Accounts_ID, g.Description
            ORDER BY [GLAccount]
        END


    -------------------------------------------------------------------------------


    --> INSERT CASH RECEIPTS HEADING
    INSERT INTO @CFF
    SELECT 'CASH PAYMENT PROJECTIONS',
           4,
           0,
           0,
           0,
           0,
           0,
           0,
           0,
           0,
           @FromDate AS [StartDate],
           @CompanyID AS [AW_User_Companies_ID]


    -------------------------------------------------------------------------------

    --> INSERT of ALL the CASH OUTFLOW PROJECTIONS per MONTH)
    ----------> Use: CASH OUTFLOW PROJECTIONS (per month)
    INSERT INTO @CFF
    SELECT Description AS [Description],
           4 AS [N1],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Outflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD1) AND dbo.fn_AS_Get_Month_Number(Outflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED1)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M1],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Outflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD2) AND dbo.fn_AS_Get_Month_Number(Outflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED2)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M2],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Outflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD3) AND dbo.fn_AS_Get_Month_Number(Outflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED3)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M3],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Outflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD4) AND dbo.fn_AS_Get_Month_Number(Outflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED4)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M4],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Outflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD5) AND dbo.fn_AS_Get_Month_Number(Outflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED5)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M5],
           CASE WHEN dbo.fn_AS_Get_Month_Number(Outflow_Date) >= dbo.fn_AS_Get_Month_Number(@SD6) AND dbo.fn_AS_Get_Month_Number(Outflow_Date) <= dbo.fn_AS_Get_Month_Number(@ED6)
                THEN ISNULL(Net_Amount, 0)
                ELSE 0
           END AS [M6],
           0 AS [T1],
           1 AS [RowTypeID],
           @FromDate AS [StartDate],
           @CompanyID AS [AW_User_Companies_ID]
    FROM AB_Cash_Outflow_Projections
    WHERE AW_User_Companies_ID = @CompanyID AND
          Post = 1 AND
         (dbo.fn_AS_Get_Month_Number(Outflow_Date) >= @FromMonthNo AND
          dbo.fn_AS_Get_Month_Number(Outflow_Date) <= @ToMonthNo)


    -------------------------------------------------------------------------------

    --> INSERT CASH RECEIPTS HEADING
    IF @ExclCBForecast = 0
        BEGIN
            INSERT INTO @CFF
            SELECT 'CASH PAID OUT (Cash Book Payments)',
                   5,
                   0,
                   0,
                   0,
                   0,
                   0,
                   0,
                   0,
                   0,
                   @FromDate AS [StartDate],
                   @CompanyID AS [AW_User_Companies_ID]
        END

    -------------------------------------------------------------------------------


    --> INSERT CB Payments - GL Account Detail
    ----------> Use: CASH PAID OUT (CURRENT month) (NB: REVERSE the SIGN of amount from CB)
    IF @ExclCBForecast = 0
        BEGIN
            INSERT INTO @CFF
            SELECT g.Description AS [GLAccount],
                   5 AS [N1],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M1],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M2],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M3],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M4],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M5],
                   -ISNULL(SUM(d.Amount), 0) / @AvgMonths AS [M6],
                   0 AS [T1],
                   1 AS [RowTypeID],
                   @FromDate AS [StartDate],
                   @CompanyID AS [AW_User_Companies_ID]
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
                  dbo.fn_AB_Get_Ending_GL_Period(h.Slu_AW_Months_ID, h.Slu_AW_Years_ID) >= @AvgFrom AND
                  dbo.fn_AB_Get_Ending_GL_Period(h.Slu_AW_Months_ID, h.Slu_AW_Years_ID) <= @AvgTo AND
                  ISNULL(d.Amount, 0) >= 0
            GROUP BY d.AB_Accounts_ID, g.Description
            ORDER BY [GLAccount]
        END


    -------------------------------------------------------------------------------


    --> INSERT CASH RECEIPTS HEADING
    INSERT INTO @CFF
    SELECT 'CASH POSITION (end of month)',
           6,
           0,
           0,
           0,
           0,
           0,
           0,
           0,
           1,
           @FromDate AS [StartDate],
           @CompanyID AS [AW_User_Companies_ID]


    -------------------------------------------------------------------------------
    -- SUM CASH POSITION and SET BEGINNING CASH ON HAND (for the 6 months)
    -------------------------------------------------------------------------------

    ------------------------------------------
    --> Get the CASH POSITION of month 1
    SELECT @Temp1 = SUM(M1)
    FROM @CFF
    WHERE N1 <> 6 AND
          M1 IS NOT NULL
    ------------------------------------------
    --> SET the CASH POSITION of month 1
    UPDATE @CFF
    SET M1 = @Temp1
    WHERE N1 = 6
    ----------------------
    --> SET the beginning CASH ON HAND of month 2
    UPDATE @CFF
    SET M2 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 2
    SELECT @Temp1 = SUM(M2)
    FROM @CFF
    WHERE N1 <> 6 AND
          M2 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 2
    UPDATE @CFF
    SET M2 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 3
    UPDATE @CFF
    SET M3 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 3
    SELECT @Temp1 = SUM(M3)
    FROM @CFF
    WHERE N1 <> 6 AND
          M3 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 3
    UPDATE @CFF
    SET M3 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 4
    UPDATE @CFF
    SET M4 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 4
    SELECT @Temp1 = SUM(M4)
    FROM @CFF
    WHERE N1 <> 6 AND
          M4 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 4
    UPDATE @CFF
    SET M4 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 5
    UPDATE @CFF
    SET M5 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 5
    SELECT @Temp1 = SUM(M5)
    FROM @CFF
    WHERE N1 <> 6 AND
          M5 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 5
    UPDATE @CFF
    SET M5 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 6
    UPDATE @CFF
    SET M6 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 6
    SELECT @Temp1 = SUM(M6)
    FROM @CFF
    WHERE N1 <> 6 AND
          M6 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 6
    UPDATE @CFF
    SET M6 = @Temp1
    WHERE N1 = 6
    ------------------------------------------


    -------------------------------------------------------------------------------
    -- CROSS-CAST months to TOTAL column using CURSOR
    -------------------------------------------------------------------------------

    --> Define a CURSOR for Income and Expense accounts
    DECLARE Sum_Cursor CURSOR FOR
        SELECT ID,
               ISNULL(M1, 0),
               ISNULL(M2, 0),
               ISNULL(M3, 0),
               ISNULL(M4, 0),
               ISNULL(M5, 0),
               ISNULL(M6, 0)
        FROM @CFF
        WHERE N1 <> 0 AND N1 <> 1 AND N1 <> 6

	OPEN Sum_Cursor

    	FETCH NEXT FROM Sum_Cursor 
    	INTO
            @CFFID,
            @V1,
            @V2,
            @V3,
            @V4,
            @V5,
            @V6
    	
    	WHILE @@FETCH_STATUS = 0
        	BEGIN
                SET @Total = @V1 + @V2 + @V3 + @V4 + @V5 + @V6

                UPDATE @CFF
                SET T1 = @Total
                WHERE ID = @CFFID

            	FETCH NEXT FROM Sum_Cursor 
            	INTO
                    @CFFID,
                    @V1,
                    @V2,
                    @V3,
                    @V4,
                    @V5,
                    @V6
        	END
	
	CLOSE Sum_Cursor

	DEALLOCATE Sum_Cursor

    -------------------------------------------------------------------------------
    -- DROP the TEMP TABLE
    -------------------------------------------------------------------------------

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Flow_Forecast_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Flow_Forecast_Temp]
 
    CREATE TABLE [dbo].[AB_Cash_Flow_Forecast_Temp] (
    	[AB_Cash_Flow_Forecast_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[N1] [tinyint] NULL ,
    	[M1] [bigint] NULL ,
    	[M2] [bigint] NULL ,
    	[M3] [bigint] NULL ,
    	[M4] [bigint] NULL ,
    	[M5] [bigint] NULL ,
    	[M6] [bigint] NULL ,
    	[T1] [bigint] NULL ,
    	[RowTypeID] [tinyint] NULL ,
        [StartDate] [datetime] NULL ,
        [AW_User_Companies_ID] [int] NULL
    ) ON [PRIMARY]
 
    CREATE CLUSTERED INDEX [CI_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp] ([N1], [RowTypeID], [Description])
    CREATE UNIQUE INDEX [IX_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp] ([AB_Cash_Flow_Forecast_Temp_ID])

    setuser

    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Flow_Forecast_Temp].[Description]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[N1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M2]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M3]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M4]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M5]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M6]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[T1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[RowTypeID]'
    EXEC sp_bindefault N'[dbo].[df_Todays_Date]', N'[AB_Cash_Flow_Forecast_Temp].[StartDate]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Flow_Forecast_Temp].[AW_User_Companies_ID]'

    setuser
 
    -------------------------------------------------------------------------------
    -- INSERT the DATA into TEMP TABLE
    -------------------------------------------------------------------------------

    INSERT INTO AB_Cash_Flow_Forecast_Temp
    SELECT Description,
           N1,
           M1,
           M2,
           M3,
           M4,
           M5,
           M6,
           T1,
           RowTypeID,
           StartDate,
           AW_User_Companies_ID
    FROM @CFF


    -------------------------------------------------------------------------------
    -- FETCH the DATA
    -------------------------------------------------------------------------------

    SET @SQL = ' SELECT '
    SET @SQL = @SQL + ' AB_Cash_Flow_Forecast_Temp_ID AS [ID], '
    SET @SQL = @SQL + ' Description AS [Description], '
    SET @SQL = @SQL + ' N1 AS [Group], '
    SET @SQL = @SQL + ' M1 AS [' + '' + @P1 + '' + '], '
    SET @SQL = @SQL + ' M2 AS [' + '' + @P2 + '' + '], '
    SET @SQL = @SQL + ' M3 AS [' + '' + @P3 + '' + '], '
    SET @SQL = @SQL + ' M4 AS [' + '' + @P4 + '' + '], '
    SET @SQL = @SQL + ' M5 AS [' + '' + @P5 + '' + '], '
    SET @SQL = @SQL + ' M6 AS [' + '' + @P6 + '' + '], '
    SET @SQL = @SQL + ' T1 AS [Total], '
    SET @SQL = @SQL + ' RowTypeID AS [RowTypeID], '
    SET @SQL = @SQL + ' StartDate AS [StartDate], '
    SET @SQL = @SQL + ' AW_User_Companies_ID AS [CompanyID] '
    SET @SQL = @SQL + ' FROM AB_Cash_Flow_Forecast_Temp '
    SET @SQL = @SQL + ' ORDER BY N1, RowTypeID, Description '


    EXEC (@SQL)




SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AB_Current_Accounting_Period
--Purpose       :Fetch the Current Accounting Period for the Company
--Functionality :
--Parameters    :
--Date          :2002/11/02
--Authors       :TB
--Version       :1.0.0
--MODS          :18/12/02 - Added returning @YearEndMonthID for the company
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Current_Accounting_Period
	(
        @CompanyID int,
        @MonthID int OUTPUT,
        @MonthShort varchar(10) OUTPUT,
        @MonthLong varchar(10) OUTPUT,
        @YearID int OUTPUT,
        @Year int OUTPUT,
        @YearEndMonthID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @MonthID = ISNULL(Slu_AW_Months_ID, 1),
           @YearID = ISNULL(Slu_AW_Years_ID, 1),
           @YearEndMonthID = ISNULL(Year_End_Month_ID, 1)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

    SELECT @MonthShort = ISNULL([Description], 'Jan'),
           @MonthLong = ISNULL(Long_Description, 'January')
    FROM Slu_AW_Months
    WHERE Slu_AW_Months_ID = @MonthID

    SELECT @Year = ISNULL([Description], 2000)
    FROM Slu_AW_Years
    WHERE Slu_AW_Years_ID = @YearID

        
SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AB_Delete_Bank_TranType_IBS_Maps
--Purpose       :Deletes a selected Bank TranType IBS Map row
--Functionality :
--Date          :2010/03/24
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Delete_Bank_TranType_IBS_Maps
    (
        @MapID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT Lup_AB_Transaction_Type_Maps_ID
            FROM Lup_AB_Transaction_Type_Maps
            WHERE Lup_AB_Transaction_Type_Maps_ID = @MapID
        )
        BEGIN
            DELETE Lup_AB_Transaction_Type_Maps
            WHERE Lup_AB_Transaction_Type_Maps_ID = @MapID

            SET @ReturnValue = 1
        END


RETURN @ReturnValue






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AB_Delete_Cash_Book_IBS_Maps
--Purpose       :Deletes a selected Cash Book IBS Map row
--Functionality :
--Date          :2010/02/28
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Delete_Cash_Book_IBS_Maps
    (
        @MapID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AB_Cash_Book_IBS_Map_ID
            FROM AB_Cash_Book_IBS_Map
            WHERE AB_Cash_Book_IBS_Map_ID = @MapID
        )
        BEGIN
            DELETE AB_Cash_Book_IBS_Map
            WHERE AB_Cash_Book_IBS_Map_ID = @MapID

            SET @ReturnValue = 1
        END


RETURN @ReturnValue




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AB_Delete_Cash_Book_IBS_Notes
--Purpose       :Deletes a selected Cash Book IBS Notes row
--Functionality :
--Date          :2010/03/03
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Delete_Cash_Book_IBS_Notes
    (
        @NoteID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AB_Cash_Book_IBS_Notes_ID
            FROM AB_Cash_Book_IBS_Notes
            WHERE AB_Cash_Book_IBS_Notes_ID = @NoteID
        )
        BEGIN
            DELETE AB_Cash_Book_IBS_Notes
            WHERE AB_Cash_Book_IBS_Notes_ID = @NoteID

            SET @ReturnValue = 1
        END


RETURN @ReturnValue




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AB_Delete_Cash_Inflow
--Purpose       :Deletes a selected Cash Inflow row
--Date          :2011/02/09
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Delete_Cash_Inflow
    (
        @InflowID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AB_Cash_Inflow_Projections_ID
            FROM AB_Cash_Inflow_Projections
            WHERE AB_Cash_Inflow_Projections_ID = @InflowID
        )
        BEGIN
            DELETE AB_Cash_Inflow_Projections
            WHERE AB_Cash_Inflow_Projections_ID = @InflowID

            SET @ReturnValue = 1
        END


RETURN @ReturnValue





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AB_Delete_Cash_Outflow
--Purpose       :Deletes a selected Cash Outflow row
--Date          :2011/02/09
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Delete_Cash_Outflow
    (
        @OutflowID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AB_Cash_Outflow_Projections_ID
            FROM AB_Cash_Outflow_Projections
            WHERE AB_Cash_Outflow_Projections_ID = @OutflowID
        )
        BEGIN
            DELETE AB_Cash_Outflow_Projections
            WHERE AB_Cash_Outflow_Projections_ID = @OutflowID

            SET @ReturnValue = 1
        END


RETURN @ReturnValue





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AB_Delete_Inactive_GL_Account
--Purpose       :DELETE ONE UNUSED GL Account with NO ACTIVITY VALIDATED in UI
--Date          :2009/03/14
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Delete_Inactive_GL_Account
	(
		@GLAccountID int,
        @CompanyID int,
        @ActivityCNT int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int


    SET @ReturnCode = 0


    --> If ZERO ACTIVITY
    IF @ActivityCNT = 0
        BEGIN
            BEGIN TRAN Delete_GLAccount
        
            	BEGIN
                    DELETE AB_Accounts
                    WHERE AB_Accounts_ID = @GLAccountID AND
                          AW_User_Companies_ID = @CompanyID
                END

            COMMIT TRAN Delete_GLAccount

            SET @ReturnCode = 1
        END




RETURN @ReturnCode











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   : sp_AB_Delete_Recurring_Journal
--Purpose       : Deletes a selected Recurring Journals Header and Details
--Functionality :
--Parameters    :
--Date          : 2002/12/28
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Delete_Recurring_Journal
    (
        @RecurringID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AB_Recurring_ID
            FROM AB_Recurring
            WHERE AB_Recurring_ID = @RecurringID

        )
        BEGIN
            DELETE AB_Recurring_Details
            WHERE AB_Recurring_ID = @RecurringID

            DELETE AB_Recurring
            WHERE AB_Recurring_ID = @RecurringID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Cash_Flow_Forecast_Temp
--Purpose       :Drop AB_Cash_Flow_Forecast_Temp table
--Date          :25 FEB 2011
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Drop_Cash_Flow_Forecast_Temp

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Flow_Forecast_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Flow_Forecast_Temp]
    
    CREATE TABLE [dbo].[AB_Cash_Flow_Forecast_Temp] (
    	[AB_Cash_Flow_Forecast_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[N1] [tinyint] NULL ,
    	[M1] [bigint] NULL ,
    	[M2] [bigint] NULL ,
    	[M3] [bigint] NULL ,
    	[M4] [bigint] NULL ,
    	[M5] [bigint] NULL ,
    	[M6] [bigint] NULL ,
    	[T1] [bigint] NULL ,
    	[RowTypeID] [tinyint] NULL  ,
        [StartDate] [datetime] NULL ,
	    [AW_User_Companies_ID] [int] NULL
    ) ON [PRIMARY]

     CREATE  CLUSTERED  INDEX [CI_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([N1], [RowTypeID], [Description]) ON [PRIMARY]
     CREATE  UNIQUE  INDEX [IX_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([AB_Cash_Flow_Forecast_Temp_ID]) ON [PRIMARY]

    setuser

    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Flow_Forecast_Temp].[Description]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M2]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M3]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M4]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M5]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M6]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[N1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[RowTypeID]'
    EXEC sp_bindefault N'[dbo].[df_Todays_Date]', N'[AB_Cash_Flow_Forecast_Temp].[StartDate]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[T1]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Flow_Forecast_Temp].[AW_User_Companies_ID]'

    setuser


    SET @RetCode = 1


RETURN @RetCode

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Balance_Sheet
--Purpose       :Drops and re-creates AP_Enterprise_Balance_Sheet table
--Date          :2007/09/09
--Authors       :TB
--MODS          :
--2004.3.8      :08/04/08 - Increased [Category] from [50] to [100] !!!!!
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Balance_Sheet]

AS

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Balance_Sheet]

        
        CREATE TABLE [dbo].[AB_Enterprise_Balance_Sheet] (
        	[AB_Enterprise_Balance_Sheet_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_B1_ID] [int] NULL ,
        	[Sys_AB_B2_ID] [int] NULL ,
        	[Sys_AB_B3_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Balance_Sheet] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Balance_Sheet] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Balance_Sheet_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Income_Statement
--Purpose       :Drops and re-creates AP_Enterprise_Income_Statement table
--Date          :2007/09/05
--Authors       :TB
--MODS          :
--2004.3.8      :08/04/08 - Increased [Category] from [50] to [100] !!!!!
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Income_Statement]

AS

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Income_Statement]

        
        CREATE TABLE [dbo].[AB_Enterprise_Income_Statement] (
        	[AB_Enterprise_Income_Statement_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_I1_ID] [int] NULL ,
        	[Sys_AB_I2_ID] [int] NULL ,
        	[Sys_AB_I3_ID] [int] NULL ,
        	[Sys_AB_I4_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,        	
        	[Total] [money] NULL
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Income_Statement] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Income_Statement] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Income_Statement_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Management_Accounts
--Purpose       :Drops and re-creates AB_Enterprise_Management_Accounts table
--Date          :2015-08-20
--Authors       :RL
--MODS          :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Management_Accounts]
AS

    DECLARE @ReturnValue int
    SET @ReturnValue = 0

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Management_Accounts]
        
        CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
        	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[IS1ID] [int] NULL ,
        	[IS2ID] [int] NULL ,        	
        	[IS3ID] [int] NULL ,        	
        	[IS4ID] [int] NULL ,
        	[GLID] [int] NULL ,
        	[DivisionID] [int] NULL ,
        	[GroupID] [int] NULL ,
        	
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	
        	[GLDivision] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[GLGroup] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[AccountNo] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[Account] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,       	
        	
        	[TotalActual] [money] NULL,
        	[TotalBudget] [money] NULL,
        	[TotalYTDActual] [money] NULL,
        	[TotalYTDBudget] [money] NULL        	
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Management_Accounts_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Trial_Balance
--Purpose       :Drops and re-creates AP_Enterprise_Trial_Balance table
--Date          :2007/08/28
--Authors       :TB
--MODS          :
--2004.3.8      :08/04/08 - Increased [Category] from [50] to [100] !!!!!
--2004.4.8      :05/11/09 - Added Divisions and Groups columns sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Trial_Balance]

AS

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Trial_Balance]

        CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
        	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Divisions] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Groups] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Trial_Balance_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Enterprise_Management_Account_Division_Sales
--Purpose       :Enterprise Management Accounts DIVISION Sales Total
--Date          :2015-08-23
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Enterprise_Management_Account_Division_Sales]
    (
        @DivisionID int,
        @CurrentTot money OUTPUT,
        @BudgetTot money OUTPUT,
        @BalanceTot money OUTPUT,
        @YTDBudgetTot money OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT
        @CurrentTot = 
            (
                SELECT ISNULL(SUM(TotalActual), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
            ),
        
        @BudgetTot = 
            (
                SELECT ISNULL(SUM(TotalBudget), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
            ),

        @BalanceTot = 
            (
                SELECT ISNULL(SUM(TotalYTDActual), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
            ),

        @YTDBudgetTot = 
            (
                SELECT ISNULL(SUM(TotalYTDBudget), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
            )

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Enterprise_Management_Account_Group_Sales
--Purpose       :Enterprise Management Accounts GROUP Sales Total
--Date          :2015-08-23
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Enterprise_Management_Account_Group_Sales]
    (
        @DivisionID int,
        @GroupID int,
        @CurrentTot money OUTPUT,
        @BudgetTot money OUTPUT,
        @BalanceTot money OUTPUT,
        @YTDBudgetTot money OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT
        @CurrentTot = 
            (
                SELECT ISNULL(SUM(TotalActual), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
                  AND GroupID = @GroupID
            ),
        
        @BudgetTot = 
            (
                SELECT ISNULL(SUM(TotalBudget), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
                  AND GroupID = @GroupID
            ),

        @BalanceTot = 
            (
                SELECT ISNULL(SUM(TotalYTDActual), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
                  AND GroupID = @GroupID
            ),

        @YTDBudgetTot = 
            (
                SELECT ISNULL(SUM(TotalYTDBudget), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
                  AND DivisionID = @DivisionID
                  AND GroupID = @GroupID
            )

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Enterprise_Management_Account_Sales
--Purpose       :Enterprise Management Accounts Sales Total
--Date          :2015-08-23
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Enterprise_Management_Account_Sales]
    (
        @CurrentTot money OUTPUT,
        @BudgetTot money OUTPUT,
        @BalanceTot money OUTPUT,
        @YTDBudgetTot money OUTPUT
    )
AS

SET NOCOUNT ON
 
    SELECT
        @CurrentTot = 
            (
                SELECT ISNULL(SUM(TotalActual), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
            ),
        
        @BudgetTot = 
            (
                SELECT ISNULL(SUM(TotalBudget), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
            ),

        @BalanceTot = 
            (
                SELECT ISNULL(SUM(TotalYTDActual), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
            ),

        @YTDBudgetTot = 
            (
                SELECT ISNULL(SUM(TotalYTDBudget), 0)
                FROM AB_Enterprise_Management_Accounts
                WHERE IS4ID = 10
            )
 
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_Exists_IBS_Post
--Purpose       :Cash Book IBS - Check if transactions posted
--Date          :2010/03/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Exists_IBS_Post
	(
        @Date datetime,
        @BankDesc varchar(100),
        @Amount money,
		@Test int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @Test = 0


	SELECT TOP 1 @Test = AB_Cash_Book_IBS_Detail_ID
	FROM AB_Cash_Book_IBS_Detail
    WHERE Transaction_Date = @Date AND
          Bank_Description = @BankDesc AND
          Amount = @Amount AND
          Slu_AW_Active_ID = 1




RETURN @Test









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--------------------------------------------------------------------------
--Description   :sp_AB_Export_GL_Transactions_OOB
--Purpose       :Exports out of balance GL Transactions
--Functionality :SELECT INTO
--Parameters    :
--Date          :2002/09/02
--Authors       :TB
--Version       :1.0.0
--------------------------------------------------------------------------

CREATE             Procedure sp_AB_Export_GL_Transactions_OOB
    (
    	@Company_ID int
    )

AS 

BEGIN

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions_OOB]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_GL_Transactions_OOB]

    
    SELECT *

    INTO AB_GL_Transactions_OOB

    FROM AB_GL_Transactions
    WHERE LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)
          IN (
                 SELECT LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)
                 FROM AB_GL_Transactions
                 GROUP BY LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)
                 HAVING SUM(AB_Transaction_Amount) <> 0
             )
    ORDER BY LEFT(CONVERT(CHAR(19),Date_Captured, 121), 19)

END    
    







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AB_Filter_GL_Filters
--Purpose       :Filters GL Accounts to set GL Filters globally
--Date          :2007/09/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AB_Filter_GL_Filters
	(
    	@CompanyID int,
        @chkOption tinyint,
    	@CategoryID int = -1,
    	@DivisionID int = -1,
    	@GroupID int = -1
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(8000),
            @SQL varchar(8000)

	SET @Filter = ''
    SET @SQL = ''


    --> Sys_AB_Account_Categories
	IF @CategoryID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' Sys_AB_Account_Categories_ID = ' +
                                convert(varchar(20), @CategoryID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' Sys_AB_Account_Categories_ID = ' +
                                convert(varchar(20), @CategoryID)
		END

    --> Lup_AB_Account_Divisions
	IF @DivisionID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' Lup_AB_Account_Divisions_ID = ' +
                                convert(varchar(20), @DivisionID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' Lup_AB_Account_Divisions_ID = ' +
                                convert(varchar(20), @DivisionID)
		END

    --> Lup_AB_Account_Groups
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' Lup_AB_Account_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' Lup_AB_Account_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END



	IF @Filter = ''
		SET @Filter = ' WHERE ' + ' AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)
	ELSE
		SET @Filter = @Filter + ' AND ' + ' AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)

	SET @SQL = 'SELECT '
    SET @SQL = @SQL + ' AB_Accounts_ID AS [ID], '
    SET @SQL = @SQL + ' [Description] AS [Description], '
    SET @SQL = @SQL + ' Account_Number AS [Account No], '
    SET @SQL = @SQL + ' Sys_AB_Account_Categories_ID AS [Category], '
    SET @SQL = @SQL + ' Lup_AB_Account_Divisions_ID AS [Division], '
    SET @SQL = @SQL + ' Lup_AB_Account_Groups_ID AS [Group], '
    SET @SQL = @SQL + ' Slu_AW_Active_ID AS [Active] '

    SET @SQL = @SQL + ' FROM AB_Accounts '
    SET @SQL = @SQL + @Filter

    IF @chkOption = 1
        BEGIN
            SET @SQL = @SQL + ' AND AB_Accounts_ID IN ' +
                                    ' (SELECT DISTINCT a.AB_Accounts_ID ' +
                                    ' FROM AB_Accounts a ' +
                                    '    INNER JOIN Sys_AB_Account_Categories b ' +
                                    '        ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID ' +
                                    ' WHERE a.AW_User_Companies_ID = ' + convert(varchar(20), @CompanyID) + ' AND ' +
                                    '       a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID AND ' +
                                    '      (b.Sys_AB_Account_Types_ID = 3 OR ' +
                                    '       b.Sys_AB_Account_Types_ID = 4)) '
        END


    SET @SQL = @SQL + ' ORDER BY [Description] '

	EXEC (@SQL)



SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


















---------------------------------------------------------------------------------
--Description   :sp_AB_GL_Account_Filter_Lups
--Purpose       :Returns LUPS for GL Account Filters
--Date          :2007/09/24
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE                 Procedure sp_AB_GL_Account_Filter_Lups
    (
    	@Option int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

        IF @Option = 1    --> Category
        	SELECT Sys_AB_Account_Categories_ID AS [ID],
        		  [Description] AS [Category] 
        	FROM Sys_AB_Account_Categories
            ORDER BY [Description] ASC

        ELSE
        IF @Option = 2    --> Division
        	SELECT Lup_AB_Account_Divisions_ID AS [ID],
        		  [Description] AS [Division] 
        	FROM Lup_AB_Account_Divisions	
        	WHERE AW_User_Companies_ID = @Company_ID
--            ORDER BY [Description] ASC

        ELSE
        IF @Option = 3    --> Group
        	SELECT Lup_AB_Account_Groups_ID AS [ID],
        		  [Description] AS [Group] 
        	FROM Lup_AB_Account_Groups	
        	WHERE AW_User_Companies_ID = @Company_ID
--            ORDER BY [Description] ASC

        ELSE
        IF @Option = 4    --> Active
        	SELECT Slu_AW_Active_ID AS [ID],
        		[Description] AS [Active]
        	FROM Slu_AW_Active


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_GL_Source_View_22CJ
--Functionality :Fetch GL Supplier Transaction using [AB_GL_Transactions.AB_Transaction_Ref]
--              :    AB_GL_Transactions JOIN AO_Transactions
--Date          :2006/02/27
--Authors       :TB
--MODS:         :
--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_GL_Source_View_AP]
    (
            @CompanyID int,
            @TranDate datetime,
            @Refno int,
            @TranTypeID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '

    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') + '' - '' + ISNULL(b.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), b.AB_Accounts_ID) + '')''  AS [Account], '

    SET @sql = @sql + ' e.[Description] AS [Month], '
    SET @sql = @sql + ' f.[Description] AS [Year], '
--     SET @sql = @sql + ' a.Slu_AW_Months_ID AS [Month], '
--     SET @sql = @sql + ' a.Slu_AW_Years_ID AS [Year], '

    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + ' d.Supplier_Name AS [Supplier] '
   
    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts b '
    SET @sql = @sql + '         ON b.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Transactions c '
    SET @sql = @sql + '         ON c.AO_Transactions_ID = a.AB_Transaction_Ref '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers d '
    SET @sql = @sql + '         ON d.AO_Suppliers_ID = c.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months e '
    SET @sql = @sql + '         ON e.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years f '
    SET @sql = @sql + '         ON f.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users g '
    SET @sql = @sql + '         ON g.AW_Users_ID = a.[User_ID] '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) = ' + '''' + LEFT(CONVERT(CHAR(10), @TranDate, 121), 10) + '''' + ' '
    SET @sql = @sql + '   AND a.AB_Transaction_Ref = ' + CONVERT(varchar(10), @Refno) + ' '
    --R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
    --SET @sql = @sql + '   AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_GL_Source_View_22CJ
--Functionality :Fetch GL Customer Journals using [AB_GL_Transactions.AB_Transaction_Ref]
--              :    AB_GL_Transactions JOIN AS_Transactions
--Date          :2006/02/27
--Authors       :TB
--MODS:         :
--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_GL_Source_View_AR]
    (
            @CompanyID int,
            @TranDate datetime,
            @Refno int,
            @TranTypeID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '

    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') + '' - '' + ISNULL(b.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), b.AB_Accounts_ID) + '')''  AS [Account], '

    SET @sql = @sql + ' e.[Description] AS [Month], '
    SET @sql = @sql + ' f.[Description] AS [Year], '
--     SET @sql = @sql + ' a.Slu_AW_Months_ID AS [Month], '
--     SET @sql = @sql + ' a.Slu_AW_Years_ID AS [Year], '

    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + ' d.Surname AS [Customer] '

    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts b '
    SET @sql = @sql + '         ON b.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions c '
    SET @sql = @sql + '         ON c.AS_Transactions_ID = a.AB_Transaction_Ref '
    SET @sql = @sql + '     LEFT JOIN AC_Customers d '
    SET @sql = @sql + '         ON d.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months e '
    SET @sql = @sql + '         ON e.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years f '
    SET @sql = @sql + '         ON f.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users g '
    SET @sql = @sql + '         ON g.AW_Users_ID = a.[User_ID] '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) = ' + '''' + LEFT(CONVERT(CHAR(10), @TranDate, 121), 10) + '''' + ' '
    SET @sql = @sql + '   AND a.AB_Transaction_Ref = ' + CONVERT(varchar(10), @Refno) + ' '
	--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
    --SET @sql = @sql + '   AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_GL_Source_View_GL
--Functionality :Fetch GL Year-End using [AB_GL_Transactions.AB_Transaction_Ref]
--Date          :2006/02/27
--Authors       :TB
--MODS:         :
--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_GL_Source_View_GL]
    (
            @CompanyID int,
            @TranDate datetime,
            @Refno int,
            @TranTypeID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '

    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') + '' - '' + ISNULL(b.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), b.AB_Accounts_ID) + '')''  AS [Account], '

    SET @sql = @sql + ' e.[Description] AS [Month], '
    SET @sql = @sql + ' f.[Description] AS [Year], '
--     SET @sql = @sql + ' a.Slu_AW_Months_ID AS [Month], '
--     SET @sql = @sql + ' a.Slu_AW_Years_ID AS [Year], '

    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount] '

    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts b '
    SET @sql = @sql + '         ON b.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months e '
    SET @sql = @sql + '         ON e.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years f '
    SET @sql = @sql + '         ON f.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users g '
    SET @sql = @sql + '         ON g.AW_Users_ID = a.[User_ID] '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) = ' + '''' + LEFT(CONVERT(CHAR(10), @TranDate, 121), 10) + '''' + ' '
    SET @sql = @sql + '   AND a.AB_Transaction_Ref = ' + CONVERT(varchar(10), @Refno) + ' '
    --R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
    --SET @sql = @sql + '   AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '
    

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AB_General_Ledger_Period_Procedure_Insert
--Purpose       :Saves a Monthly and Annual GL Period Procedure
--              :    the month-end Period Procedure date @Date
--Functionality :
--Parameters    :
--Date          :2002/11/02
--Authors       :TB
--Version       :1.0.0
--MODS          :21/12/02 - Added FISCAL YEAR-END procedure
--              :31/12/02 - Added GL Transaction for each Income/Expense account
--              :           and created a NEW GL Transaction Type for Year-End:
--              :           16 = General Journal - Year-End
--              :31/12/02 - Added Return Code @ReturnCode to validate success
--              :01/01/03 - Added Stock Valuation into NEW Stock_Valuation field
--              :02/01/03 - Added SET NEW Opening Balance, Date, Month & Year
--              :           fields during Year-End procedure
--              :02/01/03 - Added Insert a STOCK VALUATION at Month-End
--              :22/01/03 - Moved STOCK VALUATION to CUSTOMER Month-End 
--              :28/02/03 - DEACTIVATE GL ACCOUNT BALANCES and GL TRANSACTIONS
--              :           ONLY UP TO @YearEndMonth ACCOUNTING PERIOD. Enables a
--              :           Year-End to be performed any time after @YearEndMonth
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :14/03/04 - REMOVED GL Year-End
--2004.3.4      :04/03/07 - Changed Stock Valuation to use SysOptions setting
--2004.4.2      :25/10/08 - Added new Standard Cost Inventory Valuation method
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_General_Ledger_Period_Procedure_Insert
	(
        @MonthID int,
        @YearID int,
        @Date DateTime, 
        @Description varchar(50),
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @PeriodProcedureID int,
            @OldCurrentMonthID int,
            @OldCurrentYearID int,
            @NewCurrentMonthID int,
            @NewCurrentYearID int,
            @StockValuation money,
--            @ValuationMethod varchar(250),
            @ControlIndex smallint,
            @ReturnCode int


    SET @PeriodProcedureID = 0


    SET @ReturnCode = 0            --0 = Unsuccessful


    BEGIN TRANSACTION


--     -- Stock Valuation (theoretical now)
--         SELECT @ValuationMethod = ISNULL(Control_Value, '')
--         FROM Sys_AW_Options
--         WHERE Control_Type = 'OptionButton' AND
--               Control_Name = 'optInventoryValuation' AND
--               Control_Index = 0 AND
--               AW_User_Companies_ID = @CompanyID
--     
--         IF @ValuationMethod = 'True'
--             BEGIN
--             	SELECT @StockValuation = SUM(ISNULL(Average_Cost, 0) * ISNULL(On_Hand, 0))
--             	FROM AP_Products
--                 WHERE AW_User_Companies_ID = @CompanyID AND
--                       On_Hand <> 0
--     
--             END
--         ELSE
--             BEGIN
--             	SELECT @StockValuation = SUM(ISNULL(Last_Cost, 0) * ISNULL(On_Hand, 0))
--             	FROM AP_Products
--                 WHERE AW_User_Companies_ID = @CompanyID AND
--                       On_Hand <> 0
--             END


        --> Stock Valuation (theoretical now)
        SELECT @ControlIndex = ISNULL(Control_Index, 0)
        FROM Sys_AW_Options
        WHERE Control_Type = 'OptionButton' AND
              Control_Name = 'optInventoryValuation' AND
              Control_Value = 'True' AND
              AW_User_Companies_ID = @CompanyID


        IF @ControlIndex = 0
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Average_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0

            END
        ELSE
        IF @ControlIndex = 1
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Last_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END
        ELSE
        IF @ControlIndex = 2
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Standard_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END


------------------------------------------------------------------------------
--> Step 1: Insert a Period Procedure record and get its ID
------------------------------------------------------------------------------
    	INSERT AW_Period_Procedures
            (
                Sys_AW_Period_Procedure_Types_ID,
                [Description],
                [Month],
                [Year],
                Month_End_Date,
                Stock_Valuation,
                [User_ID],
                AW_User_Companies_ID
            )
    	VALUES
            (
                4,    -- 4 = GL Period Procedure
                @Description,
                @MonthID,
                @YearID,
                @Date,
                @StockValuation,
                @UserID,
                @CompanyID
            )


        SET @PeriodProcedureID = (SELECT scope_Identity())


        --> Step 2: ADVANCE the Accounting Period
        -----------------------------------------
        SET @OldCurrentMonthID = @MonthID
        SET @OldCurrentYearID = @YearID
        
        SET @NewCurrentMonthID = @OldCurrentMonthID + 1
        SET @NewCurrentYearID = @OldCurrentYearID
    
        IF @NewCurrentMonthID > 12
            BEGIN
                SET @NewCurrentMonthID = 1
                SET @NewCurrentYearID = @OldCurrentYearID + 1
            END

        --> Step 3: SET the NEW Accounting Period
        -----------------------------------------
        UPDATE AW_User_Companies
        SET Slu_AW_Months_ID = @NewCurrentMonthID,
            Slu_AW_Years_ID = @NewCurrentYearID
        WHERE AW_User_Companies_ID = @CompanyID


    SET @ReturnCode = 1


    COMMIT TRANSACTION


RETURN @ReturnCode




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























------------------------------------------------------------------------------
--Description   :sp_AB_General_Ledger_Year_End_Procedure_Insert
--Purpose       :Saves a General Ledger Year-End Period Procedure
--Date          :2004/03/14
--Authors       :TB
--MODS          :
--2004.3.2      :12/09/06 - Changed Stock Valuation to use this period Customer
--              :           Period Procedure valuation
--2004.3.4      :02/01/07 - Removed Step 3: SET the NEW Accounting Period. This
--              :           updates Accounting Period to Current + 1 and could
--              :           advance to a period later than the actual current
--2004.4.3      :23/02/09 - Added new vars @OpeningMonthID and @OpeningYearID,
--              :           set them as the NEXT month AFTER the Year-End month,
--              :           and modified set ALL GL Accounts Opening_Month and
--              :           Opening_Year to these values
--2004.4.8      :15/07/10 - Added SYNC GL ACCOUNT BALANCE to GL TRAN TOTAL
--              :           before starting Y/E procedure
--              :16/07/10 - Removed Stock Valuation as at this Year-End's Customer Period Procedure
------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AB_General_Ledger_Year_End_Procedure_Insert
	(
        @MonthID int,
        @YearID int,
        @Date DateTime, 
        @Description varchar(50),
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @EndPeriod varchar(6),
            @PeriodProcedureID int,
            @ExistingMonthID tinyint,
            @ExistingYearID int,
            @OldCurrentMonthID tinyint,
            @OldCurrentYearID int,
            @NewCurrentMonthID tinyint,
            @NewCurrentYearID int,
            @YearEndMonth int,
            @NetProfit money,
            @Narration varchar(50),
            @Notes varchar(50),
            @ProfitType varchar(20),
            @GLControlAccount int,
            @InsertGLTran bit,
            @NextGLTranID int,
            @JNLHeaderID int,
            @GLAccountID int,
            @GLDescription varchar(100),
            @AccountType int,
            @OrigGLAmount money,
            @NewGLAmount money,
            @StockValuation money,
            @ValuationMethod varchar(250),
            @OpeningMonthID int,
            @OpeningYearID int,
            @ReturnCode int


-- ---------------------------------------------------------------------------------
-- --> SYNC GL ACCOUNT BALANCE to GL TRAN TOTAL - NEW 2004.4.8 - 15/07/10
-- ---------------------------------------------------------------------------------
--     UPDATE AB_Accounts
--     SET AB_Account_Balance = ROUND(AB_Account_Balance, 2)
--     ------------------------------------------------------
--     UPDATE AB_GL_Transactions
--     SET AB_Transaction_Amount = ROUND(AB_Transaction_Amount, 2)
--     -----------------------------------------------------------------------------
--     -- UPDATE GL Account Balance SET GL Account Balance <> SUM(GL Transactions)
--     -----------------------------------------------------------------------------
--     UPDATE AB_Accounts
--     SET AB_Account_Balance = dbo.fn_AB_SUM_GL_Account_Transactions(AB_Accounts_ID, AW_User_Companies_ID)
--     WHERE AW_User_Companies_ID = @CompanyID
-- ---------------------------------------------------------------------------------


    SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
    SET @PeriodProcedureID = 0
    SET @ReturnCode = 0            --0 = Unsuccessful


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

--> Check if this is also a GL Year-End month
    SELECT @YearEndMonth = Year_End_Month_ID,
           @ExistingMonthID = Slu_AW_Months_ID,
           @ExistingYearID = Slu_AW_Years_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    BEGIN TRANSACTION

--         --> Stock Valuation as at this Year-End's Customer Period Procedure
--         SELECT @StockValuation = ISNULL(Stock_Valuation, 0)
--         FROM AW_Period_Procedures
--         WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
--               [Month] = @MonthID AND
--               [Year] = @YearID


------------------------------------------------------------------------------
--> Step 1: Insert a Period Procedure record and get its ID
------------------------------------------------------------------------------
    	INSERT AW_Period_Procedures
            (
                Sys_AW_Period_Procedure_Types_ID,
                [Description],
                [Month],
                [Year],
                Month_End_Date,
                Stock_Valuation,
                [User_ID],
                AW_User_Companies_ID
            )
    	VALUES
            (
                5,    -- 5 = GL Year-End Procedure
                @Description,
                @MonthID,
                @YearID,
                @Date,
                0,
                @UserID,
                @CompanyID
            )


        SET @PeriodProcedureID = (SELECT scope_Identity())


        --> Step 2: ADVANCE the Accounting Period
        -----------------------------------------
        SET @OldCurrentMonthID = @MonthID
        SET @OldCurrentYearID = @YearID
        
        SET @NewCurrentMonthID = @OldCurrentMonthID + 1
        SET @NewCurrentYearID = @OldCurrentYearID
    
        IF @NewCurrentMonthID > 12
            BEGIN
                SET @NewCurrentMonthID = 1
                SET @NewCurrentYearID = @OldCurrentYearID + 1
            END

        SET @OpeningMonthID = @NewCurrentMonthID
        SET @OpeningYearID = @NewCurrentYearID

    --> Set the CURRENT ACCOUNTING PERIOD back to what it was before this Year-End
        IF @ExistingMonthID > @NewCurrentMonthID
            BEGIN
                SET @NewCurrentMonthID = @ExistingMonthID
            END

        IF @ExistingYearID > @NewCurrentYearID
            BEGIN
                SET @NewCurrentYearID = @ExistingYearID
            END
    --------------------------------------------------------------------------

--         --> Step 3: SET the NEW Accounting Period
--         -----------------------------------------
--         UPDATE AW_User_Companies
--         SET Slu_AW_Months_ID = @NewCurrentMonthID,
--             Slu_AW_Years_ID = @NewCurrentYearID
--         WHERE AW_User_Companies_ID = @CompanyID


------------------------------------------------------------------------------
--> Step 5: Do a YEAR-END procedure if required
------------------------------------------------------------------------------
        IF @YearEndMonth = @MonthID
            BEGIN

            --> Get Net Income [NI] for the year -------------------
                SELECT @NetProfit = ISNULL(SUM(a.AB_Transaction_Amount), 0)
                FROM AB_GL_Transactions a
                    INNER JOIN AB_Accounts b
                        ON a.AB_Accounts_ID = b.AB_Accounts_ID
                    INNER join Sys_AB_Account_Categories c
                        ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                WHERE c.Sys_AB_I1_ID = 1 AND
                      dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
                      a.Slu_AW_Active_ID = 1 AND
                      a.AW_User_Companies_ID = @CompanyID


                IF @NetProfit < 0
                    SET @ProfitType = 'Net Profit'
                ELSE
                    SET @ProfitType = 'Net Loss'


                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 501        --RESERVES CONTROL

                SET @Narration = 'Year-End transfer of ' + @ProfitType + ' to Reserves'
                SET @Notes = ''

            --> Create NORMAL JOURNAL header for the Year-End
 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                        16,        --General Journal - Year-End
                        @CompanyID

            --> Create Reserves Journal Header for Year-End
				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                        @Date,
                        @NextGLTranID,
                        @Narration,
                        @MonthID,
                        @YearID,
                        @UserID,
                        @CompanyID


            --> Create Reserves Journal Detail for Year-End
                EXEC sp_AB_Insert_Journal_Detail
                        @JNLHeaderID,
                        @GLControlAccount,
                        @NetProfit,
                        @Notes,
                        @UserID,
                        @CompanyID,
                        @InsertGLTran

            --> Create GL TRANSACTION for Year-End Net Profit
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        16,
                        @GLControlAccount,
                        @Date,
                        'Trf to Reserves',
                        @MonthID,
                        @YearID,
                        @NextGLTranID,
                        @NetProfit,
                        @UserID,
                        @CompanyID


        --> CURSOR START -------------------------------------------------

             --> Define a CURSOR for Income and Expense accounts
            	DECLARE Accounts_Cursor CURSOR FOR
                        SELECT DISTINCT a.AB_Accounts_ID,
                                        MAX(b.Description),
                                        ISNULL(SUM(a.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions a
                            INNER JOIN AB_Accounts b
                                ON a.AB_Accounts_ID = b.AB_Accounts_ID
                            INNER JOIN Sys_AB_Account_Categories c
                                ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                        WHERE c.Sys_AB_I1_ID = 1 AND
                              dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
                              a.Slu_AW_Active_ID = 1 AND
                              a.AW_User_Companies_ID = @CompanyID
                        GROUP BY a.AB_Accounts_ID
                        ORDER BY MAX(b.Description)
            
            	OPEN Accounts_Cursor
            
                	FETCH NEXT FROM Accounts_Cursor 
                	INTO
                        @GLAccountID,
                        @GLDescription,
                        @OrigGLAmount
                	
                	WHILE @@FETCH_STATUS = 0
                    	BEGIN
                            SET @NewGLAmount = @OrigGLAmount * -1
            
                        --> Create Income/Expense JOURNAL DETAIL for Year-End
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLAccountID,
                                    @NewGLAmount,
                                    @Notes,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                        --> Create Income/Expense Year-End close off GL TRANSACTION
                        --  AND UPDATES THE GL ACCOUNT BALANCE WITH PRIOR BALANCE 
                        --  WHILE RETAINING ACCOUNT BALANCE FOR GL TRANSACTIONS
                        --  POSTED AFTER @YearEndMonth (this note added 28/02/03)
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    16,
                                    @GLAccountID,
                                    @Date,
                                    'Trf to Reserves',
                                    @MonthID,
                                    @YearID,
                                    @NextGLTranID,
                                    @NewGLAmount,
                                    @UserID,
                                    @CompanyID

                        	FETCH NEXT FROM Accounts_Cursor 
                        	INTO
                                @GLAccountID,
                                @GLDescription,
                                @OrigGLAmount
                
                    	END
            	
            	CLOSE Accounts_Cursor
            
            	DEALLOCATE Accounts_Cursor

        --> CURSOR END ---------------------------------------------

            --> DE-ACTIVATE Income & Expense accounts
                UPDATE a
                SET a.Slu_AW_Active_ID = 2    -- 2 = Disabled
                FROM AB_GL_Transactions a
                    INNER JOIN AB_Accounts b
                        ON a.AB_Accounts_ID = b.AB_Accounts_ID
                    INNER join Sys_AB_Account_Categories c
                        ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                WHERE c.Sys_AB_I1_ID = 1 AND
                      dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Slu_AW_Active_ID <> 2


            --> Update Period Procedure with Year-End date
            	UPDATE AW_Period_Procedures
                SET Year_End_Date = @Date
                WHERE AW_Period_Procedures_ID = @PeriodProcedureID


    --> SET the OPENING BALANCE AS AT @YearEndMonth,
    --  NEW FIN YEAR START DATE and PERIOD

        --> CURSOR START -------------------------------------------------

            --> Define a CURSOR for ALL GL Accounts
            	DECLARE All_GL_Accounts_Cursor CURSOR FOR
                    SELECT DISTINCT a.AB_Accounts_ID,
                                    MAX(c.Sys_AB_I1_ID),
                                    ISNULL(SUM(a.AB_Transaction_Amount), 0)
                    FROM AB_GL_Transactions a
                        LEFT JOIN AB_Accounts b
                            ON a.AB_Accounts_ID = b.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories c
                            ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                    WHERE dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
                          a.Slu_AW_Active_ID = 1 AND
                          a.AW_User_Companies_ID = @CompanyID
                    GROUP BY a.AB_Accounts_ID

            	OPEN All_GL_Accounts_Cursor
            
                	FETCH NEXT FROM All_GL_Accounts_Cursor 
                	INTO
                        @GLAccountID,
                        @AccountType,
                        @OrigGLAmount
                	
                	WHILE @@FETCH_STATUS = 0
                    	BEGIN
                            IF @AccountType = 1    --Income/Expense account
                                BEGIN
                                    SET @NewGLAmount = 0
                                END
                            ELSE                   --Asset/Liability account
                                BEGIN
                                    SET @NewGLAmount = @OrigGLAmount
                                END

                            UPDATE AB_Accounts
                            SET Opening_Balance = @NewGLAmount,
                                Opening_Date = @Date,
                                Opening_Month = @OpeningMonthID,
                                Opening_Year = @OpeningYearID
                            WHERE AB_Accounts_ID = @GLAccountID

                        	FETCH NEXT FROM All_GL_Accounts_Cursor 
                        	INTO
                                @GLAccountID,
                                @AccountType,
                                @OrigGLAmount
                
                    	END
            	
            	CLOSE All_GL_Accounts_Cursor
            
            	DEALLOCATE All_GL_Accounts_Cursor

        --> CURSOR END ---------------------------------------------

        --NEW 09/03/03----------------------------------
        --Ensure that all accounts are updated with this
        ------------------------------------------------
            UPDATE AB_Accounts
            SET Opening_Date = @Date,
                Opening_Month = @OpeningMonthID,
                Opening_Year = @OpeningYearID
        ------------------------------------------------


            END    --@YearEndMonth = @MonthID


        SET @ReturnCode = 1


    COMMIT TRANSACTION


SET NOCOUNT OFF


RETURN @ReturnCode




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description	:sp_AB_Get_Account_ID_From_Description
--Purpose       :Gets GL Account ID from GL Description
--Date			:2009/04/14
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Get_Account_ID_From_Description
	(
		@CompanyID int,
        @GLName varchar(50),
        @AccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @AccountID = AB_Accounts_ID
    FROM AB_Accounts
    WHERE Description = @GLName AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














----------------------------------------------------------------------------
--Description   :dbo.sp_AB_Get_Batch_Cashbook_Descriptions
--Purpose       :Retrieves GL Account and Tax Method descriptions
--Date          :2005/10/14
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Get_Batch_Cashbook_Descriptions
    (
        @CompanyID int,
        @GLAccountID int,
        @TaxMethodID tinyint,
        @GLAccount varchar(50) OUTPUT,
        @TaxMethod varchar(10) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @GLAccount = Description
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID AND
          AB_Accounts_ID = @GLAccountID


    SELECT @TaxMethod = Description
    FROM Sys_AW_Tax_Methods
    WHERE Sys_AW_Tax_Methods_ID = @TaxMethodID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AB_Get_COS_Control_ID
--Purpose       :Gets Cost-of-Sales Control Account ID (Control 106)
--Date			:2005/10/23
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_COS_Control_ID
	(
		@CompanyID int,
        @GLControlAccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @GLControlAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 106 AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Cash_Book_IBS_Map_Edit_Splits
--Purpose       :Gets IBS CashBook Mapping Splits data
--Functionality :
--Date          :2010/03/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Get_Cash_Book_IBS_Map_Edit_Splits
    (
        @CompanyBanksID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_IBS_Map_Splits_ID AS [SplitMapID],
           AW_Company_Banks_ID AS [CompanyBanksID],
           AB_Cash_Book_IBS_Map_ID AS [MapID],
           AB_Accounts_ID AS [GL Acct],
           Sys_AW_Tax_Methods_ID AS [Method],
           Amount AS [Split Amount],
           Tax_Amount AS [Split Tax],
           Net_Amount AS [Split Net]
    FROM AB_Cash_Book_IBS_Map_Splits
    WHERE AW_User_Companies_ID = @CompanyID AND
          AW_Company_Banks_ID = @CompanyBanksID




SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Cash_Book_IBS_Map_Splits
--Purpose       :Gets IBS CashBook Mapping Splits data for ONE MapID
--Functionality :
--Date          :2010/03/18
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AB_Get_Cash_Book_IBS_Map_Splits
    (
        @MapID int,
        @CompanyBanksID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_IBS_Map_Splits_ID AS [SplitMapID],
           AW_Company_Banks_ID AS [CompanyBanksID],
           AB_Cash_Book_IBS_Map_ID AS [MapID],
           AB_Accounts_ID AS [GL Acct],
           Sys_AW_Tax_Methods_ID AS [Method],
           Amount AS [Split Amount],
           Tax_Amount AS [Split Tax],
           Net_Amount AS [Split Net]
    FROM AB_Cash_Book_IBS_Map_Splits
    WHERE AB_Cash_Book_IBS_Map_ID = @MapID AND
          AW_Company_Banks_ID = @CompanyBanksID
    ORDER BY [MapID], [SplitMapID], [CompanyBanksID]




SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















----------------------------------------------------------------------------
--Description   :sp_AB_Get_Cash_Flow_Descriptions
--Purpose       :Get Tax Method descriptions
--Date          :2011/02/27
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Get_Cash_Flow_Descriptions
    (
        @TaxMethodID tinyint,
        @TaxMethod varchar(10) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @TaxMethod = Description
    FROM Sys_AW_Tax_Methods
    WHERE Sys_AW_Tax_Methods_ID = @TaxMethodID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description   :sp_AB_Get_Cashbook_IBS_Descriptions
--Purpose       :Get Tran Type, GL Account,Tax Method descriptions
--Date          :2010/02/28
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Get_Cashbook_IBS_Descriptions
    (
        @CompanyID int,
        @TranTypeID tinyint,
        @GLAccountID int,
        @TaxMethodID tinyint,
        @TranType varchar(20) OUTPUT,
        @GLAccount varchar(50) OUTPUT,
        @TaxMethod varchar(10) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TranType = Transaction_Code
    FROM Sys_AB_Transaction_Types
    WHERE Sys_AB_Transaction_Types_ID = @TranTypeID


    SELECT @GLAccount = Description
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID AND
          AB_Accounts_ID = @GLAccountID


    SELECT @TaxMethod = Description
    FROM Sys_AW_Tax_Methods
    WHERE Sys_AW_Tax_Methods_ID = @TaxMethodID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















----------------------------------------------------------------------------
--Description   :sp_AB_Get_Cashbook_IBS_Split_Descriptions
--Purpose       :Get GL Account and Tax Method descriptions
--Date          :2010/03/13
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Get_Cashbook_IBS_Split_Descriptions
    (
        @CompanyID int,
        @GLAccountID int,
        @TaxMethodID tinyint,
        @GLAccount varchar(50) OUTPUT,
        @TaxMethod varchar(10) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @GLAccount = Description
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID AND
          AB_Accounts_ID = @GLAccountID


    SELECT @TaxMethod = Description
    FROM Sys_AW_Tax_Methods
    WHERE Sys_AW_Tax_Methods_ID = @TaxMethodID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Company_Bank_Details
--Purpose       :Get the details of a AW_Company_Banks row
--Date          :2010/02/13
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Get_Company_Bank_Details
    (
        @CompanyBanksID int,
        @CompanyID int,
        @BankID smallint OUTPUT,
        @BankName varchar(50) OUTPUT,
        @BankGLAccountID int OUTPUT,
        @BankGLBalance money OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @BankID = cb.Slu_AW_Banks_ID, 
           @BankName = ISNULL(b.[Description], ''),
           @BankGLAccountID = cb.AB_Accounts_ID
    FROM AW_Company_Banks cb
        INNER JOIN Slu_AW_Banks b
            ON b.Slu_AW_Banks_ID = cb.Slu_AW_Banks_ID
    WHERE cb.AW_Company_Banks_ID = @CompanyBanksID AND
          cb.AW_User_Companies_ID = @CompanyID

    
    SELECT @BankGLBalance = ISNULL(AB_Account_Balance, 0)
    FROM AB_Accounts
    WHERE AB_Accounts_ID = @BankGLAccountID



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-----------------------------------------------------------------------------
--Description   :sp_AB_Get_Ending_GL_Period
--Purpose       :Returns YEAR(4) and MONTH(2) as @EndPeriod 6-digit number
--Used in       :to ORDER GL transactions in Accounting Periods
--              :
--              :
--Parameters    :
--Date          :01 JAN 2003
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE        PROCEDURE sp_AB_Get_Ending_GL_Period
    (
        @MonthID tinyint,
        @YearID int,
        @EndPeriod varchar(6) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Fiscal_Span
--Purpose       :Get the START and END of a FISCAL YEAR
--              :    for the SELECTED ACCOUNTING PERIOD
--Parameters    :
--Date          :2003/03/05
--Authors       :TB
--MODS:         :
--2004.4.3      :13/03/09 - Modified @YearEndMonthID validation by INITIALIZING it to ZERO
--              :           and REMOVING its NULL validation
--RL	V6.0	2014-10-14 - If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Get_Fiscal_Span]
	(
        @CompanyID int,
        @YearEndMonthID int OUTPUT,
        @StartMonthID int OUTPUT,
        @StartYearID int OUTPUT,
        @SelectedMonthID int OUTPUT,
        @SelectedYearID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @YearEndMonthID = 0

    SELECT @YearEndMonthID = Year_End_Month_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

--	IF @YearEndMonthID IS NULL OR @YearEndMonthID = 0
    IF @YearEndMonthID = 0
        BEGIN
            SET @YearEndMonthID = 2
        END

	--RL 2014-10-14 V6.0 If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan
	IF @YearEndMonthID = 12
		SET @StartMonthID = 1								--FIRST month of the Financial Year	
	ELSE
		SET @StartMonthID = @YearEndMonthID + 1            --FIRST month of the Financial Year

    IF @SelectedMonthID <= @YearEndMonthID
        BEGIN
            SET @StartYearID = @SelectedYearID - 1
        END
    ELSE
    IF @SelectedMonthID > @YearEndMonthID
        BEGIN
            SET @StartYearID = @SelectedYearID
        END
     
     --RL 2014-10-14 V6.0 If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan of current year  
     IF @YearEndMonthID = 12
       SET @StartYearID = @SelectedYearID
        
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description	:sp_AB_Get_GL_Account_Activity_Count
--Purpose       :Counts table activity for ONE AB_Accounts_ID
--Date			:2009/03/14
--Authors		:TB
--MODS          :
--2004.4.7      :23/08/09 - Removed REDUNDANT AP_Stock_Transfers 
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Get_GL_Account_Activity_Count
	(
		@GLAccountID int,
        @CompanyID int,
        @ActiveTables int OUTPUT,
        @ActiveRows int OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @CNT int


    SET @ActiveTables = 0
    SET @ActiveRows = 0
    SET @CNT = 0


-- Accountant
    SELECT @CNT = count(*)
    FROM AB_Budgets
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AB_Cash_Book_Batches
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AB_Cash_Book_Transaction_Details
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AB_Control_Accounts
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AB_GL_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AB_Journal_Details
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AB_Recurring_Details
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

-- Suppliers
    SELECT @CNT = count(*)
    FROM AO_GRV_Details
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Remittance_Details_Temp
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Statement_Details
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Transactions_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

-- Sales
    SELECT @CNT = count(*)
    FROM AS_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AS_Transactions_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

-- System
    SELECT @CNT = count(*)
    FROM AW_Company_Banks
    WHERE AB_Accounts_ID = @GLAccountID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0





SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :dbo.sp_AB_Get_GL_Account_BFWD
--Purpose       :Retrieves GL Account Opening Balance BEFORE a PERIOD
--Parameters    :
--Date          :2004/12/28
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_GL_Account_BFWD
    (
        @GLAccountID int,
        @OpeningPeriod varchar(6),
        @BFWD money OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @BFWD = SUM(AB_Transaction_Amount)
    FROM AB_GL_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @OpeningPeriod










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AB_Get_GL_Control_Account_ID
--Purpose       :Gets one GL Control Account ID from input Control_Number
--Date			:2005/10/23
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_GL_Control_Account_ID
	(
		@CompanyID int,
        @ControlNumber smallint,
        @GLControlAccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @GLControlAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = @ControlNumber AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_AB_Get_GL_Period_String
--Purpose       :Returns YEAR(4) and MONTH(2) as 6-digit integer as STRING
--Date          :2004/12/28
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Get_GL_Period_String
    (
        @MonthID tinyint,
        @YearID int,
        @PeriodNo varchar(6) OUTPUT
    )

AS


SET NOCOUNT ON


    SELECT @PeriodNo = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


--     DECLARE @Monthstr varchar(2),
--             @Yearstr varchar(4)
-- 
--     SET @Yearstr = RTRIM(LTRIM(CONVERT(varchar(4), @YearID)))
--     SET @Monthstr = RTRIM(LTRIM(CONVERT(varchar(2), @MonthID)))
-- 
--     IF LEN(@Yearstr) = 1
--         set @Yearstr = '000' + @Yearstr
--     ELSE
--     IF LEN(@Yearstr) = 2
--         set @Yearstr = '00' + @Yearstr
--     ELSE
--     IF LEN(@Yearstr) = 3
--         set @Yearstr = '0' + @Yearstr
-- 
--     IF LEN(@Monthstr) = 1
--         set @Monthstr = '0' + @Monthstr
-- 
--     SET @PeriodNo = @Yearstr + @Monthstr


    RETURN @PeriodNo









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :dbo.sp_AB_Get_Last_GL_Year_End_Period
--Purpose       :Retrieves GL Account Opening Balance BEFORE a PERIOD
--Parameters    :
--Date          :2004/12/28
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_Last_GL_Year_End_Period
    (
        @CompanyID int,
        @MonthID tinyint,
        @YearID int,
        @PeriodNo varchar(6) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @EndPeriod varchar(6),
            @Month tinyint,
            @Year int


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    SELECT TOP 1 @Month = [Month],
                 @Year = [Year]
    FROM AW_Period_Procedures
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Period_Procedure_Types_ID = 5 AND
          dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID) <= @EndPeriod
    ORDER BY dbo.fn_AB_Get_Ending_GL_Period([Month], [Year]) DESC

    IF (@Month = 0 OR @Month IS NULL) OR
       (@Year = 0 OR @Year IS NULL)
        BEGIN
            SET @Month = 1
            SET @Year = 1
        END


    SET @PeriodNo = dbo.fn_AB_Get_Ending_GL_Period(@Month, @Year)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Next_Transaction_Number
--Purpose       :INCREMENTS COUNTER with next available AB Transaction Number
--Functionality :Tables: Sys_AB_Transaction_Numbers
--Parameters    :
--Date          :2002/01/30
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Get_Next_Transaction_Number
    (
        @TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @Num int
    
    SELECT @Num = ISNULL(Last_Number, 0)
    FROM Sys_AB_Transaction_Numbers
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AB_Transaction_Types_ID = @TransactionType
    
    UPDATE Sys_AB_Transaction_Numbers
    SET Last_Number = @Num + 1 
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AB_Transaction_Types_ID = @TransactionType
    
    SET @TransactionNumber = CONVERT(varchar(15), @Num + 1)

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Opening_Closing_GL_Balance
--Purpose       :Retrieve the OPENING and CLOSING GL Account Balances
--              :    from a SELECTED ACCOUNTING PERIOD
--Date          :2005/01/16
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Get_Opening_Closing_GL_Balance
    (
        @GLAccountID int,
        @MonthsID tinyint,
        @YearsID int,
        @CompanyID int,
        @BFWD money OUTPUT,
        @Balance money OUTPUT
    )

AS

SET NOCOUNT ON


    DECLARE @EndPeriod varchar(6),
            @Month tinyint,
            @Year int


    SET @Month = @MonthsID - 1
    SET @Year = @YearsID

    IF @Month <= 0
        BEGIN
            SET @Month = 12
            SET @Year = @Year - 1
        END


    IF (@Month = 0 OR @Month IS NULL) OR
       (@Year = 0 OR @Year IS NULL)
        BEGIN
            SET @Month = 1
            SET @Year = 1
        END


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@Month, @Year)


------------------------------------------------------------------------------------------------------
-- This is VERY SLOW
------------------------------------------------------------------------------------------------------
--     SELECT @BFWD = CONVERT(money, ISNULL(dbo.fn_AB_BFWD_GL_Account(AB_Accounts_ID, @EndPeriod), 0))
--     FROM AB_GL_Transactions
--     WHERE AB_Accounts_ID = @GLAccountID
------------------------------------------------------------------------------------------------------


    SELECT @BFWD = SUM(AB_Transaction_Amount)
    FROM AB_GL_Transactions
    WHERE AB_Accounts_ID = @GLAccountID AND
          dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod

    
    SELECT @Balance = ISNULL(AB_Account_Balance, 0)
    FROM AB_Accounts
    WHERE AB_Accounts_ID = @GLAccountID



SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AB_Get_Purchases_Control_ID
--Purpose       :Gets Purchases Control Account ID (Control 301)
--Date			:2005/10/23
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_Purchases_Control_ID
	(
		@CompanyID int,
        @GLControlAccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @GLControlAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 301 AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   : sp_AB_Get_Recurring_Journal
--Purpose       : Retrieves a list of Recurring Journals headers
--Functionality :
--Parameters    :
--Date          : 2002/12/27
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE      PROCEDURE sp_AB_Get_Recurring_Journal
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

	SELECT
        a.AB_Recurring_ID AS [ID], 
        a.Recurring_Date AS [Date], 
        c.[Description] AS [Month], 
        d.[Description] AS [Year], 
        a.Recurring_Reference AS [Ref],
        a.Recurring_Narration AS [Narration], 
        b.UserName AS [User],
        a.Slu_AW_Active_ID AS [Active], 	
        a.Date_Captured AS [Date Captured], 
        a.AW_User_Companies_ID AS [Company] 
	FROM AB_Recurring a
        LEFT JOIN AW_Users b
            ON a.[User_ID] = b.AW_Users_ID
        LEFT JOIN Slu_AW_Months c
            ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years d
            ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID
    WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   : sp_AB_Get_Recurring_Journal_Details
--Purpose       : Retrieves a Recurring Journals Details
--Functionality :
--Parameters    :
--Date          : 2002/12/27
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE    Procedure sp_AB_Get_Recurring_Journal_Details
    (
        @RecurringID int
    )

AS

SET NOCOUNT ON

	SELECT
        AB_Recurring_Details_ID AS [ID], 
        AB_Recurring_ID AS [FK ID], 
        AB_Accounts_ID AS [GL Account], 
        Amount AS [Amount], 
        Notes AS [Notes], 
        Slu_AW_Active_ID AS [Active], 
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company] 
	FROM AB_Recurring_Details
    WHERE AB_Recurring_ID = @RecurringID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AB_Get_Sales_Control_ID
--Purpose       :Gets Sales Control Account ID (Control 102)
--Date			:2005/10/23
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_Sales_Control_ID
	(
		@CompanyID int,
        @GLControlAccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @GLControlAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 102 AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AB_Get_This_Accounting_Period
--Purpose       :Fetch the Current Accounting Period ID's for the Company
--Date          :2007/01/01
--Authors       :TB
--MODS          :
--2004.5.0      :07/04/11 - Changed @MonthID type from int to tinyint to match actual type
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Get_This_Accounting_Period
	(
        @CompanyID int,
        @MonthID tinyint OUTPUT,
        @YearID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @MonthID = ISNULL(Slu_AW_Months_ID, 1),
           @YearID = ISNULL(Slu_AW_Years_ID, 1)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


        
SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description	:sp_AB_Get_Trade_Creditors_Payment_Clearing_ID
--Purpose       :Gets Trade Creditors Payment Clearing account ID (Control 207)
--Date			:2004/12/13
--Authors		:TB
--Version		:1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Get_Trade_Creditors_Payment_Clearing_ID
	(
		@CompanyID int,
        @GLControlAccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @GLControlAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 207 AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AB_Get_Trade_Debtors_Payment_Clearing_ID
--Purpose       :Gets Trade Debtors Payment Clearing account ID (Control 105)
--Date			:2005/06/09
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Get_Trade_Debtors_Payment_Clearing_ID
	(
		@CompanyID int,
        @GLControlAccountID int OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @GLControlAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 105 AND
          AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description	:sp_AB_Get_VAT_Control_Account
--Purpose       :Gets VAT Control Account Name
--Date			:2004/11/07
--Authors		:TB
--Version		:1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Get_VAT_Control_Account
	(
		@CompanyID int,
        @GLControlAccount varchar(50) OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @GLControlAccount = b.[Description]
    FROM AB_Control_Accounts a
        INNER JOIN AB_Accounts b
            ON a.AB_Accounts_ID = b.AB_Accounts_ID
    WHERE a.Control_Number = 401 AND    --VAT Control
          a.AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Bank_IBS_Rules
--Purpose       :Insert IBS Bank Rules for ONE Bank
--Date          :22 MAR 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Insert_Bank_IBS_Rules
    (
        @IBSRuleID int,
        @CompanyBanksID int,
        @HeaderRows tinyint,
        @FooterRows tinyint,
        @Delimiter varchar(10),
        @DateFieldNo tinyint,
        @DescriptionFieldNo tinyint,
        @AmountFieldNo tinyint,
        @DateFormatID tinyint,
        @CombineFieldNos varchar(10),
        @TranTypeFieldNo varchar(10),
        @ChequeFieldNo varchar(10),
        @ChequeIdentifier varchar(10),
        @ChequeNoFrom tinyint,
        @ChequeNoTo tinyint,
        @UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @MappingID int,
            @NewRuleID int

    SET @MappingID = 0
    SET @NewRuleID = 0

    IF @IBSRuleID > 0
        BEGIN
            UPDATE Slu_AB_Bank_IBS_Rules
            SET AW_Company_Banks_ID = @CompanyBanksID,
                Header_Rows = @HeaderRows,
                Footer_Rows = @FooterRows,
                Delimiter = @Delimiter,
                Date_Field_No = @DateFieldNo,
                Description_Field_No = @DescriptionFieldNo,
                Amount_Field_No = @AmountFieldNo,
                Slu_AW_Date_Format_ID = @DateFormatID,
                Combine_Field_Nos = @CombineFieldNos,
                TranType_Field_No = @TranTypeFieldNo,
                Cheque_Field_No = @ChequeFieldNo,
                Cheque_Identifier = @ChequeIdentifier,
                Cheque_No_From = @ChequeNoFrom,
                Cheque_No_To = @ChequeNoTo,
                [User_ID] = @UserID
            WHERE Slu_AB_Bank_IBS_Rules_ID = @IBSRuleID
        END
    ELSE
        BEGIN
            INSERT Slu_AB_Bank_IBS_Rules
            (
                AW_Company_Banks_ID,
                Header_Rows,
                Footer_Rows,
                Delimiter,
                Date_Field_No,
                Description_Field_No,
                Amount_Field_No,
                Slu_AW_Date_Format_ID,
                Combine_Field_Nos,
                TranType_Field_No,
                Cheque_Field_No,
                Cheque_Identifier,
                Cheque_No_From,
                Cheque_No_To,
                [User_ID]
            )
            VALUES
            (
                @CompanyBanksID,
                @HeaderRows,
                @FooterRows,
                @Delimiter,
                @DateFieldNo,
                @DescriptionFieldNo,
                @AmountFieldNo,
                @DateFormatID,
                @CombineFieldNos,
                @TranTypeFieldNo,
                @ChequeFieldNo,
                @ChequeIdentifier,
                @ChequeNoFrom,
                @ChequeNoTo,
                @UserID
            )

            SELECT @NewRuleID = Scope_Identity()
        END


RETURN @NewRuleID

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_IBS_Detail
--Purpose       :Inserts IBS Cash Book Detail
--Date          :2010/02/25
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AB_Insert_Cash_Book_IBS_Detail
    (
        @IBSHeaderID int,
        @Post bit,
        @TranTypeID tinyint,
        @TranDate datetime,
        @RefNo varchar(20),
        @GLAccountID int,
        @TaxMethodID tinyint,
        @PostDescription varchar(50),
        @Amount money,
        @Tax money,
        @Net money,
        @Comments varchar(50),
        @BankDescription varchar(100),
        @DatePosted datetime,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @DetailID int


    SET @DetailID = 0


	BEGIN TRANSACTION

    	BEGIN 
    		INSERT INTO AB_Cash_Book_IBS_Detail
                (
                    AB_Cash_Book_IBS_Header_ID,
                    Post,
                    Sys_AB_Transaction_Types_ID,
                    Transaction_Date,
                    Ref_No,
                    AB_Accounts_ID,
                    Sys_AW_Tax_Methods_ID,
                    Post_Description,
                    Amount,
                    Tax_Amount,
                    Net_Amount,
                    Comments,
                    Bank_Description,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
    		VALUES
                (
                    @IBSHeaderID,
                    @Post,
                    @TranTypeID,
                    @TranDate,
                    @RefNo,
                    @GLAccountID,
                    @TaxMethodID,
                    @PostDescription,
                    @Amount,
                    @Tax,
                    @Net,
                    @Comments,
                    @BankDescription,
                    @DatePosted,
                    @UserID,
                    @CompanyID
                )
    		
            SELECT @DetailID = Scope_Identity() 
    	END			

	COMMIT TRAN



	
RETURN @DetailID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_IBS_Detail_Splits
--Purpose       :Inserts IBS Cash Book Detail Splits
--Date          :2010/03/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AB_Insert_Cash_Book_IBS_Detail_Splits
    (
        @IBSHeaderID int,
        @IBSDetailID int,
        @GLAccountID int,
        @TaxMethodID tinyint,
        @Amount money,
        @Tax money,
        @Net money,
        @DatePosted datetime,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @SplitID int


    SET @SplitID = 0


	BEGIN TRANSACTION

    	BEGIN 
    		INSERT INTO AB_Cash_Book_IBS_Detail_Splits
                (
                    AB_Cash_Book_IBS_Header_ID,
                    AB_Cash_Book_IBS_Detail_ID,
                    AB_Accounts_ID,
                    Sys_AW_Tax_Methods_ID,
                    Amount,
                    Tax_Amount,
                    Net_Amount,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
    		VALUES
                (
                    @IBSHeaderID,
                    @IBSDetailID,
                    @GLAccountID,
                    @TaxMethodID,
                    @Amount,
                    @Tax,
                    @Net,
                    @DatePosted,
                    @UserID,
                    @CompanyID
                )
    		
            SELECT @SplitID = Scope_Identity() 
    	END			

	COMMIT TRAN



	
RETURN @SplitID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_IBS_Header
--Purpose       :Inserts IBS Cash Book Header
--Date          :2010/02/25
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Insert_Cash_Book_IBS_Header
    (
        @PostType varchar(50),
        @CompanyBanksID int,
        @BankID smallint,
        @DatePosted datetime,
        @StartDate datetime,
        @EndDate datetime,
        @MonthsID tinyint,
        @YearsID smallint,
        @ImportFile varchar(50),
        @AutoRecon tinyint,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @HeaderID int


    SET @HeaderID = 0
    SET @ImportFile = LEFT(@ImportFile, 50)


	INSERT INTO AB_Cash_Book_IBS_Header
        (
            Posting_Type,
            AW_Company_Banks_ID,
            Slu_AW_Banks_ID,
            Date_Posted,
            Start_Date,
            End_Date,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Import_Filename,
            Auto_Recon,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
	VALUES 
        (
            @PostType,
            @CompanyBanksID,
            @BankID,
            @DatePosted,
            @StartDate,
            @EndDate,
            @MonthsID,
            @YearsID,
            @ImportFile,
            @AutoRecon,
            @DatePosted,
        	@UserID,
            @CompanyID
        )

	SELECT @HeaderID = Scope_Identity() 



RETURN @HeaderID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_IBS_Map_Splits
--Purpose       :Inserts IBS Cash Book Detail Splits
--Date          :2010/03/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AB_Insert_Cash_Book_IBS_Map_Splits
    (
        @SplitMapID int,
        @CompanyBanksID int,
        @MapID int,
        @GLAccountID int,
        @TaxMethodID tinyint,
        @Amount money,
        @Tax money,
        @Net money,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @OldMapSplitID int,
            @NewMapSplitID int


    SET @OldMapSplitID = 0
    SET @NewMapSplitID = 0


    IF @SplitMapID > 0
        BEGIN
            UPDATE AB_Cash_Book_IBS_Map_Splits
            SET AB_Accounts_ID = @GLAccountID,
                Sys_AW_Tax_Methods_ID = @TaxMethodID,
                Amount = @Amount,
                Tax_Amount = @Tax,
                Net_Amount = @Net
            WHERE AB_Cash_Book_IBS_Map_ID = @SplitMapID
        END
    ELSE
    	BEGIN
            SET @OldMapSplitID = 0

            SELECT @OldMapSplitID = AB_Cash_Book_IBS_Map_Splits_ID
            FROM AB_Cash_Book_IBS_Map_Splits
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AW_Company_Banks_ID = @CompanyBanksID AND
                  AB_Cash_Book_IBS_Map_ID = @MapID AND
                  AB_Accounts_ID = @GLAccountID AND
                  Sys_AW_Tax_Methods_ID = @TaxMethodID AND
                  Amount = @Amount AND
                  Tax_Amount = @Tax AND
                  Net_Amount = @Net

            IF @OldMapSplitID = 0
                BEGIN
            		INSERT INTO AB_Cash_Book_IBS_Map_Splits
                        (
                            AW_Company_Banks_ID,
                            AB_Cash_Book_IBS_Map_ID,
                            AB_Accounts_ID,
                            Sys_AW_Tax_Methods_ID,
                            Amount,
                            Tax_Amount,
                            Net_Amount,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID
                        )
            		VALUES
                        (
                            @CompanyBanksID,
                            @MapID,
                            @GLAccountID,
                            @TaxMethodID,
                            @Amount,
                            @Tax,
                            @Net,
                            getdate(),
                            @UserID,
                            @CompanyID
                        )
            		
                    SELECT @NewMapSplitID = Scope_Identity() 
                END
            ELSE
                BEGIN
                    UPDATE AB_Cash_Book_IBS_Map_Splits
                    SET AW_Company_Banks_ID = @CompanyBanksID,
                        AB_Cash_Book_IBS_Map_ID = @MapID,
                        AB_Accounts_ID = @GLAccountID,
                        Sys_AW_Tax_Methods_ID = @TaxMethodID,
                        Amount = @Amount,
                        Tax_Amount = @Tax,
                        Net_Amount = @Net
                    WHERE AB_Cash_Book_IBS_Map_ID = @OldMapSplitID

                    SET @NewMapSplitID = @OldMapSplitID
                END
    	END			


	
RETURN @NewMapSplitID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



























-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_IBS_Maps
--Purpose       :Insert IBS CashBook Mapping data
--Functionality :
--Date          :2010/02/13
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AB_Insert_Cash_Book_IBS_Maps
    (
        @MapID int,
        @CompanyBanksID int,
        @Post bit,
        @TranTypeID tinyint,
        @Map1 varchar(100) ='',
        @Map2 varchar(30) ='',
        @Map3 varchar(30) ='',
        @GLAccountID int,
        @TaxMethodID tinyint,
        @BankDescription varchar(100) ='',
        @Comments varchar(50) ='',
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @MappingID int,
            @NewMapID int

    SET @MappingID = 0
    SET @NewMapID = 0

    IF @MapID > 0
        BEGIN
            UPDATE AB_Cash_Book_IBS_Map
            SET Post = @Post,
                Sys_AB_Transaction_Types_ID = @TranTypeID,
                Map_1 = @Map1,
                Map_2 = @Map2,
                Map_3 = @Map3,
                AB_Accounts_ID = @GLAccountID,
                Sys_AW_Tax_Methods_ID = @TaxMethodID,
                Bank_Description = @BankDescription,
                Comments = @Comments
            WHERE AB_Cash_Book_IBS_Map_ID = @MapID
        END
    ELSE
        BEGIN
            SET @MappingID = 0

            SELECT @MappingID = AB_Cash_Book_IBS_Map_ID
            FROM AB_Cash_Book_IBS_Map
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AW_Company_Banks_ID = @CompanyBanksID AND
                  Map_1 = @Map1 AND
                  Map_2 = @Map2 AND
                  Map_3 = @Map3

            IF @MappingID = 0
                BEGIN
                    INSERT AB_Cash_Book_IBS_Map
                    (
                        AW_Company_Banks_ID,
                        Post,
                        Sys_AB_Transaction_Types_ID,
                        Map_1,
                        Map_2,
                        Map_3,
                        AB_Accounts_ID,
                        Sys_AW_Tax_Methods_ID,
                        Bank_Description,
                        Comments,
                        User_ID,
                        AW_User_Companies_ID
                    )
                    VALUES
                    (
                        @CompanyBanksID,
                        @Post,
                        @TranTypeID,
                        @Map1,
                        @Map2,
                        @Map3,
                        @GLAccountID,
                        @TaxMethodID,
                        @BankDescription,
                        @Comments,
                        @UserID,
                        @CompanyID
                    )
        
                    SELECT @NewMapID = Scope_Identity()
                END
            ELSE
                BEGIN
                    UPDATE AB_Cash_Book_IBS_Map
                    SET Post = @Post,
                        Sys_AB_Transaction_Types_ID = @TranTypeID,
                        Map_1 = @Map1,
                        Map_2 = @Map2,
                        Map_3 = @Map3,
                        AB_Accounts_ID = @GLAccountID,
                        Sys_AW_Tax_Methods_ID = @TaxMethodID,
                        Bank_Description = @BankDescription,
                        Comments = @Comments
                    WHERE AB_Cash_Book_IBS_Map_ID = @MappingID

                    SET @NewMapID = @MappingID
                END
        END


RETURN @NewMapID





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_Transactions
--Functionality :INSERTS 1. Cash Book Header Transaction 
--              :INSERTS GL Transactions for:
--              :        2. Bank GL Account provided in @Company_Banks_ID
--              :
--Date          :2002/02/04
--Authors       :TB
--MODS          :09/01/03 - Added Cash Book Ref # into the GL Tran Description
--              :09/01/03 - Added inserting Recon_Amount with value 0
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :04/02/04 - Removed concatenating Trantype and RefNo into Source Ref
--2004.2.4.2    :27/11/05 - Added trim @Ref_No and @Description to SCHEMA sizes
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Insert_Cash_Book_Transactions
    (
        @Company_Banks_ID int,
        @Transaction_Type_ID tinyint,
    	@Transaction_Date datetime,
    	@Months_ID tinyint,
    	@Years_ID smallint,
    	@Ref_No varchar(20),
    	@Description varchar(50) = '',
    	@Amount money,
    	@User_ID int,
    	@Company_ID int,
        @InsertGLTran bit = 1
    )

AS

SET NOCOUNT ON

    DECLARE @Banks_GL_Account_ID int,
    		@NextCashbookID int,
-------------------------------------------------------------------------
-- To bring in the Cash Book Ref # into the GL Transactions -------------
-------------------------------------------------------------------------
            @GLTranRef varchar(50),
            @GLSourceRef varchar(20)
-------------------------------------------------------------------------

    SET @Ref_No = LEFT(RTRIM(LTRIM(@Ref_No)), 20)
    SET @Description = LEFT(RTRIM(LTRIM(@Description)), 50)


    BEGIN TRANSACTION

    	BEGIN
    		SET @Amount = -@Amount
    	
    		INSERT INTO AB_Cash_Book_Transactions
                (
        			AW_Company_Banks_ID, 
        			Sys_AB_Transaction_Types_ID, 
        			Transaction_Date,
        			Slu_AW_Months_ID, 
        			Slu_AW_Years_ID,
        			Reference_No, 
        			Transaction_Description, 
        			Amount,
                    Recon_Amount,
        			[User_ID],
        			AW_User_Companies_ID
                )
    		VALUES
                (
                    @Company_Banks_ID,
                    @Transaction_Type_ID,
                    @Transaction_Date,
                    @Months_ID,
                    @Years_ID,
                    @Ref_No,
                    @Description,
                    @Amount,
                    0,
                    @User_ID,
                    @Company_ID
                )
    		
    		SET @NextCashbookID = (SELECT scope_Identity())
	
            IF @InsertGLTran = 1    -- 1 = YES, 0 = NO 
                BEGIN

-------------------------------------------------------------------------
-- To bring in the Cash Book Ref # into the GL Transactions -------------
-------------------------------------------------------------------------
                    SELECT @GLSourceRef = Transaction_Code
                    FROM Sys_AB_Transaction_Types
                    WHERE Sys_AB_Transaction_Types_ID = @Transaction_Type_ID


                    SET @GLSourceRef = LEFT(RTRIM(LTRIM(@Ref_No)), 20)
-------------------------------------------------------------------------

            		SELECT @Banks_GL_Account_ID = ISNULL(AB_Accounts_ID, 1)
            		FROM AW_Company_Banks 
            		WHERE AW_User_Companies_ID = @Company_ID AND
                          AW_Company_Banks_ID = @Company_Banks_ID
            	
            		EXEC sp_AB_Insert_GL_Transactions
                                        @Description,
                                        @Transaction_Type_ID,
                                        @Banks_GL_Account_ID,
                                        @Transaction_Date,        --NEW
                                        @GLSourceRef,             --NEW
                                        @Months_ID,
                                        @Years_ID,
                                        @NextCashbookID,
                                        @Amount,
                                        @User_ID,
                                        @Company_ID

                END

    	END

    COMMIT TRANSACTION


    RETURN @NextCashbookID




SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Book_Transactions_Details
--Functionality :INSERTS 1. Cash Book Transaction 
--              :INSERTS GL Transactions for:
--              :        2. GL Bank Control Account provided,
--              :        3. V.A.T. on Cash Book Transaction
--Functionality :Insert
--Parameters    :
--Date          :2002/02/04
--Authors       :TB
--MODS          :23/09/02 - Fixed @Tax_Amount validation from: IF > 0 to: IF <> 0
--              :           causing TAX not to be inserted in GL if a DEPOSIT,
--              :           i.e. when @Tax_Amount < 0
--              :09/01/03 - Added Cash Book Ref # into the GL Tran Description
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :04/02/04 - Removed concatenating Trantype and RefNo into Source Ref
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Insert_Cash_Book_Transactions_Details
    (
        @CB_Header_ID int,
        @AB_Accounts_ID int,
    	@Tax_Method tinyint,
    	@Amount money,
    	@Tax_Code tinyint,
    	@Tax_Amount money,
    	@Net_Amount money,
    	@Comments varchar(50),
    	@GL_Description varchar(50) = '',
    	@User_ID int,
    	@Company_ID int,
        @InsertGLTran bit = 1
    )

AS

SET NOCOUNT ON

    DECLARE @Cashbook_Trans_Type_ID int,
            @Months_ID tinyint,
            @Years_ID smallint,
            @VAT_GL_Acc_ID int,
            @New_CB_Details_ID int,
            @Transaction_Date datetime,        --NEW
-------------------------------------------------------------------------
-- To bring in the Cash Book Ref # into the GL Transactions -------------
-------------------------------------------------------------------------
            @GLSourceRef varchar(20),
            @Ref_No varchar(20)
-------------------------------------------------------------------------
    
	BEGIN TRANSACTION
    	BEGIN 

    		INSERT INTO AB_Cash_Book_Transaction_Details
                (
        			AB_Cash_Book_Transactions_ID, 
        			AB_Accounts_ID, 
        			Sys_AW_Tax_Methods_ID,
        			Amount, 
        			Sys_AW_Tax_Codes_ID,
        			Tax_Amount, 
        			Net_Amount, 
        			Comments,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
    		VALUES
                (
                    @CB_Header_ID ,
                    @AB_Accounts_ID ,
                    @Tax_Method ,
                    @Amount ,
                    @Tax_Code ,
                    @Tax_Amount ,
                    @Net_Amount ,
                    @Comments ,
                    GETDATE(),
                    @User_ID,
                    @Company_ID
                )
    		
            SET @New_CB_Details_ID = (SELECT scope_Identity())
    			
    	END			

        IF @InsertGLTran = 1    -- 1 = YES, 0 = NO 
        	BEGIN

            --> Select The TRANSACTION TYPE ID of this Transaction
        		SELECT @Cashbook_Trans_Type_ID = Sys_AB_Transaction_Types_ID,
                       @Transaction_Date = Transaction_Date,
                       @Months_ID = Slu_AW_Months_ID,
                       @Years_ID = Slu_AW_Years_ID,
                       @Ref_No = Reference_No
        		FROM AB_Cash_Book_Transactions
        		WHERE AB_Cash_Book_Transactions_ID = @CB_Header_ID
        		
        		IF ISNULL(@Tax_Amount, 0) <> 0    --23/09/02, was > 0 
        			BEGIN
        				SET @Amount = (ISNULL(@Amount, 0) - ISNULL(@Tax_Amount, 0))
        			END

-------------------------------------------------------------------------
-- To bring in the Cash Book Ref # into the GL Transactions -------------
-------------------------------------------------------------------------
                    SELECT @GLSourceRef = Transaction_Code
                    FROM Sys_AB_Transaction_Types
                    WHERE Sys_AB_Transaction_Types_ID = @Cashbook_Trans_Type_ID


                    SET @GLSourceRef = LEFT(RTRIM(LTRIM(@Ref_No)), 20)
                    SET @GL_Description = LEFT(@GL_Description, 50)
-------------------------------------------------------------------------

        		EXEC sp_AB_Insert_GL_Transactions
                        @GL_Description,
                        @Cashbook_Trans_Type_ID,	
                        @AB_Accounts_ID,
                        @Transaction_Date,        --NEW
                        @GLSourceRef,             --NEW
                        @Months_ID,
                        @Years_ID,
                        @CB_Header_ID,            --@New_CB_Details_ID,
                        @Amount,
                        @User_ID,
                        @Company_ID	
        		
                --> VAT Control
        		IF ISNULL(@Tax_Amount, 0) <> 0    --23/09/02, was > 0 
        			BEGIN 			
        				SELECT @VAT_GL_Acc_ID = AB_Accounts_ID
        				FROM AB_Control_Accounts
        				WHERE Control_Number = 401    --VAT Control
    
                        EXEC sp_AB_Insert_GL_Transactions
                                @GL_Description,
                                @Cashbook_Trans_Type_ID,
        						@VAT_GL_Acc_ID,
                                @Transaction_Date,        --NEW
                                @GLSourceRef,             --NEW
                                @Months_ID,
                                @Years_ID,
                                @CB_Header_ID,            --@New_CB_Details_ID,
                                @Tax_Amount,
                                @User_ID,
                                @Company_ID
        			END
        	END

	COMMIT TRAN
	
    RETURN @New_CB_Details_ID

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Forecast
--Purpose       :Insert Cash Flow FORECAST data
--Functionality :
--Date          :2011/02/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AB_Insert_Cash_Forecast
    (
        @Description varchar(50) = '',
        @N1 tinyint,
        @M1 bigint,
        @M2 bigint,
        @M3 bigint,
        @M4 bigint,
        @M5 bigint,
        @M6 bigint,
        @T1 bigint,
        @RowTypeID tinyint,
        @StartDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewForecastID int

    SET @NewForecastID = 0


    INSERT AB_Cash_Flow_Forecast_Temp
    (
        Description,
        N1,
        M1,
        M2,
        M3,
        M4,
        M5,
        M6,
        T1,
        RowTypeID,
        StartDate,
        AW_User_Companies_ID
    )
    VALUES
    (
        @Description,
        @N1,
        @M1,
        @M2,
        @M3,
        @M4,
        @M5,
        @M6,
        @T1,
        @RowTypeID,
        @StartDate,
        @CompanyID
    )

    SELECT @NewForecastID = Scope_Identity()


RETURN @NewForecastID




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Inflows
--Purpose       :Insert Cash Flow INFLOW data
--Functionality :
--Date          :2011/02/08
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Insert_Cash_Inflows
    (
        @InflowID int,
        @Post bit,
        @InflowDate datetime,
        @Description varchar(50) = '',
        @TaxMethodID tinyint,
        @Amount money,
        @Tax money,
        @Net money,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewInflowID int

    SET @NewInflowID = 0

    IF @InflowID > 0
        BEGIN
            UPDATE AB_Cash_Inflow_Projections
            SET Post = @Post,
                Inflow_Date = @InflowDate,
                Description = @Description,
                Sys_AW_Tax_Methods_ID = @TaxMethodID,
                Amount = @Amount,
                Tax_Amount = @Tax,
                Net_Amount = @Net
            WHERE AB_Cash_Inflow_Projections_ID = @InflowID
        END
    ELSE
        BEGIN
            INSERT AB_Cash_Inflow_Projections
            (
                Post,
                Inflow_Date,
                Description,
                Sys_AW_Tax_Methods_ID,
                Amount,
                Tax_Amount,
                Net_Amount,
                User_ID,
                AW_User_Companies_ID
            )
            VALUES
            (
                @Post,
                @InflowDate,
                @Description,
                @TaxMethodID,
                @Amount,
                @Tax,
                @Net,
                @UserID,
                @CompanyID
            )

            SELECT @NewInflowID = Scope_Identity()
        END


RETURN @NewInflowID























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Cash_Outflows
--Purpose       :Insert Cash Flow Outflow data
--Functionality :
--Date          :2011/02/08
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Insert_Cash_Outflows
    (
        @OutflowID int,
        @Post bit,
        @OutflowDate datetime,
        @Description varchar(50) = '',
        @TaxMethodID tinyint,
        @Amount money,
        @Tax money,
        @Net money,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewOutflowID int

    SET @NewOutflowID = 0

    IF @OutflowID > 0
        BEGIN
            UPDATE AB_Cash_Outflow_Projections
            SET Post = @Post,
                Outflow_Date = @OutflowDate,
                Description = @Description,
                Sys_AW_Tax_Methods_ID = @TaxMethodID,
                Amount = @Amount,
                Tax_Amount = @Tax,
                Net_Amount = @Net
            WHERE AB_Cash_Outflow_Projections_ID = @OutflowID
        END
    ELSE
        BEGIN
            INSERT AB_Cash_Outflow_Projections
            (
                Post,
                Outflow_Date,
                Description,
                Sys_AW_Tax_Methods_ID,
                Amount,
                Tax_Amount,
                Net_Amount,
                User_ID,
                AW_User_Companies_ID
            )
            VALUES
            (
                @Post,
                @OutflowDate,
                @Description,
                @TaxMethodID,
                @Amount,
                @Tax,
                @Net,
                @UserID,
                @CompanyID
            )

            SELECT @NewOutflowID = Scope_Identity()
        END


RETURN @NewOutflowID























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Balance_Sheet
--Purpose       :INSERT Enterprise Balance Sheet Report data
--Date          :2007/09/09
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Balance_Sheet]
	(
        @ColumnName						varchar(50),
        @Sys_AB_B1_ID					int,
        @Sys_AB_B2_ID					int,
        @Sys_AB_B3_ID					int,
        @AccountNo						varchar(16),
        @Category						varchar(100),
        @Level1							varchar(100),
        @Level2							varchar(100),
        @Level3							varchar(100),
        @Account						varchar(50),
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        @Balance						money,
        @GroupByDepartment				tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @eIS_ID int,
            @ReturnValue int


    SET @eIS_ID = 0
    SET @ReturnValue = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Category = ISNULL(@Category, '')
    SET @Level1 = ISNULL(@Level1, '')
    SET @Level2 = ISNULL(@Level2, '')
    SET @Level3 = ISNULL(@Level3, '')
    SET @Account = ISNULL(@Account, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')   
    SET @Balance = ISNULL(@Balance, 0)


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Category = RTRIM(LTRIM(@Category))
    SET @Level1 = RTRIM(LTRIM(@Level1))
    SET @Level2 = RTRIM(LTRIM(@Level2))
    SET @Level3 = RTRIM(LTRIM(@Level3))
    SET @Account = RTRIM(LTRIM(@Account))
	SET @Department = RTRIM(LTRIM(@Department))        

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Account = @Department
		END
	END

	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Balance_Sheet_ID
		FROM AB_Enterprise_Balance_Sheet
		WHERE Sys_AB_B1_ID = @Sys_AB_B1_ID AND
			  Sys_AB_B2_ID = @Sys_AB_B2_ID AND
			  Sys_AB_B3_ID = @Sys_AB_B3_ID AND
			  Account_Number = @AccountNo
		ORDER BY RTRIM(LTRIM(Account_Number)) ASC
	END
	ELSE
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Balance_Sheet_ID
		FROM AB_Enterprise_Balance_Sheet
		WHERE Sys_AB_B1_ID = @Sys_AB_B1_ID AND
			  Sys_AB_B2_ID = @Sys_AB_B2_ID AND
			  Sys_AB_B3_ID = @Sys_AB_B3_ID AND
			  Account = @Account
		ORDER BY RTRIM(LTRIM(Account_Number)) ASC
	END

    IF @eIS_ID IS NULL
        BEGIN
            SET @eIS_ID = 0
        END


    IF @eIS_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Balance_Sheet '
            SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '            
            SET @sql = @sql + '      Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Balance)
            SET @sql = @sql + '  WHERE AB_Enterprise_Balance_Sheet_ID = ' + CONVERT(varchar(20), @eIS_ID)

            SET @ReturnValue = 1
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Balance_Sheet '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      Sys_AB_B1_ID, '
            SET @sql = @sql + '      Sys_AB_B2_ID, '
            SET @sql = @sql + '      Sys_AB_B3_ID, '
            SET @sql = @sql + '      Account_Number, '
            SET @sql = @sql + '      Category, '
            SET @sql = @sql + '      Level1, '
            SET @sql = @sql + '      Level2, '
            SET @sql = @sql + '      Level3, '
            SET @sql = @sql + '      Account, '
            SET @sql = @sql + '      Total, '
            SET @sql = @sql +        @ColumnName + ' '
            SET @sql = @sql + '  ) '
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_B1_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_B2_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_B3_ID) + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '
            SET @sql = @sql +           '''' + @Category + '''' + ', '
            SET @sql = @sql +           '''' + @Level1 + '''' + ', '
            SET @sql = @sql +           '''' + @Level2 + '''' + ', '
            SET @sql = @sql +           '''' + @Level3 + '''' + ', '
            SET @sql = @sql +           '''' + @Account + '''' + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ' '
            SET @sql = @sql + '  ) '

            SET @ReturnValue = 2
        END


    EXEC (@sql)

RETURN @ReturnValue

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Income_Statement
--Purpose       :INSERT Enterprise Income Statement Report data
--Date          :2007/09/05
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Income_Statement]
	(
        @ColumnName						varchar(50),
        @Sys_AB_I1_ID					int,
        @Sys_AB_I2_ID					int,
        @Sys_AB_I3_ID					int,
        @Sys_AB_I4_ID					int,
        @AccountNo						varchar(16),
        @Category						varchar(100),
        @Level1							varchar(100),
        @Level2							varchar(100),
        @Level3							varchar(100),
        @Level4							varchar(100),
        @Account						varchar(50),
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        @Balance						money,
        @GroupByDepartment				tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @eIS_ID int,
            @ReturnValue int


    SET @eIS_ID = 0
    SET @ReturnValue = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Category = ISNULL(@Category, '')
    SET @Level1 = ISNULL(@Level1, '')
    SET @Level2 = ISNULL(@Level2, '')
    SET @Level3 = ISNULL(@Level3, '')
    SET @Level4 = ISNULL(@Level4, '')
    SET @Account = ISNULL(@Account, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')
    SET @Balance = ISNULL(@Balance, 0)

    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Category = RTRIM(LTRIM(@Category))
    SET @Level1 = RTRIM(LTRIM(@Level1))
    SET @Level2 = RTRIM(LTRIM(@Level2))
    SET @Level3 = RTRIM(LTRIM(@Level3))
    SET @Level4 = RTRIM(LTRIM(@Level4))
    SET @Account = RTRIM(LTRIM(@Account))
	SET @Department = RTRIM(LTRIM(@Department))    

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Account = @Department
		END
	END

	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Income_Statement_ID
		FROM AB_Enterprise_Income_Statement
		WHERE Sys_AB_I1_ID = @Sys_AB_I1_ID AND
			  Sys_AB_I2_ID = @Sys_AB_I2_ID AND
			  Sys_AB_I3_ID = @Sys_AB_I3_ID AND
			  Sys_AB_I4_ID = @Sys_AB_I4_ID AND
			  Account_Number = @AccountNo
		ORDER BY RTRIM(LTRIM(Account_Number)) ASC
	END
	ELSE
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Income_Statement_ID
		FROM AB_Enterprise_Income_Statement
		WHERE Sys_AB_I1_ID = @Sys_AB_I1_ID AND
			  Sys_AB_I2_ID = @Sys_AB_I2_ID AND
			  Sys_AB_I3_ID = @Sys_AB_I3_ID AND
			  Sys_AB_I4_ID = @Sys_AB_I4_ID AND
			  Account = @Account
		ORDER BY RTRIM(LTRIM(Account)) ASC
	END


    IF @eIS_ID IS NULL
        BEGIN
            SET @eIS_ID = 0
        END


    IF @eIS_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Income_Statement '
            SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '            
            SET @sql = @sql + '      Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Balance)
            SET @sql = @sql + '  WHERE AB_Enterprise_Income_Statement_ID = ' + CONVERT(varchar(20), @eIS_ID)

            SET @ReturnValue = 1
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Income_Statement '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      Sys_AB_I1_ID, '
            SET @sql = @sql + '      Sys_AB_I2_ID, '
            SET @sql = @sql + '      Sys_AB_I3_ID, '
            SET @sql = @sql + '      Sys_AB_I4_ID, '
            SET @sql = @sql + '      Account_Number, '
            SET @sql = @sql + '      Category, '
            SET @sql = @sql + '      Level1, '
            SET @sql = @sql + '      Level2, '
            SET @sql = @sql + '      Level3, '
            SET @sql = @sql + '      Level4, '
            SET @sql = @sql + '      Account, '
            SET @sql = @sql + '      Total, '
            SET @sql = @sql +        @ColumnName + ' '
            SET @sql = @sql + '  ) '
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I1_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I2_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I3_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I4_ID) + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '
            SET @sql = @sql +           '''' + @Category + '''' + ', '
            SET @sql = @sql +           '''' + @Level1 + '''' + ', '
            SET @sql = @sql +           '''' + @Level2 + '''' + ', '
            SET @sql = @sql +           '''' + @Level3 + '''' + ', '
            SET @sql = @sql +           '''' + @Level4 + '''' + ', '
            SET @sql = @sql +           '''' + @Account + '''' + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ' '
            SET @sql = @sql + '  ) '

            SET @ReturnValue = 2
        END


    EXEC (@sql)

RETURN @ReturnValue

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Management_Accounts
--Purpose       :INSERT Enterprise Management Accounts Report data
--Date          :2015-08-20
--Authors       :RL
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-----------------------	--------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Management_Accounts]
	(
        @ColumnName varchar(50),
       	@IS1ID [int],
       	@IS2ID [int],
       	@IS3ID [int],       	       	
       	@IS4ID [int],
       	
       	@GLID [int],
       	@DivisionID int,
        @GroupID int,
        
        @Level1 varchar(100),
        @Level2 varchar(100),
        @Level3 varchar(100),
        @Level4 varchar(100),
        
        @GLDivision varchar(100),
        @GLGroup varchar(100),
        @AccountNo varchar(100),
        @Account varchar(100),
        
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        
        @Actual money,
        @Budget money,
        @YTDActual money,
        @YTDBudget money,
        @GroupByDepartment				tinyint                
  	)
AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @eMA_ID int,
            @ReturnValue int

    SET @eMA_ID = 0
    SET @ReturnValue = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Level1 = ISNULL(@Level1, '')
    SET @Level2 = ISNULL(@Level2, '')
    SET @Level3 = ISNULL(@Level3, '')
    SET @Level4 = ISNULL(@Level4, '')
    SET @GLDivision = ISNULL(@GLDivision, '')
    SET @GLGroup = ISNULL(@GLGroup, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Account = ISNULL(@Account, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')   
    SET @Actual = ISNULL(@Actual, 0)
    SET @Budget = ISNULL(@Budget, 0)
    SET @YTDActual = ISNULL(@YTDActual, 0)
    SET @YTDBudget = ISNULL(@YTDBudget, 0)

    
    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Level1 = RTRIM(LTRIM(@Level1))
    SET @Level2 = RTRIM(LTRIM(@Level2))
    SET @Level3 = RTRIM(LTRIM(@Level3))
    SET @Level4 = RTRIM(LTRIM(@Level4))
    SET @GLDivision = RTRIM(LTRIM(@GLDivision))
    SET @GLGroup = RTRIM(LTRIM(@GLGroup))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Department = RTRIM(LTRIM(@Department))        

    --> SELECT FIRST @AccountNo and @Category (in case several exist)
    --SELECT TOP 1 @eIS_ID = AB_Enterprise_Management_Accounts_ID
    --FROM AB_Enterprise_Management_Accounts
    --WHERE Level1 = @Level1 AND
    --      Level2 = @Level2 AND
    --      Level3 = @Level3 AND
    --      Level4 = @Level4 AND
    --      AccountNo = @AccountNo
    --ORDER BY RTRIM(LTRIM(AccountNo)) ASC

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Account = @Department
		END
	END


	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		SELECT TOP 1 @eMA_ID = ISNULL(AB_Enterprise_Management_Accounts_ID, 0)
		FROM AB_Enterprise_Management_Accounts
		WHERE RTRIM(LTRIM(AccountNo)) = @AccountNo
		  AND RTRIM(LTRIM(GLDivision)) = @GLDivision
		  AND RTRIM(LTRIM(GLGroup)) = @GLGroup

		ORDER BY RTRIM(LTRIM(AccountNo)), RTRIM(LTRIM(GLDivision)), RTRIM(LTRIM(GLGroup)) ASC
	END
	ELSE
	BEGIN
		SELECT TOP 1 @eMA_ID = ISNULL(AB_Enterprise_Management_Accounts_ID, 0)
		FROM AB_Enterprise_Management_Accounts
		WHERE RTRIM(LTRIM(Account)) = @Account
		  AND RTRIM(LTRIM(GLDivision)) = @GLDivision
		  AND RTRIM(LTRIM(GLGroup)) = @GLGroup

		ORDER BY RTRIM(LTRIM(Account)), RTRIM(LTRIM(GLDivision)), RTRIM(LTRIM(GLGroup)) ASC
	END


    IF @eMA_ID IS NULL
    BEGIN
		SET @eMA_ID = 0
    END


    IF @eMA_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Management_Accounts '
            
            --SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '                        
            
            SET @sql = @sql + '  SET ' + @ColumnName + '_Act = ISNULL( ' + @ColumnName + '_Act,0) + ' + CONVERT(varchar(50), @Actual) + ', '  
            --SET @sql = @sql + '  SET ' + @ColumnName + '_Act = ' + CONVERT(varchar(50), @Actual) + ', '            
            SET @sql = @sql + '      TotalActual = ISNULL(TotalActual, 0) + ' + CONVERT(varchar(50), @Actual) + ', '

			SET @sql = @sql + '   ' + @ColumnName + '_Bud = ISNULL( ' + @ColumnName + '_Bud,0) + ' + CONVERT(varchar(50), @Budget) + ', '  
            --SET @sql = @sql + '   ' + @ColumnName + '_Bud = ' + CONVERT(varchar(50), @Budget) + ', '
            SET @sql = @sql + '      TotalBudget = ISNULL(TotalBudget, 0) + ' + CONVERT(varchar(50), @Budget) + ', '

			SET @sql = @sql + '   ' + @ColumnName + '_YTDAct = ISNULL( ' + @ColumnName + '_YTDAct,0) + ' + CONVERT(varchar(50), @YTDActual) + ', '  
            --SET @sql = @sql + '   ' + @ColumnName + '_YTDAct = ' + CONVERT(varchar(50), @YTDActual) + ', '
            SET @sql = @sql + '      TotalYTDActual = ISNULL(TotalYTDActual, 0) + ' + CONVERT(varchar(50), @YTDActual) + ', '            

			SET @sql = @sql + '   ' + @ColumnName + '_YTDBud = ISNULL( ' + @ColumnName + '_YTDBud,0) + ' + CONVERT(varchar(50), @YTDBudget) + ', '  
            --SET @sql = @sql + '   ' + @ColumnName + '_YTDBud = ' + CONVERT(varchar(50), @YTDBudget) + ', '
            SET @sql = @sql + '      TotalYTDBudget = ISNULL(TotalYTDBudget, 0) + ' + CONVERT(varchar(50), @YTDBudget) + ' '
            
            SET @sql = @sql + '  WHERE AB_Enterprise_Management_Accounts_ID = ' + CONVERT(varchar(20), @eMA_ID)

            SET @ReturnValue = 1
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Management_Accounts '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      IS1ID, '
            SET @sql = @sql + '      IS2ID, '
            SET @sql = @sql + '      IS3ID, '                                    
            SET @sql = @sql + '      IS4ID, '
            
            SET @sql = @sql + '      GLID, '
            SET @sql = @sql + '      DivisionID, '
            SET @sql = @sql + '      GroupID, '
            
            SET @sql = @sql + '      Level1, '
            SET @sql = @sql + '      Level2, '
            SET @sql = @sql + '      Level3, '
            SET @sql = @sql + '      Level4, '
            
            SET @sql = @sql + '      GLDivision, '
            SET @sql = @sql + '      GLGroup, '
            SET @sql = @sql + '      AccountNo, '
            SET @sql = @sql + '      Account, '
            
            SET @sql = @sql + '      TotalActual, '
            SET @sql = @sql + '      TotalBudget, '
            SET @sql = @sql + '      TotalYTDActual, '
            SET @sql = @sql + '      TotalYTDBudget, '
                       
            SET @sql = @sql +        @ColumnName + '_Act, '
			SET @sql = @sql +        @ColumnName + '_Bud, '
			SET @sql = @sql +        @ColumnName + '_YTDAct, '						
			SET @sql = @sql +        @ColumnName + '_YTDBud '			
            SET @sql = @sql + '  ) '
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           CONVERT(varchar(20), @IS1ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @IS2ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @IS3ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @IS4ID) + ', '                                    
            SET @sql = @sql +           CONVERT(varchar(20), @GLID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @DivisionID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @GroupID) + ', '

            SET @sql = @sql +           '''' + @Level1 + '''' + ', '
            SET @sql = @sql +           '''' + @Level2 + '''' + ', '
            SET @sql = @sql +           '''' + @Level3 + '''' + ', '
            SET @sql = @sql +           '''' + @Level4 + '''' + ', '

            SET @sql = @sql +           '''' + @GLDivision + '''' + ', '
            SET @sql = @sql +           '''' + @GLGroup + '''' + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '            
            SET @sql = @sql +           '''' + @Account + '''' + ', '


            SET @sql = @sql +           CONVERT(varchar(50), @Actual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @Budget) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDActual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDBudget) + ', '			
			
            SET @sql = @sql +           CONVERT(varchar(50), @Actual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @Budget) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDActual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDBudget) + ' '			
            SET @sql = @sql + '  ) '

            SET @ReturnValue = 2
        END


    EXEC (@sql)
--Select @sql
RETURN @ReturnValue

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Trial_Balance
--Purpose       :INSERT Enterprise Trial Balance
--Date          :2007/08/28
--Authors       :TB
--MODS:         :
--2004.4.8      :05/11/09 - Added @Divisions and @Groups columns sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Trial_Balance]
	(
        @ColumnName						varchar(50),
        @Description					varchar(50),
        @AccountNo						varchar(16),
        @Category						varchar(100),
        @Divisions						varchar(50),
        @Groups							varchar(50),
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        @Balance						money,
        @GroupByDepartment				tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(4000),
            @eTB_ID int


    SET @eTB_ID = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @Description = ISNULL(@Description, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Category = ISNULL(@Category, '')
    SET @Divisions = ISNULL(@Divisions, '')
    SET @Groups = ISNULL(@Groups, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')
    SET @Balance = ISNULL(@Balance, 0)


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @Description = RTRIM(LTRIM(@Description))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Category = RTRIM(LTRIM(@Category))
    SET @Divisions = RTRIM(LTRIM(@Divisions))
    SET @Groups = RTRIM(LTRIM(@Groups))
	SET @Department = RTRIM(LTRIM(@Department))

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Description = @Department
		END
	END
	
	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eTB_ID = ISNULL(AB_Enterprise_Trial_Balance_ID, 0)
		FROM AB_Enterprise_Trial_Balance
		WHERE RTRIM(LTRIM(Account_Number)) = @AccountNo
		  AND RTRIM(LTRIM(Divisions)) = @Divisions
		  AND RTRIM(LTRIM(Groups)) = @Groups

		ORDER BY RTRIM(LTRIM(Account_Number)), RTRIM(LTRIM(Divisions)), RTRIM(LTRIM(Groups)) ASC
	END
	ELSE
	BEGIN
	
		--> SELECT FIRST @Account Name and @Category (in case several exist)
		SELECT TOP 1 @eTB_ID = ISNULL(AB_Enterprise_Trial_Balance_ID, 0)
		FROM AB_Enterprise_Trial_Balance
		WHERE RTRIM(LTRIM([Description])) = @Description
		  AND RTRIM(LTRIM(Divisions)) = @Divisions
		  AND RTRIM(LTRIM(Groups)) = @Groups

		ORDER BY RTRIM(LTRIM([Description])), RTRIM(LTRIM(Divisions)), RTRIM(LTRIM(Groups)) ASC
	END

    IF @eTB_ID IS NULL
        BEGIN
            SET @eTB_ID = 0
        END


    IF @eTB_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Trial_Balance '
            SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql + '      Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Balance)
            SET @sql = @sql + '  WHERE AB_Enterprise_Trial_Balance_ID = ' + CONVERT(varchar(20), @eTB_ID)
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Trial_Balance '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      Description, '
            SET @sql = @sql + '      Account_Number, '
            SET @sql = @sql + '      Category, '
            SET @sql = @sql + '      Divisions, '
            SET @sql = @sql + '      Groups, '
            SET @sql = @sql + '      Lup_AB_Account_Departments_ID, '
            SET @sql = @sql + '      Department, '                        
            SET @sql = @sql + '      Total, '
            SET @sql = @sql +        @ColumnName + ' '
            SET @sql = @sql + '  ) '
        
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           '''' + @Description + '''' + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '
            SET @sql = @sql +           '''' + @Category + '''' + ', '
            SET @sql = @sql +           '''' + @Divisions + '''' + ', '
            SET @sql = @sql +           '''' + @Groups + '''' + ', '
            SET @sql = @sql +           '' + Convert(Varchar(10),@Lup_AB_Account_Departments_ID) + '' + ', '
            SET @sql = @sql +           '''' + @Department + '''' + ', '                        
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ' '
            SET @sql = @sql + '  ) '
        END

   EXEC (@sql)
--Select @Sql
SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_AB_Insert_First_GL_Account
--Purpose       :Inserts an empty Account into the General Ledger
--Date          :2006/03/29
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Insert_First_GL_Account
    (
        @UserID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

    INSERT AB_Accounts
        (
            Description,
            [User_ID],
            AW_User_Companies_ID
        )

    VALUES
        (
            'New GL Account',
            @UserID,
            @CompanyID
        )


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_GL_Budget
--Purpose       :INSERT/UPDATE IMPORTED GL BUDGET
--Functionality :INSERTS a new budget for one month/year for a GLAccountID or
--              :UPDATES an existing budget for one month/year for a GLAccountID
--Date          :2011/10/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Insert_GL_Budget
    (
    	@GLAccountID int,
        @YearID int,
        @MonthID tinyint,
    	@Amount money,
        @CompanyID int,
        @UserID int,
        @Captured datetime
    )

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,
                Date_Captured = @Captured,
                [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

            SET @RetCode = 1
        END
    ELSE
        BEGIN
            INSERT AB_Budgets
                (
                    AB_Accounts_ID,
                    Slu_AW_Years_ID,
                    Slu_AW_Months_ID,
                    Budget_Amount,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
            VALUES
                (
                	@GLAccountID,
                    @YearID,
                    @MonthID,
                	@Amount,
                    @Captured,
                    @UserID,
                    @CompanyID
                )

            SET @RetCode = 2
        END


RETURN @RetCode









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--------------------------------------------------------------------------
--Description   :sp_AB_Insert_GL_Transactions
--Purpose       :Inserts a Transaction into the General Ledger 
--Functionality :Insert
--Parameters    :
--Date          :2002/01/28
--Authors       :TB
--MODS          :07/01/03 - Added precautionary ROUNDING of @Transaction_Amount
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           input parameters
--2004.4.7      :27/08/09 - Added @GLTranID as RETURN VALUE of INSERTED GL Transaction
--              :           for Stock Transfer Log (as well as many other possible uses) 
--------------------------------------------------------------------------

CREATE                Procedure sp_AB_Insert_GL_Transactions
    (
    	@Description varchar(50) = '',
    	@Transaction_Type_ID tinyint,
    	@AB_Accounts_ID int = 1,
        @AB_Transaction_Date datetime,
        @AB_Source_Ref varchar(20),
    	@AW_Months_ID int,
    	@AW_Years_ID int,
    	@Transaction_Ref int,
    	@Transaction_Amount money,
    	@User_ID int,
    	@Company_ID int
    )

AS 

SET NOCOUNT ON


    -- NEW 2004.4.7
    DECLARE @GLTranID int


    SET @Transaction_Amount = ROUND(@Transaction_Amount, 2)
    SET @GLTranID = 0


    IF @AB_Transaction_Date IS NULL
        BEGIN
            SET @AB_Transaction_Date = getdate()
        END


    BEGIN
    	INSERT INTO AB_GL_Transactions
            (
                [Description],
    			Sys_AB_Transaction_Types_ID,
    			AB_Accounts_ID,
    			AB_Transaction_Date,
                AB_Source_Ref,
    			Slu_AW_Months_ID,
    			Slu_AW_Years_ID,
    			AB_Transaction_Ref,
    			AB_Transaction_Amount,
    			[User_ID],
    			AW_User_Companies_ID
            )
    	VALUES
            (
                @Description,
    			@Transaction_Type_ID,
    			@AB_Accounts_ID,
    			@AB_Transaction_Date,
                @AB_Source_Ref,
    			@AW_Months_ID,
    			@AW_Years_ID,
    			@Transaction_Ref,
    			@Transaction_Amount,
    			@User_ID,
    			@Company_ID
            )

        -- NEW 2004.4.7
        SELECT @GLTranID = Scope_Identity()
    
    
        --> Update AB_Accounts Balance
    	UPDATE AB_Accounts 
    	SET AB_Account_Balance = ISNULL(AB_Account_Balance, 0) + ISNULL(@Transaction_Amount, 0)
    	WHERE AB_Accounts_ID = @AB_Accounts_ID
    END


    -- NEW 2004.4.7
    RETURN @GLTranID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Journal_Detail
--Purpose       :Inserts a journal Detail
--              :NB: By Default also Inserts a GLTransaction record
--Functionality :Tables: AB_Journal_Details, sp_AB_Insert_GL_Transactions
--Parameters    :
--Date          :2002/02/04
--Authors       :TB
--Version       :1.0.0
--MODS          :05/02/02 - Parameterized the inserting of a GL Transaction
--              :29/12/02 - Added @JnlNarration and fetched from Journal Header
--              :           to seperate Gl Transaction notes from Journal notes
--              :17/10/03 - Replaced @New_Journal_Detail_ID with @JnlHeaderID:
--              :           Eliminates a new GL Tran Ref No each journal allocation
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :20/12/04 - Assigned the Journal_Reference value to @GLSourceRef now !!!
-- RL V5.9      :2013-07-30 - Increased notes length to 70
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Insert_Journal_Detail]
    (
    	@JnlHeaderID int,
    	@AB_Accounts_ID int,
    	@Amount money,
    	@Notes varchar(70),
    	@User_ID int,
        @Company_ID int,
        @InsertGLTran bit = 1
    )

AS

SET NOCOUNT ON

    DECLARE @New_Journal_Detail_ID int,
    		@Months_ID int, 
    		@Years_ID int,
            @JnlNarration varchar(50),
            @JnlDate datetime,
            @GLSourceRef varchar(20)

	BEGIN
		INSERT INTO AB_Journal_Details
			(
                AB_Journals_ID,
                AB_Accounts_ID,
                Amount,
                Notes,
                Date_Captured,
                [User_ID],
                AW_User_Companies_ID
            )
		VALUES 
			(
                @JnlHeaderID ,
                @AB_Accounts_ID ,
                @Amount,
                @Notes,
                getdate(),
                @User_ID ,
                @Company_ID
            )
	
		SELECT @New_Journal_Detail_ID = Scope_Identity() 
	END

    IF @InsertGLTran = 1    -- 1 = YES, 0 = NO 
    	BEGIN
    		SELECT @JnlNarration = LEFT(ISNULL(Journal_Narration, ''), 50),
                   @JnlDate = Journal_Date,
                   @GLSourceRef = LEFT(Journal_Reference, 20),
                   @Months_ID = ISNULL(Slu_AW_Months_ID, 0),
                   @Years_ID = ISNULL(Slu_AW_Years_ID, 0)
    		FROM AB_Journals
    		WHERE AB_Journals_ID = @JnlHeaderID


    		EXEC sp_AB_Insert_GL_Transactions
                    @JnlNarration,
                    15,
        			@AB_Accounts_ID,
                    @JnlDate,                --NEW
                    @GLSourceRef,            --NEW
                    @Months_ID,
                    @Years_ID,
                    @JnlHeaderID,
        			@Amount,
                    @User_ID,
                    @Company_ID	
    		    
    		RETURN @New_Journal_Detail_ID
    	END
	
SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Journal_Header
--Purpose       :Inserts a journal Header
--Functionality :Tables: AB_Journals
--Parameters    :
--Date          :2002/02/04
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Insert_Journal_Header
    (
    	@Date datetime,
    	@Journal_Ref varchar(30),
    	@Narration varchar(200),
    	@AW_Months_ID int,
    	@AW_Years_ID int,
    	@User_ID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @New_Journal_ID int


	INSERT INTO AB_Journals
        (
            Journal_Date,
            Journal_Reference,
            Journal_Narration,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
	VALUES 
        (
            @Date,
            @Journal_Ref ,
            @Narration ,
            @AW_Months_ID ,
            @AW_Years_ID ,
            GETDATE(),
            @User_ID ,
            @CompanyID
        )

	SELECT @New_Journal_ID = Scope_Identity() 



RETURN @New_Journal_ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   : sp_AB_Insert_Recurring_Detail
--Purpose       : Inserts a new Recurring Journal Detail
--Functionality :
--Parameters    :
--Date          : 2002/12/27
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Insert_Recurring_Detail
    (
    	@Journal_ID int,
    	@AB_Accounts_ID int,
    	@Amount money,
    	@Notes varchar(50),
    	@User_ID int,
        @Company_ID int,
        @InsertGLTran bit = 1
    )

AS

SET NOCOUNT ON

    DECLARE @New_Journal_Detail_ID int,
    		@Months_ID int, 
    		@Years_ID int

	BEGIN
		INSERT INTO AB_Recurring_Details
			(
                AB_Recurring_ID,
                AB_Accounts_ID,
                Amount,
                Notes,
                Date_Captured,
                [User_ID],
                AW_User_Companies_ID
            )
		VALUES 
			(
                @Journal_ID ,
                @AB_Accounts_ID ,
                @Amount,
                @Notes,
                getdate(),
                @User_ID ,
                @Company_ID
            )
	
	END


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   : sp_AB_Insert_Recurring_Header
--Purpose       : Inserts a new Recurring Journal
--Functionality :
--Parameters    :
--Date          : 2002/12/27
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE        PROCEDURE sp_AB_Insert_Recurring_Header
    (
    	@Date datetime,
    	@Journal_Ref varchar(30),
    	@Narration varchar(200),
    	@AW_Months_ID int,
    	@AW_Years_ID int,
    	@User_ID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @New_Journal_ID int

	INSERT INTO AB_Recurring
		(
            Recurring_Date,
            Recurring_Reference,
            Recurring_Narration,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
	VALUES 
		(
            @Date,
            @Journal_Ref,
            @Narration,
            @AW_Months_ID,
            @AW_Years_ID,
            getdate(),
            @User_ID,
            @CompanyID
        )

	SELECT @New_Journal_ID = Scope_Identity() 

	RETURN @New_Journal_ID


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














----------------------------------------------------------------------------
--Description   :sp_AB_Insert_System_GL_Account
--Purpose       :Inserts an empty Account into the General Ledger
--Date          :2006/10/02
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Insert_System_GL_Account
    (
        @Description varchar(50),
        @Category int,
        @UserID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

    DECLARE @NewGLID int


    INSERT AB_Accounts
        (
            Description,
            Sys_AB_Account_Categories_ID,
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @Description,
            @Category,
            @UserID,
            @CompanyID
        )

    SET @NewGLID = (SELECT scope_Identity())



RETURN @NewGLID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Management_Account_Division_Sales
--Purpose       :Management Accounts DIVISION Sales Total
--Date          :2007/09/28
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Management_Account_Division_Sales
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @DivisionID int,
        @CurrentTot money OUTPUT,
        @BudgetTot money OUTPUT,
        @BalanceTot money OUTPUT,
        @YTDBudgetTot money OUTPUT
    )

AS

SET NOCOUNT ON


    DECLARE @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


    --NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    ------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    IF @IgnoreYEJnl = 1
        BEGIN
            SELECT
                @CurrentTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND t.Slu_AW_Months_ID = @MonthID
                          AND t.Slu_AW_Years_ID = @YearID
                          AND t.Sys_AB_Transaction_Types_ID <> 16
                    ),
                
                @BudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND bud.Slu_AW_Months_ID = @MonthID
                          AND bud.Slu_AW_Years_ID = @YearID
                    ),
        
                @BalanceTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
                          AND Sys_AB_Transaction_Types_ID <> 16
                    ),

                @YTDBudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= @EndPeriod
                    )

        END
    ELSE
        BEGIN
            SELECT
                @CurrentTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND t.Slu_AW_Months_ID = @MonthID
                          AND t.Slu_AW_Years_ID = @YearID
                    ),
                
                @BudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND bud.Slu_AW_Months_ID = @MonthID
                          AND bud.Slu_AW_Years_ID = @YearID
                    ),
                
                @BalanceTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
                    ),

                @YTDBudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= @EndPeriod
                    )

        END


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Management_Account_Group_Sales
--Purpose       :Management Accounts GROUP Sales Total
--Date          :2007/09/28
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Management_Account_Group_Sales
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @DivisionID int,
        @GroupID int,
        @CurrentTot money OUTPUT,
        @BudgetTot money OUTPUT,
        @BalanceTot money OUTPUT,
        @YTDBudgetTot money OUTPUT
    )

AS

SET NOCOUNT ON


    DECLARE @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


    --NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    ------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    IF @IgnoreYEJnl = 1
        BEGIN
            SELECT
                @CurrentTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND t.Slu_AW_Months_ID = @MonthID
                          AND t.Slu_AW_Years_ID = @YearID
                          AND t.Sys_AB_Transaction_Types_ID <> 16
                    ),
                
                @BudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND bud.Slu_AW_Months_ID = @MonthID
                          AND bud.Slu_AW_Years_ID = @YearID
                    ),
        
                @BalanceTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
                          AND Sys_AB_Transaction_Types_ID <> 16
                    ),

                @YTDBudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= @EndPeriod
                    )

        END
    ELSE
        BEGIN
            SELECT
                @CurrentTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND t.Slu_AW_Months_ID = @MonthID
                          AND t.Slu_AW_Years_ID = @YearID
                    ),
                
                @BudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND bud.Slu_AW_Months_ID = @MonthID
                          AND bud.Slu_AW_Years_ID = @YearID
                    ),
                
                @BalanceTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
                    ),

                @YTDBudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND a.Lup_AB_Account_Divisions_ID = @DivisionID
                          AND a.Lup_AB_Account_Groups_ID = @GroupID
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= @EndPeriod
                    )

        END


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Management_Account_Sales
--Purpose       :Management Accounts Sales Total
--Date          :2007/09/28
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Management_Account_Sales
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @CurrentTot money OUTPUT,
        @BudgetTot money OUTPUT,
        @BalanceTot money OUTPUT,
        @YTDBudgetTot money OUTPUT
    )

AS

SET NOCOUNT ON


    DECLARE @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


    --NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    ------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    IF @IgnoreYEJnl = 1
        BEGIN
            SELECT
                @CurrentTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND t.Slu_AW_Months_ID = @MonthID
                          AND t.Slu_AW_Years_ID = @YearID
                          AND t.Sys_AB_Transaction_Types_ID <> 16
                    ),
                
                @BudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND bud.Slu_AW_Months_ID = @MonthID
                          AND bud.Slu_AW_Years_ID = @YearID
                    ),
        
                @BalanceTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
                          AND Sys_AB_Transaction_Types_ID <> 16
                    ),

                @YTDBudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= @EndPeriod
                    )

        END
    ELSE
        BEGIN
            SELECT
                @CurrentTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND t.Slu_AW_Months_ID = @MonthID
                          AND t.Slu_AW_Years_ID = @YearID
                    ),
                
                @BudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND bud.Slu_AW_Months_ID = @MonthID
                          AND bud.Slu_AW_Years_ID = @YearID
                    ),
                
                @BalanceTot = 
                    (
                        SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0)
                        FROM AB_GL_Transactions t
                        INNER JOIN AB_Accounts a
                            ON t.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
                    ),

                @YTDBudgetTot = 
                    (
                        SELECT ISNULL(SUM(bud.Budget_Amount), 0)
                        FROM AB_Budgets bud
                        INNER JOIN AB_Accounts a
                            ON bud.AB_Accounts_ID = a.AB_Accounts_ID
                        INNER JOIN Sys_AB_Account_Categories b
                            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
                        WHERE a.AW_User_Companies_ID = @CompanyID
                          AND b.Sys_AB_I4_ID = 10
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= @StartPeriod
                          AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= @EndPeriod
                    )

        END


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






-------------------------------------------------------------------------------
--Description   : sp_AB_Next_Transaction_Number
--Purpose       : INCREMENT next available Accountant Transaction Number
--Functionality : Tables: Sys_AB_Transaction_Numbers
--Parameters    : RETURNS next transaction number as parameter
--Date          : 2002/01/30
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AB_Next_Transaction_Number
    (
        @TransactionType int, 
        @CompanyID int
    )

AS

SET NOCOUNT ON    

    DECLARE @Num int,
            @TransactionNumber varchar(15)
    
    SELECT @Num = ISNULL(Last_Number, 0)
    FROM Sys_AB_Transaction_Numbers
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AB_Transaction_Types_ID = @TransactionType
    
    UPDATE Sys_AB_Transaction_Numbers
    SET Last_Number = @Num + 1 
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AB_Transaction_Types_ID = @TransactionType
    
    SET @TransactionNumber = CONVERT(varchar(15), @Num + 1)

    RETURN @TransactionNumber

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_AB_Reverse_Cash_Book_Transaction
--Purpose       :Reverse ONE Cash Book Transaction
--              :ALSO INSERTS A GL TRANSACTION
--Functionality :Insert
--Date          :2004/10/19
--Authors       :TB
--MODS          :
--2004.3.8      :14/01/08 - Removed setting [Recon_Amount] in CB Reversal that
--              :           causes reversed transactions to show as reconciled
--2004.4.8      :05/03/10 - Set [Recon_Amount] = 0 in CB Reversal otherwise it
--              :           is inserted as a NULL value
--2004.5.0      :17/03/11 - Added @OrigAmount = ISNULL(Amount, 0) to prevent NULL Amount
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AB_Reverse_Cash_Book_Transaction
    (
        @CBReversalTranID int,
    	@UserID int,
        @InsertGLTran bit
    )

AS

SET NOCOUNT ON

    DECLARE @Banks_GL_Account_ID int,
    		@NextCashbookID int,
            @GLTranRef varchar(50),
            @GLSourceRef varchar(20),
            @Company_Banks_ID int,
            @Transaction_Type_ID tinyint,
            @Transaction_Date datetime,
            @Months_ID tinyint,
            @Years_ID smallint,
            @Ref_No varchar(20),
            @Description varchar(50),
            @OrigAmount money,
            @Company_ID int


    SELECT 
        @Company_Banks_ID = AW_Company_Banks_ID,
        @Transaction_Type_ID = Sys_AB_Transaction_Types_ID,
        @Transaction_Date = Transaction_Date,
        @Months_ID = Slu_AW_Months_ID,
        @Years_ID = Slu_AW_Years_ID,
        @Ref_No = Reference_No,
        @Description = LEFT('REVERSAL: Ref No ' + ISNULL(Reference_No, '') + ' - ' + ISNULL(Transaction_Description, ''), 50),
        @OrigAmount = ISNULL(Amount, 0),
        @Company_ID = AW_User_Companies_ID
    FROM AB_Cash_Book_Transactions
    WHERE AB_Cash_Book_Transactions_ID = @CBReversalTranID


    BEGIN TRANSACTION

    	BEGIN
    		SET @OrigAmount = -@OrigAmount
    	
    		INSERT INTO AB_Cash_Book_Transactions
                (
        			AW_Company_Banks_ID, 
        			Sys_AB_Transaction_Types_ID, 
        			Transaction_Date,
        			Slu_AW_Months_ID, 
        			Slu_AW_Years_ID,
        			Reference_No, 
        			Transaction_Description, 
        			Amount,
                    Recon_Amount,
        			[User_ID],
        			AW_User_Companies_ID
                )
    		VALUES
                (
                    @Company_Banks_ID,
                    @Transaction_Type_ID,
                    @Transaction_Date,
                    @Months_ID,
                    @Years_ID,
                    @Ref_No,
                    @Description,
                    @OrigAmount,
                    0,
                    @UserID,
                    @Company_ID
                )
    		
    		SET @NextCashbookID = (SELECT scope_Identity())
	
            IF @InsertGLTran = 1        -- 1 = YES, 0 = NO 
                BEGIN

-------------------------------------------------------------------------
-- To bring in the Cash Book Ref # into the GL Transactions -------------
-------------------------------------------------------------------------
                    SELECT @GLSourceRef = Transaction_Code
                    FROM Sys_AB_Transaction_Types
                    WHERE Sys_AB_Transaction_Types_ID = @Transaction_Type_ID


                    SET @GLSourceRef = LEFT(RTRIM(LTRIM(@Ref_No)), 20)
                    SET @Description = LEFT(@Description, 50)
-------------------------------------------------------------------------

            		SELECT @Banks_GL_Account_ID = ISNULL(AB_Accounts_ID, 1)
            		FROM AW_Company_Banks 
            		WHERE AW_User_Companies_ID = @Company_ID AND
                          AW_Company_Banks_ID = @Company_Banks_ID
            	
            		EXEC sp_AB_Insert_GL_Transactions
                                        @Description,
                                        @Transaction_Type_ID,
                                        @Banks_GL_Account_ID,
                                        @Transaction_Date,
                                        @GLSourceRef,
                                        @Months_ID,
                                        @Years_ID,
                                        @NextCashbookID,
                                        @OrigAmount,
                                        @UserID,
                                        @Company_ID
                END

    	END

    COMMIT TRANSACTION


RETURN @NextCashbookID


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AB_Reverse_Cash_Book_Transaction_Details
--Purpose       :Reverse ONE Cash Book Transactions 
--              :NB: By Default also Inserts a GLTransaction record
--Functionality :Insert
--Parameters    :
--Date          :2004/10/19
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Reverse_Cash_Book_Transaction_Details
    (
        @CB_Header_ID int,
        @AB_Accounts_ID int,
    	@Tax_Method tinyint,
    	@Amount money,
    	@Tax_Code tinyint,
    	@Tax_Amount money,
    	@Net_Amount money,
    	@Comments varchar(50),
    	@User_ID int,
    	@Company_ID int,
        @InsertGLTran bit = 1
    )

AS

SET NOCOUNT ON

    DECLARE @Cashbook_Trans_Type_ID int,
            @Months_ID tinyint,
            @Years_ID smallint,
            @VAT_GL_Acc_ID int,
            @New_CB_Details_ID int,
            @Transaction_Date datetime,
            @GLSourceRef varchar(20),
            @Ref_No varchar(20),
            @CB_Description varchar(50)
-------------------------------------------------------------------------
    
	BEGIN TRANSACTION


        --> Get the newly REVERSED TRANSACTION info
		SELECT @Cashbook_Trans_Type_ID = Sys_AB_Transaction_Types_ID,
               @Transaction_Date = Transaction_Date,
               @Months_ID = Slu_AW_Months_ID,
               @Years_ID = Slu_AW_Years_ID,
               @Ref_No = Reference_No,
               @CB_Description = LEFT(Transaction_Description, 50)
		FROM AB_Cash_Book_Transactions
		WHERE AB_Cash_Book_Transactions_ID = @CB_Header_ID


		INSERT INTO AB_Cash_Book_Transaction_Details
            (
    			AB_Cash_Book_Transactions_ID, 
    			AB_Accounts_ID, 
    			Sys_AW_Tax_Methods_ID,
    			Amount, 
    			Sys_AW_Tax_Codes_ID,
    			Tax_Amount, 
    			Net_Amount, 
    			Comments,
    			Date_Captured,
    			[User_ID],
    			AW_User_Companies_ID
            )
		VALUES
            (
                @CB_Header_ID ,
                @AB_Accounts_ID ,
                @Tax_Method ,
                @Amount ,
                @Tax_Code ,
                @Tax_Amount ,
                @Net_Amount ,
                @Comments ,
                getdate(),
                @User_ID,
                @Company_ID
            )
		
        SET @New_CB_Details_ID = (SELECT scope_Identity())
    			

        IF @InsertGLTran = 1    -- 1 = YES, 0 = NO 
        	BEGIN

        		IF ISNULL(@Tax_Amount, 0) <> 0
        			BEGIN
        				SET @Amount = (ISNULL(@Amount, 0) - ISNULL(@Tax_Amount, 0))
        			END

-------------------------------------------------------------------------
-- To bring in the Cash Book Ref # into the GL Transactions -------------
-------------------------------------------------------------------------
                    SELECT @GLSourceRef = Transaction_Code
                    FROM Sys_AB_Transaction_Types
                    WHERE Sys_AB_Transaction_Types_ID = @Cashbook_Trans_Type_ID


                    SET @GLSourceRef = LEFT(RTRIM(LTRIM(@Ref_No)), 20)
--                    SET @CB_Description = LEFT(@CB_Description, 50)
-------------------------------------------------------------------------

        		EXEC sp_AB_Insert_GL_Transactions
                        @CB_Description,
                        @Cashbook_Trans_Type_ID,	
                        @AB_Accounts_ID,
                        @Transaction_Date,
                        @GLSourceRef,
                        @Months_ID,
                        @Years_ID,
                        @CB_Header_ID,
                        @Amount,
                        @User_ID,
                        @Company_ID	
        		
                --> VAT Control
        		IF ISNULL(@Tax_Amount, 0) <> 0
        			BEGIN 			
        				SELECT @VAT_GL_Acc_ID = AB_Accounts_ID
        				FROM AB_Control_Accounts
        				WHERE Control_Number = 401		
    
                        EXEC sp_AB_Insert_GL_Transactions
                                @CB_Description,
                                @Cashbook_Trans_Type_ID,
        						@VAT_GL_Acc_ID,
                                @Transaction_Date,
                                @GLSourceRef,
                                @Months_ID,
                                @Years_ID,
                                @CB_Header_ID,
                                @Tax_Amount,
                                @User_ID,
                                @Company_ID
        			END
        	END

	COMMIT TRAN
	
    RETURN @New_CB_Details_ID

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Reverse_General_Journal
--Purpose       :Reverse ONE General Journal
--Functionality :Insert REVERSAL GL Journal for the SAME JOURNAL TYPEID and
--              :Posts Reversal GL Transactions
--Date          :2009/03/10
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Reverse_General_Journal
    (
        @JournalID int,
        @MonthID int,
        @YearID int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @JnlID int,
            @JnlDate datetime,
            @JnlShortDate varchar(20),
            @JnlRef varchar(30),
            @JnlNarration varchar(200),
            @JnlMonthID int,
            @JnlYearID int,
            @ReversalNarration varchar(300),
            @GLNarration varchar(50),
            @ReversalDate datetime,
            @JNLHeaderID int,
            @NextGLTranID int,
            @GLAccountID int,
            @Amount money,
            @Notes varchar(50),
            @ReversalAmount money,
            @InsertGLTran bit,
            @GLSourceRef varchar(20),
            @JNLTypeID tinyint,
            @ReturnValue int
            

    SET @ReversalDate = getdate()
    SET @InsertGLTran = 0              --0 = DO NOT insert a GL Transaction in JNL Details
    SET @NextGLTranID = 0
    SET @ReturnValue = 0


    BEGIN

        ---------------------------------------------------------------------
        --> Get the Journal values
        ---------------------------------------------------------------------
        SELECT @JnlID = AB_Journals_ID,
               @JnlDate = Journal_Date,
               @JnlShortDate = LEFT(CONVERT(CHAR(10), Journal_Date, 121), 10),
               @JnlRef = Journal_Reference,
               @JnlNarration = Journal_Narration,
               @JnlMonthID = Slu_AW_Months_ID,
               @JnlYearID = Slu_AW_Years_ID
        FROM AB_Journals
        WHERE AW_User_Companies_ID = @CompanyID AND
              AB_Journals_ID = @JournalID


        SET @GLNarration = 'REVERSAL of Journal ' + 
                            LTRIM(RTRIM(@JnlRef)) +
                            ' dated ' +
                            @JnlShortDate

        SET @GLNarration = LEFT(@GLNarration, 50)

        SET @ReversalNarration = LEFT(@GLNarration  + ' - ' + @JnlNarration, 200)


        ---------------------------------------------------------------------
        --> Get the Journal TypeID (Sys_AB_Transaction_Types_ID)
        ---------------------------------------------------------------------
        SELECT @JNLTypeID = Sys_AB_Transaction_Types_ID
        FROM AB_GL_Transactions
        WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Months_ID = @JnlMonthID AND
              Slu_AW_Years_ID = @JnlYearID AND
              CONVERT(CHAR(19), AB_Transaction_Date) = CONVERT(CHAR(19), @JnlDate) AND
             (AB_Transaction_Ref = CONVERT(int, @JnlRef) OR
              AB_Transaction_Ref = CONVERT(int, @JnlID))

        SET @JNLTypeID = ISNULL(@JNLTypeID, 0)

        IF @JNLTypeID = 0
            BEGIN
                SET @JNLTypeID = 15
            END


        ---------------------------------------------------------------------
        --> Create JOURNAL HEADER for REVERSAL Journal
        ---------------------------------------------------------------------
        EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                15,
                @CompanyID

		EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                @ReversalDate,
                @NextGLTranID,
                @ReversalNarration,
                @MonthID,
                @YearID,
                @UserID,
                @CompanyID


        ------------------------------------------------------------
        --> INSERT Reversal DETAIL items
        ------------------------------------------------------------
    	DECLARE Reversal_Cursor CURSOR FOR
            (
                SELECT AB_Accounts_ID,
                       Amount,
                       Notes
                FROM AB_Journal_Details
                WHERE AW_User_Companies_ID = @CompanyID AND
                      AB_Journals_ID = @JournalID
            )

    	OPEN Reversal_Cursor

        	FETCH NEXT FROM Reversal_Cursor 
        	INTO
                @GLAccountID,
                @Amount,
                @Notes

        	WHILE @@FETCH_STATUS = 0
        	BEGIN

                SET @ReversalAmount = @Amount * -1
                SET @GLSourceRef = CONVERT(varchar(20), @JNLHeaderID)

                --> INSERT JOURNAL DETAIL
                EXEC sp_AB_Insert_Journal_Detail
                        @JNLHeaderID,
                        @GLAccountID,
                        @ReversalAmount,
                        @Notes,
                        @UserID,
                        @CompanyID,
                        @InsertGLTran


                --> INSERT GL TRANSACTION
                EXEC sp_AB_Insert_GL_Transactions
                        @GLNarration,
                        @JNLTypeID,
                        @GLAccountID,
                        @ReversalDate,
                        @GLSourceRef,
                        @MonthID,
                        @YearID,
                        @NextGLTranID,
                        @ReversalAmount,
                        @UserID,
                        @CompanyID


            	FETCH NEXT FROM Reversal_Cursor 
            	INTO
                    @GLAccountID,
                    @Amount,
                    @Notes

        	END

    	CLOSE Reversal_Cursor

    	DEALLOCATE Reversal_Cursor


        SET @ReturnValue = @JNLHeaderID

    END



RETURN @ReturnValue


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






-------------------------------------------------------------------------------------------------------
--Description   : sp_AB_Search_Cash_Book_Transactions
--Purpose       : Returns The Cash Book Transactions for specific Bank and Tansaction Type and Accounting Period
--Functionality : Select
--Parameters    : 
--Date          : 2001/07/05
--Authors       : Charl
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE PROCEDURE sp_AB_Search_Cash_Book_Transactions

(
    @Company_Banks_ID int,
    @Transaction_Type_ID int,
	@Months_ID tinyint,
	@Years_ID smallint,
	@Company_ID int
)

AS
SET NOCOUNT ON
SELECT AB_Cash_Book_Transactions_ID AS [ID], 
	AW_Company_Banks_ID AS Bank, 
	Sys_AB_Transaction_Types_ID AS [Transaction Types], 
	Transaction_Date AS [Date], 
	Slu_AW_Months_ID AS [Month], 
	Slu_AW_Years_ID AS [Year],
	Reference_No AS [Ref No], 
	Transaction_Description AS [Description], 
	Amount, 
	Date_Captured AS [Date Captured], 
	User_ID AS [User ID], 
	AW_User_Companies_ID AS [Company ID], 
	Slu_AW_Active_ID AS [Active] 
FROM AB_Cash_Book_Transactions 
WHERE AW_Company_Banks_ID = @Company_Banks_ID AND 
	Sys_AB_Transaction_Types_ID = @Transaction_Type_ID AND 
	Slu_AW_Months_ID = @Months_ID AND
	Slu_AW_Years_ID = @Years_ID AND
	AW_User_Companies_ID = @Company_ID 






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :sp_AB_Select_AB_Accounts
--Purpose       :General Ledger and Budget Accounts
--Date          :2002/02/19
--Authors       :TB
--MODS          :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :03/08/03 - Added [Account Balance]
--              :22/08/03 - Added [Movement]
--              :01/05/05 - Added [Controllable]
--              :02/05/05 - Added [AccountTypeID] to limit [Controllable]
--2004.3.7      :23/09/07 - Added [Account Group]
--              :28/09/07 - Added [Account Division]
--RL	V6.2	2016-06-24	:Added Lup_AB_Account_Types_ID
-----------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_AB_Accounts]
    (
        @AB_Accounts_ID int,
        @Company_ID int 
    )

AS

SET NOCOUNT ON

    SELECT
        a.AB_Accounts_ID AS [ID], 
        a.[Description] AS [Description], 
        a.Account_Number AS [Account Number], 
        a.Sys_AB_Account_Categories_ID AS [Account Categories], 
        b.Sys_AB_I1_ID AS [AccountTypeID],
        a.Sys_AW_Tax_Codes_ID AS [Tax Code],
        a.Lup_AB_Cost_Centers_ID AS [Cost Centers],
        a.Lup_AB_Account_Divisions_ID AS [Account Division],
        a.Lup_AB_Account_Groups_ID AS [Account Group],
        a.Slu_AW_Active_ID AS [Active], 
        a.AB_Account_Balance AS [Account Balance], 
        a.Opening_Balance AS [Opening Balance], 
        ISNULL(a.AB_Account_Balance, 0) - ISNULL(a.Opening_Balance, 0) AS [Movement],
        a.AW_YesNo_Controllable_ID AS [Controllable],
        a.Date_Captured AS [Date Captured], 
        a.[User_ID] AS [User ID],
        a.AW_User_Companies_ID AS [Company ID],
        a.Lup_AB_Account_Departments_ID  AS [Account Department]      
    FROM AB_Accounts a
        INNER JOIN Sys_AB_Account_Categories b
            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
    WHERE a.AB_Accounts_ID = @AB_Accounts_ID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description   :sp_AB_Select_AB_Accounts_Pick_List
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/19
--Authors       :TB
--MODS          :19/12/02 - Modified Account_Number alias length
--              :27/01/05 - Changed alias for the Account Number to [Number]
----------------------------------------------------------------------------

CREATE       PROCEDURE sp_AB_Select_AB_Accounts_Pick_List
    (
        @CompanyID int 
    )

AS

SET NOCOUNT ON

    SELECT
        AB_Accounts_ID AS [ID], 
        ISNULL(Description, '') AS [Account], 
        ISNULL(Account_Number, '') AS [Number]
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY Description ASC


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Accounts
--Functionality :Returns Account Info
--Parameters    :
--Date          :2013/10/28
--Authors       :RL
--Version       :5.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Select_Accounts]
AS

SET NOCOUNT ON

	SELECT ac.AB_Accounts_ID AS [ID],
		   IsNull(ac.Description,'') AS [Account_Name],
		   at.Description AS [Account_Status],
		   uc.Company_Name As [Company_Name]
	FROM AB_Accounts ac
	INNER JOIN Slu_AW_Active at
	ON ac.Slu_AW_Active_ID = at.Slu_AW_Active_ID
	Inner Join AW_User_Companies uc
	On ac.AW_User_Companies_ID = uc.AW_User_Companies_ID 	
	ORDER BY IsNull(ac.Description,'') ASC

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Bank_IBS_Rules
--Purpose       :Select IBS Bank Rules for ONE Bank
--Date          :22 MAR 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Select_Bank_IBS_Rules
	(
        @CompanyBanksID int
	)

AS

SET NOCOUNT ON


    SELECT Slu_AB_Bank_IBS_Rules_ID AS [ID],
           AW_Company_Banks_ID AS [CompanyBanksID],
           Header_Rows AS [HeaderRows],
           Footer_Rows AS [FooterRows],
           Delimiter AS [Delimiter],
           Date_Field_No AS [DateFieldNo],
           Description_Field_No AS [DescriptionFieldNo],
           Amount_Field_No AS [AmountFieldNo],
           Slu_AW_Date_Format_ID AS [DateFormatID],
           Combine_Field_Nos AS [CombineFieldNos],
           TranType_Field_No AS [TranTypeFieldNo],
           Cheque_Field_No AS [ChequeFieldNo],
           Cheque_Identifier AS [ChequeIdentifier],
           Cheque_No_From AS [ChequeNoFrom],
           Cheque_No_To AS [ChequeNoTo],
           [User_ID] AS [UserID],
           Slu_AW_Active_ID AS [ActiveID]
    FROM Slu_AB_Bank_IBS_Rules
    WHERE AW_Company_Banks_ID = @CompanyBanksID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Bank_TranType_IBS_Maps
--Purpose       :Select Cask Book IBS History Detail rows of a HeaderID
--Date          :28 FEB 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Select_Bank_TranType_IBS_Maps
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON


        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 [UserID],
               AW_User_Companies_ID as [CompanyID],
               Slu_AW_Active_ID As [Active]
        From Lup_AB_Transaction_Type_Maps
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Bank], [Mapping CSV List]


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Batch_CashBook_Items
--Purpose       :Select Batch CashBook Items data
--Functionality :!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!
--Date          :2005/06/19
--Authors       :TB
--MODS          :06/01/06 - Removed [@CBBatchID int] input parameter and its
--              :           corresponding reference in the WHERE clause
--              :12/01/06 - Removed Batch_Total and Allocated fields
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Select_Batch_CashBook_Items
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

	SET @sql = ' SELECT '
--Header
    SET @sql = @sql + ' AB_Cash_Book_Batches_ID AS [BatchID], '
    SET @sql = @sql + ' AW_Company_Banks_ID AS [BankID], '
    SET @sql = @sql + ' Sys_AB_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + ' Slu_AW_Years_ID AS [YearID], '
--     SET @sql = @sql + ' Batch_Total AS [Batch Total], '
--     SET @sql = @sql + ' Allocated AS [Allocated], '
--Grid
    SET @sql = @sql + ' Transaction_Date AS [Date], '
    SET @sql = @sql + ' Ref_No AS [Ref No], '
    SET @sql = @sql + ' Description AS [Details], '
    SET @sql = @sql + ' Amount AS [Amount], '
    SET @sql = @sql + ' AB_Accounts_ID AS [GL Account], '
    SET @sql = @sql + ' Sys_AW_Tax_Methods_ID AS [Tax Method], '
    SET @sql = @sql + ' Split_Amount AS [Split Amount], '
    SET @sql = @sql + ' VAT_Amount AS [VAT], '
    SET @sql = @sql + ' Net_Amount AS [Total] '

    SET @sql = @sql + ' FROM AB_Cash_Book_Batches '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + ' ORDER BY Ref_No '




SET NOCOUNT OFF


EXEC (@sql)




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--------------------------------------------------------------------------------
--Description   :sp_AB_Select_Budget_Month_Actuals
--Purpose       :Returns the GL monthly transaction totals
--Functionality :
--Parameters    :
--Date          :2003/04/07
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Added ORDER BY in [CurrentBudget] and [NextBudget] subQueries to
--              :           handle MULTIPLE BUDGETS for the SAME Account/Month/Year !!! TCRUST !!!
--------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Select_Budget_Month_Actuals
    (
        @CompanyID int,
        @GLAccount int,
        @MonthID int,
        @ThisYearID int
    )

AS

SET NOCOUNT ON

	DECLARE @NextYearID int,
            @PrevYearID int

    SET @PrevYearID = @ThisYearID - 1
    SET @NextYearID = @ThisYearID + 1

    SELECT
        ISNULL(
                (
                    SELECT ISNULL(SUM(AB_Transaction_Amount), 0)
                    FROM AB_GL_Transactions
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          AB_Accounts_ID = @GLAccount AND
                          Slu_AW_Months_ID = @MonthID AND
                          Slu_AW_Years_ID = @ThisYearID AND
                          Sys_AB_Transaction_Types_ID <> 16
                    GROUP BY Slu_AW_Months_ID, Slu_AW_Years_ID
                ), 0) AS [SumCurrent],

        ISNULL(
                (
                    SELECT TOP 1 ISNULL(Budget_Amount, 0)
                    FROM AB_Budgets
                    WHERE AW_User_Companies_ID = @CompanyID AND
                        AB_Accounts_ID = @GLAccount AND
                        Slu_AW_Months_ID = @MonthID AND
                        Slu_AW_Years_ID = @ThisYearID
                    ORDER BY Date_Captured DESC
                ), 0) AS [CurrentBudget]


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Select_CashBook_Bank_Statements
--Purpose       :Retrieves Cash Book Transactions in Date Order 
--Functionality : 
--Parameters    : 
--Date          :2001/02/07
--Authors       :TB
--Version       :1
--MODS          :16/09/02 - Altered ORDER to ASCENDING Transaction Date
-------------------------------------------------------------------------------
CREATE    PROCEDURE sp_AB_Select_CashBook_Bank_Statements 
    (
    	@CompanyBanksID int,
    	@FromDate datetime,
    	@ToDate Datetime,
    	@CompanyID int
    )

AS

SET NOCOUNT ON
	
	SELECT
        a.AB_Cash_Book_Transactions_ID AS [ID],
        a.Transaction_Date AS [Date],
        a.Reference_No AS [Ref No],
        c.[Description] AS [Month],
        d.[Description] AS [Year],
        b.Transaction_Code AS [Code],
        b.[Description] AS [Transaction Type] ,
        a.Transaction_Description AS [Description],
        a.Amount
	FROM AB_Cash_Book_Transactions a
        LEFT JOIN Sys_AB_Transaction_Types b
		    ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID
        LEFT JOIN Slu_AW_Months c
            ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years d
            ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID
	WHERE AW_Company_Banks_ID = @CompanyBanksID AND
          AW_User_Companies_ID = @CompanyID AND
          Transaction_Date >= @FromDate AND 							 
          Transaction_Date <= @ToDate
	ORDER BY Transaction_Date


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Detail
--Purpose       :Select Cask Book IBS History Detail rows of a HeaderID
--Date          :28 FEB 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AB_Select_Cash_Book_IBS_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_IBS_Detail_ID AS [ID],
           AB_Cash_Book_IBS_Header_ID AS [HeaderID],
           Post AS [Post],
           Sys_AB_Transaction_Types_ID AS [Transaction Type],
           Transaction_Date AS [Date],
           Ref_No AS [Ref No],
           AB_Accounts_ID AS [GL Account],
           Sys_AW_Tax_Methods_ID AS [Tax Method],
           Post_Description AS [Description],
           Amount AS [Amount],
           Tax_Amount AS [Tax],
           Net_Amount AS [Net],
           Comments AS [Comments]
    FROM AB_Cash_Book_IBS_Detail
    WHERE AB_Cash_Book_IBS_Header_ID = @HeaderID AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY AB_Cash_Book_IBS_Detail_ID




SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Detail_Splits
--Purpose       :Select Cask Book IBS History Detail rows of a HeaderID
--Date          :16 MAR 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Select_Cash_Book_IBS_Detail_Splits
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_IBS_Detail_Splits_ID AS [ID],
           AB_Cash_Book_IBS_Detail_ID AS [DetailID],
           AB_Accounts_ID AS [GL Acct],
           Sys_AW_Tax_Methods_ID AS [Method],
           Amount AS [Split Amount],
           Tax_Amount AS [Split Tax],
           Net_Amount AS [Split Net]
    FROM AB_Cash_Book_IBS_Detail_Splits
    WHERE AB_Cash_Book_IBS_Header_ID = @HeaderID AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY AB_Cash_Book_IBS_Detail_Splits_ID




SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Header
--Purpose       :Select ONE Cask Book IBS History Header row
--Date          :28 FEB 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Select_Cash_Book_IBS_Header
	(
        @HeaderID int
	)

AS

SET NOCOUNT ON


    SELECT AB_Cash_Book_IBS_Header_ID AS [ID],
           AW_Company_Banks_ID AS [CompanyBanksID],
           Posting_Type AS [PostingType],
           Slu_AW_Banks_ID AS [BankID],
           Date_Posted AS [DatePosted],
           Start_Date AS [StartDate],
           End_Date AS [EndDate],
           Slu_AW_Months_ID AS [MonthID],
           Slu_AW_Years_ID AS [YearID],
           Import_Filename AS [ImportFile],
           Auto_Recon AS [AutoRecon],
           [User_ID] AS [UserID],
           Slu_AW_Active_ID AS [ActiveID]
    FROM AB_Cash_Book_IBS_Header
    WHERE AB_Cash_Book_IBS_Header_ID = @HeaderID













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Maps
--Purpose       :Select IBS CashBook Mapping data
--Functionality :
--Date          :2010/02/13
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Select_Cash_Book_IBS_Maps
    (
        @CompanyBanksID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_IBS_Map_ID AS [MapID],
           AW_Company_Banks_ID AS [CompanyBanksID],
           Post AS [Post],
           Sys_AB_Transaction_Types_ID AS [TranTypeID],
           Map_1 AS [Map1],
           Map_2 AS [Map2],
           Map_3 AS [Map3],
           AB_Accounts_ID AS [GLAccountID],
           Sys_AW_Tax_Methods_ID AS [TaxMethod],
           Bank_Description AS [Description],
           Comments AS [Comments]
    FROM AB_Cash_Book_IBS_Map
    WHERE AW_User_Companies_ID = @CompanyID AND
          AW_Company_Banks_ID = @CompanyBanksID




SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Maps_Edit
--Purpose       :Select IBS CashBook Mapping data for editing
--Functionality :
--Date          :2010/02/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AB_Select_Cash_Book_IBS_Maps_Edit
    (
        @CompanyBanksID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_IBS_Map_ID AS [MapID],
           AW_Company_Banks_ID AS [CompanyBanksID],
           Post AS [Post],
           Sys_AB_Transaction_Types_ID AS [Transaction Type],
           AB_Accounts_ID AS [GL Account],
           Sys_AW_Tax_Methods_ID AS [Tax Method],
           Comments AS [Comments],
           Bank_Description AS [Bank Description],
           Map_1 AS [Map 1],
           Map_2 AS [Map 2],
           Map_3 AS [Map 3]
    FROM AB_Cash_Book_IBS_Map
    WHERE AW_User_Companies_ID = @CompanyID AND
          AW_Company_Banks_ID = @CompanyBanksID
    ORDER BY [MapID], [CompanyBanksID]




SET NOCOUNT OFF























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Maps_Import
--Purpose       :Select IBS CashBook Mapping data for import
--Functionality :
--Date          :2010/03/01
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AB_Select_Cash_Book_IBS_Maps_Import
    (
        @Option tinyint,
        @BankID smallint,
        @TranTypeID tinyint,
        @Maps varchar(300),
        @ActiveID tinyint,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int


    SET @RetCode = 0


    IF @Option = 0
        BEGIN
        	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],
        		   Slu_AW_Active_ID as [Active] 
        	FROM Lup_AB_Transaction_Type_Maps
        	WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Bank], [Mapping CSV List]
        END
    ELSE
    IF @Option = 1
        BEGIN
            INSERT INTO Lup_AB_Transaction_Type_Maps
                (
                    Slu_AW_Banks_ID,
                    Sys_AB_Transaction_Types_ID,
                    Mapping_CSV,
                    User_ID,
                    AW_User_Companies_ID,
                    Slu_AW_Active_ID
                )
            VALUES
                (
                    @BankID,
                    @TranTypeID,
                    @Maps,
                    @UserID,
                    @CompanyID,
                    @ActiveID
                )

            SELECT @RetCode = Scope_Identity()

            RETURN @RetCode

        END



SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description	:sp_AB_Select_Cash_Book_IBS_Notes
--Purpose       :SELECT Cash Book IBS notes 
--Date			:2010/03/03
--Authors		:TB
--MODS    		:
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Select_Cash_Book_IBS_Notes
	(
		@CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT  AB_Cash_Book_IBS_Notes_ID AS [NoteID],
            Note AS [Notes],
            [User_ID] AS [UserID],
            AW_User_Companies_ID AS [CompanyID]
    FROM AB_Cash_Book_IBS_Notes
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY Date_Captured ASC













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_IBS_Posting
--Purpose       :Selects Cask Book Posting Detail for a month
--Date          :16 APR 2010
--Authors       :TB
--Mods          :
--2004.4.9      :23/09/10 - Added transaction search and changed to dynamic SQL
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Select_Cash_Book_IBS_Posting
    (
        @CompanyBanksID int,
        @Option tinyint,
        @TranTypeID tinyint,
    	@MonthID tinyint,
    	@YearID smallint,
        @chkSearch tinyint,
        @Search varchar(50),
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000),
            @Filter varchar(100)

    IF @chkSearch = 1
        BEGIN
        	SET @Filter = '%' + RTRIM(LTRIM(@Search)) + '%'
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' t.AB_Cash_Book_Transactions_ID AS [ID], '
    SET @sql = @sql + ' t.AW_Company_Banks_ID AS [CompanyBankID], '
    SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [Date], '
    SET @sql = @sql + ' tt.Transaction_Code AS [Transaction Type], ' 
    SET @sql = @sql + ' t.Reference_No AS [Ref No], '
    SET @sql = @sql + ' t.Transaction_Description AS [Description], '
    SET @sql = @sql + ' g.[Description] AS [GL Account], '
    SET @sql = @sql + ' tm.[Description] AS [Tax Method], '
    SET @sql = @sql + ' d.Amount AS [Amount], '
    SET @sql = @sql + ' d.Tax_Amount AS [Tax], '
    SET @sql = @sql + ' d.Net_Amount AS [Net], '
    SET @sql = @sql + ' d.Comments, '
    SET @sql = @sql + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '
    SET @sql = @sql + ' FROM AB_Cash_Book_Transactions t '
    SET @sql = @sql + '     LEFT JOIN  AB_Cash_Book_Transaction_Details d '
    SET @sql = @sql + '         ON t.AB_Cash_Book_Transactions_ID = d.AB_Cash_Book_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Transaction_Types tt '
    SET @sql = @sql + '         ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts g '
    SET @sql = @sql + '         ON d.AB_Accounts_ID = g.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Tax_Methods tm '
    SET @sql = @sql + '         ON d.Sys_AW_Tax_Methods_ID = tm.Sys_AW_Tax_Methods_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON t.[User_ID] = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND t.AW_Company_Banks_ID = ' + CONVERT(varchar(10), @CompanyBanksID) + ' '
    SET @sql = @sql + '   AND t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' '
    SET @sql = @sql + '   AND t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    IF @Option = 1
        BEGIN
            SET @sql = @sql + '   AND t.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '
        END


    IF @chkSearch = 1
        BEGIN
            SET @sql = @sql + ' AND (t.Transaction_Description LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  t.Reference_No LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), t.Amount) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  g.[Description] LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), d.Amount) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), d.Net_Amount) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  d.[Comments] LIKE ' + '''' + @Filter+ ''''  + ') '
        END


    SET @sql = @sql + ' ORDER BY [Date] '



    EXEC (@sql)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/03/08
--Authors       :TB
--MODS          :23/07/02 - Fixed BANK ACCOUNT selection of the Company
--              :           in Cash Up & Banking 'Bank Account' DBC
--              :24/11/02 - Added Option 10 - Get CASH BOOK's GL Account Balance
--              :04/02/03 - Added Option 11 - Tax Methods (CB Header) to ORDER
--              :           options in ALPHA sequence & put <None> first in list
--              :27/03/04 - Removed ORDER BY in option 11  - Tax Methods (CB Header)
--              :           to sequence & put <Inclusive> first in list
--              :16/04/04 - Replaced ORDER BY in option 11  - Tax Methods (CB Header)
--              :           to sequence & put <None> first in list (for Deposits)
--              :23/08/05 - Added filter for ACTIVE BANK ACCOUNTS ONLY in Option 1
--2004.2.7      :25/03/06 - Added GL Account with Account Number in option 12
--2004.4.8      :19/02/10 - Added Transaction Type Map in Option 13 (CBIBS)
--              :28/02/10 - Added Tax Method WITHOUT 'Exclusive' in Option 14 (CBIBS)
--              :19/03/10 - Added Transaction Type CODE in Option 15 (CBIBS)
--              :22/03/10 - Added Date Formats in Option 16 (CBIBS)
--              :24/03/10 - Added Banks in Option 17 (CBIBS)
--2004.4.9      :13/09/10 - Replaced gl.AB_Account_Balance with SUM(ISNULL(t.AB_Transaction_Amount, 0))
--              :           in @Option = 10 Get CASH BOOK BALANCE (GL Account Balance)
--2004.5.1      :10/06/11 - Modified Option 5, 12 to only select ACTIVE GL Accounts
-------------------------------------------------------------------------------

CREATE                        PROCEDURE sp_AB_Select_Cash_Book_Lups
    (
    	@Option tinyint,
        @CompanyID  int = 0,
    	@ValueID int = 0
    )

AS

SET NOCOUNT ON

-- @Option Values
-----------------
-- 1=Bank
-- 2=Transaction Type
-- 3=Months
-- 4=Years
-- 5=GL Account
-- 6=Tax Codes
-- 7=Tax Methods
-- 8=Active
-- 9=Transaction Type
--10=Cash Book Balance
----------------------

    --> Banks
    IF @Option = 1
        SELECT cb.AW_Company_Banks_ID AS [ID], 
               ISNULL(b.[Description], '') + 
               ISNULL(' - ' + cb.Account_Number, '') + 
               ISNULL(' - ' + cb.Account_Name, '') AS [Bank]
        FROM AW_Company_Banks cb 
            INNER JOIN dbo.Slu_AW_Banks b 
                ON cb.Slu_AW_Banks_ID = b.Slu_AW_Banks_ID 
        WHERE cb.AW_User_Companies_ID = @CompanyID AND
              cb.Slu_AW_Active_ID = 1
        ORDER BY b.[Description], cb.Account_Number, cb.Account_Name
    
    --> Transaction Type (Specific)
    ELSE
    IF @Option = 2
    	SELECT Sys_AB_Transaction_Types_ID as [ID], 
              [Description] AS [Type] 
    	FROM Sys_AB_Transaction_Types
    	WHERE Sys_AB_Transaction_Categories_ID = @ValueID
    --	ORDER BY [Description]    --Remove so that CASH BOOK TranType defaults to 'CHEQUE'
    
    --> Months
    ELSE
    IF @Option = 3
    	SELECT Slu_AW_Months_ID AS [ID], 
              [Description] AS [Month] 
    	FROM Slu_AW_Months
    
    --> Years
    ELSE
    IF @Option = 4
    	SELECT Slu_AW_Years_ID AS [ID], 
              [Description] AS [Year] 
    	FROM Slu_AW_Years
    
    --> GL Account
    ELSE
    IF @Option = 5
    	SELECT AB_accounts_ID AS [ID], 
              [Description] AS [GL Account] 
    	FROM AB_Accounts
    	WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
    	ORDER BY [Description]

    --> Tax Codes
    ELSE
    IF @Option = 6
    	SELECT Sys_AW_Tax_Codes_ID AS [ID], 
              [Description] AS [Tax Code],
    	Tax_Rate AS [Rate] 
    	FROM Sys_AW_Tax_Codes
    
    --> Tax Methods
    ELSE
    IF @Option = 7
    	SELECT Sys_AW_Tax_Methods_ID AS [ID],
              [Description] AS [Tax Method] 
    	FROM Sys_AW_Tax_Methods
    
    --> Active
    ELSE
    IF @Option = 8
    	
    	SELECT Slu_AW_Active_ID as [ID],
              [Description] AS [Active] 
    	FROM Slu_AW_Active
    
    --> Transaction Type (CASH BOOK)
    ELSE
    IF @Option = 9
    	SELECT Sys_AB_Transaction_Types_ID as [ID], 
              [Description] as [Type] 
    	FROM Sys_AB_Transaction_Types
        WHERE Sys_AB_Transaction_Categories_ID = 3 OR    --Cash Book
              Sys_AB_Transaction_Categories_ID = 4       --Credit Card
    	ORDER BY [Description]

    --> Get CASH BOOK BALANCE (GL Account Balance)
    ELSE
    IF @Option = 10
--     	SELECT gl.AB_Account_Balance AS [GLBalance]
--     	FROM AW_Company_Banks cb
--             LEFT JOIN AB_Accounts gl
--                 ON cb.AB_Accounts_ID = gl.AB_Accounts_ID
--         WHERE cb.AW_Company_Banks_ID = @ValueID

        --NEW 2004.4.9 - Eliminates out-of-balance GL Account Balances
        --                (result should be the same if GL Account Balance is correct)
        SELECT SUM(ISNULL(t.AB_Transaction_Amount, 0)) AS [GLBalance]
        FROM AB_GL_Transactions t
            LEFT join AW_Company_Banks b
                ON t.AB_Accounts_ID = b.AB_Accounts_ID
        WHERE b.AW_Company_Banks_ID = @ValueID AND
              b.Slu_AW_Active_ID = 1

    --> Tax Methods (CB Header)
    ELSE
    IF @Option = 11
    	SELECT Sys_AW_Tax_Methods_ID AS [ID],
              [Description] AS [Tax Method] 
    	FROM Sys_AW_Tax_Methods
        ORDER BY [Description] ASC

    --> GL Account with Account Number
    ELSE
    IF @Option = 12
    	SELECT AB_accounts_ID AS [ID], 
               ISNULL(LEFT(LTRIM(RTRIM(Account_Number)), 6) + ' ', '') + [Description] AS [GL Account] 
    	FROM AB_Accounts
    	WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
    	ORDER BY [Description]

    --> Transaction Type Map
    ELSE
    IF @Option = 13
    	SELECT Lup_AB_Transaction_Type_Maps_ID as [ID],
               Sys_AB_Transaction_Types_ID as [TranTypeID],
               Mapping_CSV as [Map] 
    	FROM Lup_AB_Transaction_Type_Maps
        WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Banks_ID = @ValueID AND
              Slu_AW_Active_ID = 1
    	ORDER BY [TranTypeID]

    --> Tax Methods (IBS - Exclusive ignored)
    ELSE
    IF @Option = 14
    	SELECT Sys_AW_Tax_Methods_ID AS [ID],
              [Description] AS [Tax Method] 
    	FROM Sys_AW_Tax_Methods
        WHERE Sys_AW_Tax_Methods_ID <> 2
        ORDER BY [Description] ASC

    --> Transaction Type CODE (CBIBS) (Specific)
    ELSE
    IF @Option = 15
    	SELECT Sys_AB_Transaction_Types_ID as [ID], 
              Transaction_Code AS [Type] 
    	FROM Sys_AB_Transaction_Types
    	WHERE Sys_AB_Transaction_Categories_ID = @ValueID
    --	ORDER BY [Description]    --Remove so that CASH BOOK TranType defaults to 'CHEQUE'

    --> Date Formats
    ELSE
    IF @Option = 16
    	SELECT Sys_AW_Date_Formats_ID AS [ID],
              [Description] AS [Description] 
    	FROM Sys_AW_Date_Formats

    --> Banks
    ELSE
	IF @Option = 17
		SELECT [Slu_AW_Banks_ID] as [ID], 
               [Description] as [Bank]
		FROM [Slu_AW_Banks]










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_Recon_History
--Purpose       :Returns Cash Book Reconciliation Transactions
--              :for specific Bank, Transaction Type, Accounting Period
--Functionality :Select
--Parameters    :
--Date          :2002/11/23
--Authors       :TB
--MODS          :27/11/02 - Removed Recon-Chk field
--              :09/01/03 - Changed SORT ORDER to TranType, TranDate
--2004.4.9      :22/09/10 - Added NEW input parameters @Month_ID and @Year_ID to fetch
--              :           RECONCILED transactions for ONE Accounting Period
--V6.4	RL	2018/02/07	:Added Sys_AB_Transaction_Types_ID 30 - Cash Book - Tax Payment
--V6.4	RL	2018/02/07	:Added Sys_AB_Transaction_Types_ID 31 - Cash Book - Tax Received
-------------------------------------------------------------------------------
-- NB: Actual DB Column** assignments to Aliases below is REQUIRED for setting
--     (adding or assigning) ADO Field.Values in the recordset
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Select_Cash_Book_Recon_History]
    (
        @Company_Banks_ID int,
    	@Company_ID int,
        @Reconciled tinyint,
    	@Month_ID tinyint,
        @Year_ID smallint,
        @Option tinyint
    )

AS

SET NOCOUNT ON


--> Unreconciled Transactions
    IF @Reconciled = 0
        BEGIN
        --> Cheques and other Debits
            IF @Option = 0
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 

                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
                     (tt.Sys_AB_Transaction_Types_ID = 9 OR         --Cash Book - Cheque
                      tt.Sys_AB_Transaction_Types_ID = 11 OR        --Cash Book - Interest Paid
                      tt.Sys_AB_Transaction_Types_ID = 12 OR        --Cash Book - Bank Charge
                      tt.Sys_AB_Transaction_Types_ID = 13 OR        --Credit Card - Charge
                      tt.Sys_AB_Transaction_Types_ID = 14 OR        --Credit Card - Payment
                      tt.Sys_AB_Transaction_Types_ID = 18 OR        --Cash Book - Debit Order
                      tt.Sys_AB_Transaction_Types_ID = 20 OR        --Cash Book - EFT Payment
                      tt.Sys_AB_Transaction_Types_ID = 21 OR		--Cash Book - EFT Payment          --Cash Book - Buy Association
					  tt.Sys_AB_Transaction_Types_ID = 30 OR		--Cash Book - Tax Payment       
					  tt.Sys_AB_Transaction_Types_ID = 31)			--Cash Book - Tax Received       
                ORDER BY tt.Transaction_Code, t.Transaction_Date  

        --> Deposits and other Credits
            ELSE
            IF @Option = 1
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 
    
                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
                     (tt.Sys_AB_Transaction_Types_ID = 10 OR        --Cash Book - Deposit
                      tt.Sys_AB_Transaction_Types_ID = 17 OR        --Cash Book - Interest Received
                      tt.Sys_AB_Transaction_Types_ID = 19)          --Cash Book - EFT Deposit
                ORDER BY tt.Transaction_Code, t.Transaction_Date 

        END

--> Reconciled Transactions
    ELSE
    IF @Reconciled = 1
        BEGIN
        --> Cheques and other Debits
            IF @Option = 0
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 

                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      t.Slu_AW_Months_ID = @Month_ID AND
                      t.Slu_AW_Years_ID = @Year_ID AND
                     (t.Sys_AB_Transaction_Types_ID = 9 OR         --Cash Book - Cheque
                      t.Sys_AB_Transaction_Types_ID = 11 OR        --Cash Book - Interest Paid
                      t.Sys_AB_Transaction_Types_ID = 12 OR        --Cash Book - Bank Charge
                      t.Sys_AB_Transaction_Types_ID = 13 OR        --Credit Card - Charge
                      t.Sys_AB_Transaction_Types_ID = 14 OR        --Credit Card - Payment
                      t.Sys_AB_Transaction_Types_ID = 18 OR        --Cash Book - Debit Order
                      t.Sys_AB_Transaction_Types_ID = 20 OR        --Cash Book - EFT Payment
                      t.Sys_AB_Transaction_Types_ID = 21 OR          --Cash Book - Buy Association
					  t.Sys_AB_Transaction_Types_ID = 30 OR			--Cash Book - Tax Payment       
					  t.Sys_AB_Transaction_Types_ID = 31)			--Cash Book - Tax Received       
                ORDER BY tt.Transaction_Code, t.Transaction_Date 

        --> Deposits and other Credits
            ELSE
            IF @Option = 1
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 
    
                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      t.Slu_AW_Months_ID = @Month_ID AND
                      t.Slu_AW_Years_ID = @Year_ID AND
                     (t.Sys_AB_Transaction_Types_ID = 10 OR        --Cash Book - Deposit
                      t.Sys_AB_Transaction_Types_ID = 17 OR        --Cash Book - Interest Received
                      t.Sys_AB_Transaction_Types_ID = 19)          --Cash Book - EFT Deposit
                ORDER BY tt.Transaction_Code, t.Transaction_Date 

        END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_Transactions
--Purpose       :Returns the Cash Book Transactions
--              :for specific Bank, Transaction Type
--Date          :2002/03/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE        PROCEDURE sp_AB_Select_Cash_Book_Transactions
    (
        @Company_Banks_ID int,
        @Transaction_Type_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Cash_Book_Transactions_ID AS [ID], 
           AW_Company_Banks_ID AS Bank, 
           Sys_AB_Transaction_Types_ID AS [Transaction Types], 
           Transaction_Date AS [Date], 
           Slu_AW_Months_ID AS [Month], 
           Slu_AW_Years_ID AS [Year],
           Reference_No AS [Ref No], 
           Transaction_Description AS [Description], 
           Amount
    FROM AB_Cash_Book_Transactions 
    WHERE AW_Company_Banks_ID = @Company_Banks_ID AND 
          Sys_AB_Transaction_Types_ID = @Transaction_Type_ID AND 
          AW_User_Companies_ID = @Company_ID 

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_Select_AB_Cash_Book_Transactions_Details
--Purpose       :Returns the Cash Book Transaction Details
--              :for a specific CB Transaction Header ID
--Date          :2002/03/08
--Authors       :TB
--Version       :1.0.0
--MODS          :19/10/04 - Added new field [GLAccountID], [TaxMethodID], [TaxCodeID]
--              :           for Cashbook Transaction Reversal
-------------------------------------------------------------------------------

CREATE        PROCEDURE sp_AB_Select_Cash_Book_Transactions_Details
    (
        @CB_Transactions_ID int
    )

AS

SET NOCOUNT ON

    SELECT CBTD.AB_Cash_Book_Transaction_Details_ID AS [ID], 
           CBTD.AB_Cash_Book_Transactions_ID AS [FK ID], 
           A.[Description] AS [GL Account],
           TM.[Description] AS [Tax Method], 
           TC.[Description] AS [Tax Code], 
           CBTD.Amount AS [Amount], 
           CBTD.Tax_Amount AS [Tax Amount],
           CBTD.Net_Amount AS [Net], 
           CBTD.Comments AS [Comments], 
           CBTD.Date_Captured AS [Date Captured],
           CBTD.[User_ID] AS [User ID], 
           CBTD.AW_User_Companies_ID AS [Company ID], 
           CBTD.Slu_AW_Active_ID AS [Active],
           CBTD.AB_Accounts_ID AS [GLAccountID],
           CBTD.Sys_AW_Tax_Methods_ID AS [TaxMethodID],
           CBTD.Sys_AW_Tax_Codes_ID AS [TaxCodeID]
    FROM AB_Cash_Book_Transaction_Details CBTD
        INNER JOIN AB_Accounts A
        	ON CBTD.AB_Accounts_ID = A.AB_Accounts_ID 
        INNER JOIN Sys_AW_Tax_Methods TM 
        	ON CBTD.Sys_AW_Tax_Methods_ID = TM.Sys_AW_Tax_Methods_ID
        INNER JOIN Sys_AW_Tax_Codes TC
        	ON CBTD.Sys_AW_Tax_Codes_ID  = TC.Sys_AW_Tax_Codes_ID
     WHERE CBTD.AB_Cash_Book_Transactions_ID = @CB_Transactions_ID 


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_Transactions
--Purpose       :Returns The Cash Book Transactions
--              :for specific Bank, Transaction Type, Accounting Period
--Date          :2002/03/08
--Authors       :TB
--Version       :1.0.0
--MODS          :22/11/02 - Removed AB_Cash_Book_Transactions.Account_Name AS [Bank]
--              :12/09/04 - Added LEFT JOIN AW_Users and [User] field
--              :19/10/04 - Added [TranTypeID] field for Cashbook transaction REVERSAL
--              :14/10/04 - Added @Transaction_Type_ID = 0 (ALL) option
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Select_Cash_Book_Transactions_History
    (
        @Company_Banks_ID int,
        @Transaction_Type_ID int,
    	@AW_Months_ID tinyint,
    	@AW_Years_ID smallint,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


    IF @Transaction_Type_ID = 0
        BEGIN
            SELECT
                t.AB_Cash_Book_Transactions_ID AS [ID], 
        --    	b.Account_Name AS [Bank], 
            	tt.[Description] AS [Transaction Types], 
            	t.Transaction_Date AS [Date], 
            	m.[Description] AS [Month], 
            	y.[Description] AS [Year],
            	t.Reference_No AS [Ref No], 
            	t.Transaction_Description AS [Description], 
            	t.Amount AS [Amount],
                u.UserName AS [User],
                t.Sys_AB_Transaction_Types_ID AS [TranTypeID]
            FROM AB_Cash_Book_Transactions t
                INNER JOIN Sys_AB_Transaction_Types tt
                	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                INNER JOIN AW_Company_Banks b
                	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                INNER JOIN Slu_AW_Months m
                	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                INNER JOIN Slu_AW_Years y
                	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                LEFT JOIN AW_Users u
                	ON t.[User_ID] = u.AW_Users_ID
            WHERE
                t.AW_Company_Banks_ID = @Company_Banks_ID AND 
            	t.Slu_AW_Months_ID = @AW_Months_ID AND
            	t.Slu_AW_Years_ID = @AW_Years_ID AND
            	t.AW_User_Companies_ID = @Company_ID
        END
    ELSE
        BEGIN
            SELECT
                t.AB_Cash_Book_Transactions_ID AS [ID], 
        --    	b.Account_Name AS [Bank], 
            	tt.[Description] AS [Transaction Types], 
            	t.Transaction_Date AS [Date], 
            	m.[Description] AS [Month], 
            	y.[Description] AS [Year],
            	t.Reference_No AS [Ref No], 
            	t.Transaction_Description AS [Description], 
            	t.Amount AS [Amount],
                u.UserName AS [User],
                t.Sys_AB_Transaction_Types_ID AS [TranTypeID]
            FROM AB_Cash_Book_Transactions t
                INNER JOIN Sys_AB_Transaction_Types tt
                	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                INNER JOIN AW_Company_Banks b
                	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                INNER JOIN Slu_AW_Months m
                	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                INNER JOIN Slu_AW_Years y
                	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                LEFT JOIN AW_Users u
                	ON t.[User_ID] = u.AW_Users_ID
            WHERE
                t.AW_Company_Banks_ID = @Company_Banks_ID AND 
            	t.Sys_AB_Transaction_Types_ID = @Transaction_Type_ID AND 
            	t.Slu_AW_Months_ID = @AW_Months_ID AND
            	t.Slu_AW_Years_ID = @AW_Years_ID AND
            	t.AW_User_Companies_ID = @Company_ID
        END



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Inflows
--Purpose       :
--Date          :8 FEB 2011
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Select_Cash_Inflows
    (
        @FromDate datetime,
        @ToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT AB_Cash_Inflow_Projections_ID [InflowID],
           Post AS [Post],
           Inflow_Date AS [Date],
           Description AS [Description],
           Sys_AW_Tax_Methods_ID AS [Tax Method],
           Amount AS [Amount],
           Tax_Amount AS [Tax],
           Net_Amount AS [Net]
    FROM AB_Cash_Inflow_Projections
    WHERE AW_User_Companies_ID = @CompanyID AND
          Inflow_Date >= @FromDate AND
          Inflow_Date <= @ToDate
    ORDER BY [Date]











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






























-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Outflows
--Purpose       :
--Date          :8 FEB 2011
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Select_Cash_Outflows
    (
        @FromDate datetime,
        @ToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT AB_Cash_Outflow_Projections_ID [OutflowID],
           Post AS [Post],
           Outflow_Date AS [Date],
           Description AS [Description],
           Sys_AW_Tax_Methods_ID AS [Tax Method],
           Amount AS [Amount],
           Tax_Amount AS [Tax],
           Net_Amount AS [Net]
    FROM AB_Cash_Outflow_Projections
    WHERE AW_User_Companies_ID = @CompanyID AND
          Outflow_Date >= @FromDate AND
          Outflow_Date <= @ToDate
    ORDER BY [Date]











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cashflow_Forecast
--Purpose       :Select Cash Flow Forecast from AB_Cash_Flow_Forecast_Temp
--Date          :2011/02/24
--Authors       :TB
--MODS:
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Select_Cashflow_Forecast
    (
        @FromDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @StartDate datetime,
            @SQL varchar(4000),
            @D1 datetime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @P1 varchar(10),
            @P2 varchar(10),
            @P3 varchar(10),
            @P4 varchar(10),
            @P5 varchar(10),
            @P6 varchar(10),
            @V1 bigint,
            @V2 bigint,
            @V3 bigint,
            @V4 bigint,
            @V5 bigint,
            @V6 bigint,
            @Total bigint,
            @CFFID int,
            @Temp1 bigint


    --> Get the StartDate from the last forecast so that Column headings match it
	SELECT TOP 1 @StartDate = StartDate
    FROM AB_Cash_Flow_Forecast_Temp
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY StartDate DESC

	IF @StartDate IS NULL 
        BEGIN
            SET @StartDate = @FromDate
        END


    --> Set Forecast Month dates - e.g. @D1 = '2011/01/01', @D6 = '2011/06/01'
    SET @D1 = @StartDate
    SET @D2 = DATEADD(mm, 1, @D1)
    SET @D3 = DATEADD(mm, 1, @D2) 
    SET @D4 = DATEADD(mm, 1, @D3)
    SET @D5 = DATEADD(mm, 1, @D4)
    SET @D6 = DATEADD(mm, 1, @D5)

    --> Set Forecast Column names - e.g. @P1 = 'JAN 2011', @P6 = 'JUN 2011'
    SET @P1 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @D1))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @D1))
    SET @P2 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @D2))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @D2))
    SET @P3 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @D3))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @D3))
    SET @P4 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @D4))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @D4))
    SET @P5 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @D5))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @D5))
    SET @P6 = LEFT(UPPER(CONVERT(varchar(10), DATENAME(mm, @D6))), 3) + ' ' + CONVERT(varchar(4), DATEPART(yyyy, @D6))


    -------------------------------------------------------------------------------
    --> Declare a TABLE variable
    -------------------------------------------------------------------------------
    DECLARE @CFF table
        (
	        [ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[N1] [tinyint] DEFAULT 0 NULL ,
        	[M1] [bigint] DEFAULT 0 NULL ,
        	[M2] [bigint] DEFAULT 0 NULL ,
        	[M3] [bigint] DEFAULT 0 NULL ,
        	[M4] [bigint] DEFAULT 0 NULL ,
        	[M5] [bigint] DEFAULT 0 NULL ,
        	[M6] [bigint] DEFAULT 0 NULL ,
        	[T1] [bigint] DEFAULT 0 NULL ,
        	[RowTypeID] [tinyint] DEFAULT 0 NULL ,
        	[StartDate] [datetime] DEFAULT getdate() NULL ,
        	[AW_User_Companies_ID] [int] DEFAULT 1 NULL
        )

    -------------------------------------------------------------------------------
    -- INSERT the DATA into TEMP TABLE
    -------------------------------------------------------------------------------

    INSERT INTO @CFF
    SELECT Description,
           N1,
           M1,
           M2,
           M3,
           M4,
           M5,
           M6,
           T1,
           RowTypeID,
           StartDate,
           AW_User_Companies_ID
    FROM AB_Cash_Flow_Forecast_Temp


    -------------------------------------------------------------------------------
    -- SUM CASH POSITION and SET BEGINNING CASH ON HAND (for the 6 months)
    -------------------------------------------------------------------------------

    ------------------------------------------
    --> Zero ALL CASH POSITION totals
    UPDATE @CFF
    SET M1 = 0,
        M2 = 0,
        M3 = 0,
        M4 = 0,
        M5 = 0,
        M6 = 0,
        T1 = 0
    WHERE N1 = 6
   ------------------------------------------
    --> Zero ALL TOTALS (T1)
    UPDATE @CFF
    SET T1 = 0
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 1
    SELECT @Temp1 = SUM(M1)
    FROM @CFF
    WHERE N1 <> 6 AND
          M1 IS NOT NULL
    ------------------------------------------
    --> SET the CASH POSITION of month 1
    UPDATE @CFF
    SET M1 = @Temp1
    WHERE N1 = 6
    ----------------------
    --> SET the beginning CASH ON HAND of month 2
    UPDATE @CFF
    SET M2 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 2
    SELECT @Temp1 = SUM(M2)
    FROM @CFF
    WHERE N1 <> 6 AND
          M2 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 2
    UPDATE @CFF
    SET M2 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 3
    UPDATE @CFF
    SET M3 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 3
    SELECT @Temp1 = SUM(M3)
    FROM @CFF
    WHERE N1 <> 6 AND
          M3 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 3
    UPDATE @CFF
    SET M3 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 4
    UPDATE @CFF
    SET M4 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 4
    SELECT @Temp1 = SUM(M4)
    FROM @CFF
    WHERE N1 <> 6 AND
          M4 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 4
    UPDATE @CFF
    SET M4 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 5
    UPDATE @CFF
    SET M5 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 5
    SELECT @Temp1 = SUM(M5)
    FROM @CFF
    WHERE N1 <> 6 AND
          M5 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 5
    UPDATE @CFF
    SET M5 = @Temp1
    WHERE N1 = 6
    ------------------------------------------
    --> SET the beginning CASH ON HAND of month 6
    UPDATE @CFF
    SET M6 = @Temp1
    WHERE N1 = 1
    ------------------------------------------


    ------------------------------------------
    --> Get the CASH POSITION of month 6
    SELECT @Temp1 = SUM(M6)
    FROM @CFF
    WHERE N1 <> 6 AND
          M6 IS NOT NULL
    ----------------------
    --> SET the CASH POSITION of month 6
    UPDATE @CFF
    SET M6 = @Temp1
    WHERE N1 = 6
    ------------------------------------------


    -------------------------------------------------------------------------------
    -- CROSS-CAST months to TOTAL column using CURSOR
    -------------------------------------------------------------------------------

    --> Define a CURSOR for Income and Expense accounts
    DECLARE Sum_Cursor CURSOR FOR
        SELECT ID,
               ISNULL(M1, 0),
               ISNULL(M2, 0),
               ISNULL(M3, 0),
               ISNULL(M4, 0),
               ISNULL(M5, 0),
               ISNULL(M6, 0)
        FROM @CFF
        WHERE N1 <> 0 AND N1 <> 1 AND N1 <> 6

	OPEN Sum_Cursor

    	FETCH NEXT FROM Sum_Cursor 
    	INTO
            @CFFID,
            @V1,
            @V2,
            @V3,
            @V4,
            @V5,
            @V6
    	
    	WHILE @@FETCH_STATUS = 0
        	BEGIN
                SET @Total = @V1 + @V2 + @V3 + @V4 + @V5 + @V6

                UPDATE @CFF
                SET T1 = @Total
                WHERE ID = @CFFID

            	FETCH NEXT FROM Sum_Cursor 
            	INTO
                    @CFFID,
                    @V1,
                    @V2,
                    @V3,
                    @V4,
                    @V5,
                    @V6
        	END
	
	CLOSE Sum_Cursor

	DEALLOCATE Sum_Cursor


    -------------------------------------------------------------------------------
    -- DROP the TEMP TABLE
    -------------------------------------------------------------------------------

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Flow_Forecast_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Flow_Forecast_Temp]
 
    CREATE TABLE [dbo].[AB_Cash_Flow_Forecast_Temp] (
    	[AB_Cash_Flow_Forecast_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[N1] [tinyint] NULL ,
    	[M1] [bigint] NULL ,
    	[M2] [bigint] NULL ,
    	[M3] [bigint] NULL ,
    	[M4] [bigint] NULL ,
    	[M5] [bigint] NULL ,
    	[M6] [bigint] NULL ,
    	[T1] [bigint] NULL ,
    	[RowTypeID] [tinyint] NULL ,
        [StartDate] [datetime] NULL ,
        [AW_User_Companies_ID] [int] NULL
    ) ON [PRIMARY]
 
    CREATE CLUSTERED INDEX [CI_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp] ([N1], [RowTypeID], [Description])
    CREATE UNIQUE INDEX [IX_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp] ([AB_Cash_Flow_Forecast_Temp_ID])

    setuser

    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Flow_Forecast_Temp].[Description]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[N1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M2]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M3]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M4]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M5]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M6]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[T1]'
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[RowTypeID]'
    EXEC sp_bindefault N'[dbo].[df_Todays_Date]', N'[AB_Cash_Flow_Forecast_Temp].[StartDate]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Flow_Forecast_Temp].[AW_User_Companies_ID]'

    setuser
 
    -------------------------------------------------------------------------------
    -- INSERT the DATA into TEMP TABLE
    -------------------------------------------------------------------------------

    INSERT INTO AB_Cash_Flow_Forecast_Temp
    SELECT Description,
           N1,
           M1,
           M2,
           M3,
           M4,
           M5,
           M6,
           T1,
           RowTypeID,
           StartDate,
           AW_User_Companies_ID
    FROM @CFF


    -------------------------------------------------------------------------------
    -- FETCH the DATA
    -------------------------------------------------------------------------------

    SET @SQL = ' SELECT '
    SET @SQL = @SQL + ' AB_Cash_Flow_Forecast_Temp_ID AS [ID], '
    SET @SQL = @SQL + ' Description AS [Description], '
    SET @SQL = @SQL + ' N1 AS [Group], '
    SET @SQL = @SQL + ' M1 AS [' + '' + @P1 + '' + '], '
    SET @SQL = @SQL + ' M2 AS [' + '' + @P2 + '' + '], '
    SET @SQL = @SQL + ' M3 AS [' + '' + @P3 + '' + '], '
    SET @SQL = @SQL + ' M4 AS [' + '' + @P4 + '' + '], '
    SET @SQL = @SQL + ' M5 AS [' + '' + @P5 + '' + '], '
    SET @SQL = @SQL + ' M6 AS [' + '' + @P6 + '' + '], '
    SET @SQL = @SQL + ' T1 AS [Total], '
    SET @SQL = @SQL + ' RowTypeID AS [RowTypeID], '
    SET @SQL = @SQL + ' StartDate AS [StartDate], '
    SET @SQL = @SQL + ' AW_User_Companies_ID AS [CompanyID] '
    SET @SQL = @SQL + ' FROM AB_Cash_Flow_Forecast_Temp '
    SET @SQL = @SQL + ' ORDER BY N1, RowTypeID, Description '


    EXEC (@SQL)




SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Condensed_IS
--Purpose       :Manager Console
--Functionality :
--Date          :2004/02/23
--Authors       :TB
--Version       :1.0.0
--MODS:         :15/03/04 - Fixed Invalid use of NULL error with OUTER ISNULL
--              :01/05/05 - Added @ShowGLControllable input parameter to filter
--              :           Controllable GL Accounts ONLY
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Select_Condensed_IS
	(
        @ShowGLControllableOnly tinyint,
        @CompanyID int,
        @Sales Money OUTPUT,
        @CostOfSales Money OUTPUT,
        @GrossProfit Money OUTPUT,
        @OtherIncome Money OUTPUT,
        @OperatingIncome Money OUTPUT,
        @DistribCosts Money OUTPUT,
        @AdminExpenses Money OUTPUT,
        @OtherExpenses Money OUTPUT,
        @TotalExpenses Money OUTPUT,
        @ProfitLoss Money OUTPUT
	)

AS

SET NOCOUNT ON

    IF @ShowGLControllableOnly = 1    -- Contollable Accounts ONLY
        BEGIN
        --> Sales
            SELECT @Sales = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 10 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Cost Of Sales
            SELECT @CostOfSales = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 20 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Gross Profit
            SELECT @GrossProfit = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Other Income
            SELECT @OtherIncome = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 20 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Operating Income
            SELECT @OperatingIncome = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 20 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Distribution Costs
            SELECT @DistribCosts = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 30 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Administration Expenses
            SELECT @AdminExpenses = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 40 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Other Expenses
            SELECT @OtherExpenses = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 50 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> TOTAL Expenses
            SELECT @TotalExpenses = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 30 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> -Profit / Loss
            SELECT @ProfitLoss = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  b.AW_YesNo_Controllable_ID = 1
        END

    ELSE        -- ALL Accounts
        BEGIN
        --> Sales
            SELECT @Sales = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 10 
    
        --> Cost Of Sales
            SELECT @CostOfSales = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 20 
    
        --> Gross Profit
            SELECT @GrossProfit = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10
    
        --> Other Income
            SELECT @OtherIncome = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 20
    
        --> Operating Income
            SELECT @OperatingIncome = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 20
    
        --> Distribution Costs
            SELECT @DistribCosts = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 30
    
        --> Administration Expenses
            SELECT @AdminExpenses = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 40
    
        --> Other Expenses
            SELECT @OtherExpenses = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 50
    
        --> TOTAL Expenses
            SELECT @TotalExpenses = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 30 AND
                  c.Sys_AB_I3_ID <= 50
    
        --> -Profit / Loss
            SELECT @ProfitLoss = ISNULL(ROUND(SUM(a.AB_Transaction_Amount), 2), 0)
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 50
        END


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Condensed_IS_Budget
--Purpose       :Manager Console
--Functionality :
--Date          :2005/05/01
--Authors       :TB
--MODS:         :01/05/05 - Added @ShowGLControllable input parameter to filter
--              :           Controllable GL Accounts ONLY
--2004.3.8      :20/01/08 - Added select budget for FISCAL SPAN based on the
--              :           Accounting Period passed in with @MonthID and @YearID
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Select_Condensed_IS_Budget
	(
        @ShowGLControllableOnly tinyint,
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @Sales Money OUTPUT,
        @CostOfSales Money OUTPUT,
        @GrossProfit Money OUTPUT,
        @OtherIncome Money OUTPUT,
        @OperatingIncome Money OUTPUT,
        @DistribCosts Money OUTPUT,
        @AdminExpenses Money OUTPUT,
        @OtherExpenses Money OUTPUT,
        @TotalExpenses Money OUTPUT,
        @ProfitLoss Money OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @StartPeriod varchar(6),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int


    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    IF @ShowGLControllableOnly = 1    -- Contollable Accounts ONLY
        BEGIN
        --> Sales
            SELECT @Sales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Cost Of Sales
            SELECT @CostOfSales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Gross Profit
            SELECT @GrossProfit = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Other Income
            SELECT @OtherIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Operating Income
            SELECT @OperatingIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Distribution Costs
            SELECT @DistribCosts = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 30 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Administration Expenses
            SELECT @AdminExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 40 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Other Expenses
            SELECT @OtherExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> TOTAL Expenses
            SELECT @TotalExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 30 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> -Profit / Loss
            SELECT @ProfitLoss = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
        END

    ELSE        -- ALL Accounts            
        BEGIN
        --> Sales
            SELECT @Sales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Cost Of Sales
            SELECT @CostOfSales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Gross Profit
            SELECT @GrossProfit = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Other Income
            SELECT @OtherIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Operating Income
            SELECT @OperatingIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Distribution Costs
            SELECT @DistribCosts = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 30 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Administration Expenses
            SELECT @AdminExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 40 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Other Expenses
            SELECT @OtherExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> TOTAL Expenses
            SELECT @TotalExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 30 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> -Profit / Loss
            SELECT @ProfitLoss = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
        END

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Condensed_IS_Budget_Year
--Purpose       :Manager Console
--Functionality :
--Date          :2008/01/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Select_Condensed_IS_Budget_Year
	(
        @ShowGLControllableOnly tinyint,
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @Sales Money OUTPUT,
        @CostOfSales Money OUTPUT,
        @GrossProfit Money OUTPUT,
        @OtherIncome Money OUTPUT,
        @OperatingIncome Money OUTPUT,
        @DistribCosts Money OUTPUT,
        @AdminExpenses Money OUTPUT,
        @OtherExpenses Money OUTPUT,
        @TotalExpenses Money OUTPUT,
        @ProfitLoss Money OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @StartPeriod varchar(6),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @EndMonthID int,
            @EndYearID int


    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @EndMonthID = @YearEndMonthID
    SET @EndYearID = @StartYearID + 1

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@EndMonthID, @EndYearID)


    IF @ShowGLControllableOnly = 1    -- Contollable Accounts ONLY
        BEGIN
        --> Sales
            SELECT @Sales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Cost Of Sales
            SELECT @CostOfSales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Gross Profit
            SELECT @GrossProfit = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Other Income
            SELECT @OtherIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Operating Income
            SELECT @OperatingIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Distribution Costs
            SELECT @DistribCosts = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 30 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Administration Expenses
            SELECT @AdminExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 40 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> Other Expenses
            SELECT @OtherExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> TOTAL Expenses
            SELECT @TotalExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 30 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
    
        --> -Profit / Loss
            SELECT @ProfitLoss = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod AND
                  b.AW_YesNo_Controllable_ID = 1
        END

    ELSE        -- ALL Accounts            
        BEGIN
        --> Sales
            SELECT @Sales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  c.Sys_AB_I4_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Cost Of Sales
            SELECT @CostOfSales = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  c.Sys_AB_I4_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Gross Profit
            SELECT @GrossProfit = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 10 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Other Income
            SELECT @OtherIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Operating Income
            SELECT @OperatingIncome = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 20 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Distribution Costs
            SELECT @DistribCosts = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 30 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Administration Expenses
            SELECT @AdminExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 40 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> Other Expenses
            SELECT @OtherExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID = 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> TOTAL Expenses
            SELECT @TotalExpenses = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 30 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    
        --> -Profit / Loss
            SELECT @ProfitLoss = ISNULL(ROUND(SUM(a.Budget_Amount), 2), 0)
            FROM AB_Budgets a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER JOIN Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
                INNER JOIN Sys_AB_I3 d
                    ON c.Sys_AB_I3_ID = d.Sys_AB_I3_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  c.Sys_AB_I3_ID >= 10 AND
                  c.Sys_AB_I3_ID <= 50 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
        END

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-----------------------------------------------------------------------------------
--Description   :sp_AB_Select_Control_Account
--Purpose       :Returns the Control Account
--Functionality :
--Parameters    :
--Date          :2002/02/07
--Authors       :TB
--MODS          :
--2004.4.4      :10/04/09 - Changed [User_ID] to [User] and [Date Captured] to [Date Changed]
--              :           to display these columns in UI
-----------------------------------------------------------------------------------

CREATE     PROCEDURE sp_AB_Select_Control_Account
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Control_Accounts_ID AS [ID],
            Control_Number AS [Control No],
            [Description] AS [Description],
            User_Description AS [User Description],
            AB_Accounts_ID AS [GL Account],
            Date_Captured AS [Date Changed],
            [User_ID] AS [User],
            AW_User_Companies_ID AS [Company],
            Slu_AW_Active_ID AS [Active]
    FROM AB_Control_Accounts
    WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cost_Centres
--Purpose       :
--              :
--Parameters    :
--Date          :2003/08/03
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Select_Cost_Centres
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT Lup_AB_Cost_Centers_ID AS [ID], 
          [Description] AS [Cost Centre]
    FROM Lup_AB_Cost_Centers
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1
    ORDER BY [Description]

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Duplicated_GLAccount_Numbers
--Purpose       :
--Date          :2007/08/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Select_Duplicated_GLAccount_Numbers
    (
        @CompanyID int
    )
AS

SET NOCOUNT ON

    SELECT MAX(AB_Accounts_ID) as [ID],
           Account_Number as [Number],
           Count(*) as [Count]
    FROM dbo.AB_Accounts
    GROUP BY Account_Number
    HAVING Count(*) > 1


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Enterprise_Balance_Sheet
--Purpose       :SELECT Enterprise Balance Sheet Report data
--Date          :2007/09/09
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Balance_Sheet]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6)


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' b.Sys_AB_B1_ID AS [AB_ID1], '
    SET @sql = @sql + ' b.Sys_AB_B2_ID AS [AB_ID2], '
    SET @sql = @sql + ' b.Sys_AB_B3_ID AS [AB_ID3], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '
    
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [Balance] '

    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B1 c '
    SET @sql = @sql + '         ON b.Sys_AB_B1_ID = c.Sys_AB_B1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B2 d '
    SET @sql = @sql + '         ON b.Sys_AB_B2_ID = d.Sys_AB_B2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B3 e '
    SET @sql = @sql + '         ON b.Sys_AB_B3_ID = e.Sys_AB_B3_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '      

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)   --  + ' AND '


    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_B1_ID, '
    SET @sql = @sql + '          b.Sys_AB_B2_ID, '
    SET @sql = @sql + '          b.Sys_AB_B3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '    --Orders the P/L categories
    SET @sql = @sql + '          a.[Description] '

    EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Enterprise_Income_Statement
--Purpose       :SELECT Enterprise Income Statement Report data
--Date          :2007/09/05
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Income_Statement]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' b.Sys_AB_I1_ID AS [AB_ID1], '
    SET @sql = @sql + ' b.Sys_AB_I2_ID AS [AB_ID2], '
    SET @sql = @sql + ' b.Sys_AB_I3_ID AS [AB_ID3], '
    SET @sql = @sql + ' b.Sys_AB_I4_ID AS [AB_ID4], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '
 
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '   

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '    --Only Income Statement accounts


    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
    SET @sql = @sql + '          a.Description   '

    EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Management_Account_Groups
--Purpose       :SELECT Enterprise Management Accounts Report data. Based on sp_RPT_AB_Management_Account_Groups
--Parameters    :
--Date          :2015/08/20
--Authors       :RL
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Management_Accounts]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @CombineSalesCOS tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6),
            @RevenueCategory varchar(100)

    --NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    ------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    ------------------------------------------------
    -- Get the DESCRIPTION of the Revenue Category
    ------------------------------------------------
    SELECT @RevenueCategory = Description
    FROM Sys_AB_Account_Categories
    WHERE Sys_AB_Account_Categories_ID = 13
    ------------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + ' b.Sys_AB_I1_ID AS [IS1ID], '
    SET @sql = @sql + ' b.Sys_AB_I2_ID AS [IS2ID], '
    SET @sql = @sql + ' b.Sys_AB_I3_ID AS [IS3ID], '
    SET @sql = @sql + ' b.Sys_AB_I4_ID AS [IS4ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Divisions_ID AS [DivisionID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Groups_ID AS [GroupID], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + ' CASE WHEN b.Sys_AB_Account_Categories_ID = 14 '
            SET @sql = @sql + '      THEN ''' + @RevenueCategory + ''' '
            SET @sql = @sql + '      ELSE ISNULL(b.[Description], '''') '
            SET @sql = @sql + ' END AS [Level4], ' 
        END
    ELSE
         BEGIN
            SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [Level4], '
         END

    SET @sql = @sql + ' ISNULL(g.[Description], '''') AS [GLDivision], '
    SET @sql = @sql + ' ISNULL(h.[Description], '''') AS [GLGroup], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [AccountNo], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)

    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Actual], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [YTDActual], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [YTDBudget] '




    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Divisions g '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = g.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups h '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = h.Lup_AB_Account_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '         

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND b.Sys_AB_I4_ID <> 0 '                    --Only Income Statement accounts

    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END

    IF @IgnoreZeroTrans = 1
        BEGIN
--             SET @sql = @sql + ' AND ( '
--             SET @sql = @sql + '     SELECT COUNT(*) '
--             SET @sql = @sql + '     FROM AB_GL_Transactions t '
--             SET @sql = @sql + '     WHERE '
--             SET @sql = @sql + '         ( '
--             SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--             SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--             SET @sql = @sql + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END

    IF @IgnoreZeroBalance = 1
        BEGIN
--             SET @sql = @sql + ' AND ( '
--             SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
--             SET @sql = @sql + '     FROM AB_GL_Transactions t '
--             SET @sql = @sql + '     WHERE '
--             SET @sql = @sql + '         ( '
--             SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--             SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--             SET @sql = @sql + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

            IF @IgnoreYEJnl = 1
                BEGIN
                    SET @sql = @sql + '          AND Sys_AB_Transaction_Types_ID <> 16'
                END
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + '          [Level4], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
        END

    SET @sql = @sql + '          g.[Description], '
    SET @sql = @sql + '          h.[Description], '

    IF @CombineSalesCOS = 1
        BEGIN
            --------------------------------------------------------------
            --> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            --------------------------------------------------------------

            SET @sql = @sql + '          a.Account_Number, '
        END

    SET @sql = @sql + '          a.Description   '


EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Enterprise_Trial_Balance
--Purpose       :Enterprise Trial Balance Report data
--Functionality :Fetches GL ACCOUNT BALANCE
--Date          :2007/08/28
--Authors       :TB
--MODS:         :
--2004.4.8      :05/11/09 - Added @GroupBy and @Grouping sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Trial_Balance]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int        
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @EndPeriod varchar(6)

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [GLDivision], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [GLGroup], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Balance] '

    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories c '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Divisions d '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = d.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups e '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = e.Lup_AB_Account_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '   

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)

    SET @sql = @sql + ' ORDER BY ISNULL(a.Account_Number, '''') ASC '

    EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AB_Select_FirstLast_Transaction_Date
--Purpose       :Select FIRST or LAST GL Transaction Date
--Date          :2007/02/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Select_FirstLast_Transaction_Date
	(
    	@CompanyID int,
        @Option tinyint,
        @TranDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @Year varchar(4),
            @Month varchar(2),
            @Day varchar(2),
            @Hour varchar(2),
            @Minute varchar(2),
            @Second varchar(2),
            @Date varchar(10),
            @Time varchar(8),
            @DateCaptured datetime,
            @FullDateTime varchar(30)


--> Get the FIRST GL Transaction Date
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 @TranDate = AB_Transaction_Date,
                         @DateCaptured = Date_Captured
            FROM AB_GL_Transactions
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AB_Transaction_Date ASC
        END

    ELSE

--> Get the LAST GL Transaction Date
    IF @Option = 1
        BEGIN
            SELECT TOP 1 @TranDate = AB_Transaction_Date,
                         @DateCaptured = Date_Captured
            FROM AB_GL_Transactions
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AB_Transaction_Date DESC
        END


    IF @TranDate IS NOT NULL
        BEGIN
            SELECT @Year = CONVERT(varchar(4), DATEPART(yy, @TranDate)),
                   @Month = CONVERT(varchar(2), DATEPART(mm, @TranDate)),
                   @Day = CONVERT(varchar(2), DATEPART(dd, @TranDate)),
                   @Hour = CONVERT(varchar(2), DATEPART(hh, @TranDate)),
                   @Minute = CONVERT(varchar(2), DATEPART(mi, @TranDate)),
                   @Second = CONVERT(varchar(2), DATEPART(ss, @TranDate))
        
        
            ------------------------------------------------------------
            --> Format the DATE
            ------------------------------------------------------------
            IF LEN(RTRIM(LTRIM(@Month))) = 1
                SET @Month = '0' + @Month
        
            IF LEN(RTRIM(LTRIM(@Day))) = 1
                set @Day = '0' + @Day
        
            SET @Date = @Year + '/' + @Month + '/' + @Day
        
        
            ------------------------------------------------------------
            --> Format the TIME
            ------------------------------------------------------------
            IF RTRIM(LTRIM(@Hour)) = ''
                BEGIN

                    SELECT @Hour = CONVERT(varchar(2), DATEPART(hh, @DateCaptured)),
                           @Minute = CONVERT(varchar(2), DATEPART(mi, @DateCaptured)),
                           @Second = CONVERT(varchar(2), DATEPART(ss, @DateCaptured))

                    IF LEN(RTRIM(LTRIM(@Hour))) = 1
                        SET @Hour = '0' + @Hour

                    IF LEN(RTRIM(LTRIM(@Minute))) = 1
                        set @Minute = '0' + @Minute

                    IF LEN(RTRIM(LTRIM(@Second))) = 1
                        set @Second = '0' + @Second
                END
            ELSE
                BEGIN
                    IF LEN(RTRIM(LTRIM(@Hour))) = 1
                        SET @Hour = '0' + @Hour

                    IF LEN(RTRIM(LTRIM(@Minute))) = 1
                        set @Minute = '0' + @Minute

                    IF LEN(RTRIM(LTRIM(@Second))) = 1
                        set @Second = '0' + @Second
                END



            SET @Time = @Hour + ':' + @Minute + ':' + @Second
        END


    SET @FullDateTime = @Date + ' ' + @Time
    SET @TranDate = CONVERT(datetime, @FullDateTime)




SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












--------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Accounts_As_Lup
--Purpose       :Returns all GL Accounts as a Lookup
--Functionality :
--Parameters    :
--Date          :2002/11/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AB_Select_GL_Accounts_As_Lup
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AB_Accounts_ID AS [ID],
    	[Description] AS [GL Account]
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID AND 
    	Slu_AW_Active_ID = 1
    ORDER BY [Description]


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Accounts_Lups
--Purpose       :Returns the General Ledger UI Lups
--Date          :2002/02/17
--Authors       :TB
--MODS          :19/07/02 - Added Months with SHORT Description
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :01/05/05 - Added @Choice = 9 Yes/No
--              :19/02/06 - Added @Choice = 10 Transaction Code
--2004.3.7      :23/09/07 - Added @Choice = 11 GL Account Group
--              :28/09/07 - Added @Choice = 12 GL Account Division
--              :01/10/07 - Removed ORDER BY in GL Division and Group to seperate
--              :           SALES from EXPENSE accounts in list
--2004.4.4      :10/04/09 - Added @Choice = 13 User Name
--RL	V6.2	2016-06-24	:Added @Choice = 14 Lup_AB_Account_Departments_ID
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_GL_Accounts_Lups]
    (
    	@Choice tinyint
    )

AS

SET NOCOUNT ON

	--> Account Categories
	IF @Choice = 1
		SELECT Sys_AB_Account_Categories_ID AS [ID],
			  [Description] AS [Account Categories]
		FROM Sys_AB_Account_Categories		
		ORDER BY [Description]	

	--> Tax Codes
	ELSE 
	IF @Choice = 2
		SELECT Sys_AW_Tax_Codes_ID AS [ID],
			[Description] AS [Tax Code]
		FROM Sys_AW_Tax_Codes

	--> Cost Centers
	ELSE 
	IF @Choice = 3
		SELECT Lup_AB_Cost_Centers_ID AS [ID],
			[Description] AS [Cost Centers]
		FROM Lup_AB_Cost_Centers
		ORDER BY [Description]	

	--> Active
	ELSE 
	IF @Choice = 4
		SELECT Slu_AW_Active_ID AS [ID],
			[Description] AS [Active]
		FROM Slu_AW_Active

	--> Transaction Types
	ELSE 
	IF @Choice = 5
		SELECT Sys_AB_Transaction_Types_ID AS [ID],
			[Description] AS [Transaction_Types]
		FROM Sys_AB_Transaction_Types

    --> Years
    ELSE
    IF @Choice = 6
    	SELECT Slu_AW_Years_ID AS [ID], 
        	[Description] AS [Year] 
    	FROM Slu_AW_Years

    --> Months (Long Description)
    ELSE 
    IF @Choice = 7
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Long_Description] AS [Month] 
    	FROM Slu_AW_Months

    --> Months (Short Description)
    ELSE 
    IF @Choice = 8
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Description] AS [Month] 
    	FROM Slu_AW_Months

    --> Yes/No
    ELSE
    IF @Choice = 9
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [YesNo] 
    	FROM Slu_AW_YesNo

	--> Transaction Code
	ELSE 
	IF @Choice = 10
		SELECT Sys_AB_Transaction_Types_ID AS [ID],
			Transaction_Code AS [TranCode]
		FROM Sys_AB_Transaction_Types

	--> GL Account Group
	ELSE 
	IF @Choice = 11
		SELECT Lup_AB_Account_Groups_ID AS [ID],
			[Description] AS [GL Group]
		FROM Lup_AB_Account_Groups
--		ORDER BY [Description]

	--> GL Account Division
	ELSE 
	IF @Choice = 12
		SELECT Lup_AB_Account_Divisions_ID AS [ID],
			[Description] AS [GL Division]
		FROM Lup_AB_Account_Divisions
--		ORDER BY [Description]

	--> User
	ELSE 
	IF @Choice = 13
        SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + Firstname, '') AS [User]
        FROM AW_Users
        ORDER BY [User]
        
	--> GL Account Department
	ELSE 
	IF @Choice = 14
		SELECT Lup_AB_Account_Departments_ID AS [ID],
			[Description] AS [GL Department]
		FROM Lup_AB_Account_Departments
		ORDER BY [Description]

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-- SET @GLAccountID = 16        --155
-- SET @ChkTranType = 0
-- SET @TransactionTypeID = 5    --Accounts Payable - Invoice
-- SET @ChkDate = 0
-- SET @FromDate = '2003/01/01 01:36:33 PM'
-- SET @ToDate = '2003/04/30 01:36:33 PM'
-- SET @ChkPeriod = 0
-- SET @MonthID = 3
-- SET @YearID = 4
-- SET @chkSearch = 1
-- SET @Search = 'refund'
-- SET @CompanyID = 1


-------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Editor
--Purpose       :Fetch GL Transaction History
--Functionality :uses BETWEEN
--Date          :2006/02/19
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Select_GL_Editor
    (
        @GLAccountID int,
        @ChkTranType tinyint,
        @TransactionTypeID int = 0,
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkPeriod tinyint,
        @MonthID int = 0,
        @YearID int = 0,
        @chkSearch tinyint,
        @Search varchar(50),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(1000)


    IF @chkSearch = 1
        BEGIN
        	SET @Filter = '%' + RTRIM(LTRIM(@Search)) + '%'
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' Sys_AB_Transaction_Types_ID AS [GLTranTypeID], '
    SET @sql = @sql + ' Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' AB_Transaction_Date AS [Date], '
    SET @sql = @sql + ' [Description] AS [Narration], '
    SET @sql = @sql + ' AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + ' Slu_AW_Months_ID AS [Month], '
    SET @sql = @sql + ' Slu_AW_Years_ID AS [Year], '
    SET @sql = @sql + ' AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' [User_ID] AS [User] '

    SET @sql = @sql + ' FROM AB_GL_Transactions '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

    IF @chkSearch <> 1
        BEGIN
            SET @sql = @sql + ' AND AB_Accounts_ID = '  + CONVERT(varchar(10), @GLAccountID) + ' '
        END

    IF @ChkTranType = 1
        BEGIN
            SET @sql = @sql + ' AND Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TransactionTypeID) + ' ' 
        END
    
    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + '  AND (AB_Transaction_Date BETWEEN ' +
                                        '''' + LEFT(CONVERT(CHAR(19), @FromDate, 121), 19) + '''' + ' '
            SET @sql = @sql + '                                AND  ' +
                                        '''' + LEFT(CONVERT(CHAR(19), @ToDate, 121), 19) + '''' + ') '
        END
    
    IF @ChkPeriod = 1
        BEGIN
            SET @sql = @sql + ' AND Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' '
            SET @sql = @sql + ' AND Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '
        END
    
    IF @chkSearch = 1
        BEGIN
            SET @sql = @sql + ' AND (AB_Source_Ref LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), AB_Transaction_Ref) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR [Description] LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), AB_Transaction_Amount) LIKE ' + '''' + @Filter+ ''''  + ') '
        END
    

    SET @sql = @sql + ' ORDER BY AB_GL_Transactions_ID DESC '



--PRINT @sql

    EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Fiscal_Month_Totals
--Purpose       :Returns the GL monthly transaction totals
--Functionality :Gets parameter MONTH/YEAR Actuals and Budgets for a GL Account
--Date          :2002/02/17
--Authors       :TB
--MODS          :13/12/02 - Added New AB_Budgets table data
--2004.5.5      :10/11/11 - Added ORDER BY in [CurrentBudget] and [NextBudget] subQueries to
--              :           handle MULTIPLE BUDGETS for the SAME Account/Month/Year !!! TCRUST !!!
--------------------------------------------------------------------------------

CREATE      PROCEDURE sp_AB_Select_GL_Fiscal_Month_Totals
    (
        @CompanyID int,
        @GLAccount int,
        @MonthID int,
        @ThisYearID int
    )

AS

SET NOCOUNT ON

	DECLARE @NextYearID int,
            @PrevYearID int

    SET @PrevYearID = @ThisYearID - 1
    SET @NextYearID = @ThisYearID + 1

    SELECT
        ISNULL(
                (
                    SELECT ISNULL(SUM(AB_Transaction_Amount), 0)
                    FROM AB_GL_Transactions
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          AB_Accounts_ID = @GLAccount AND
                          Slu_AW_Months_ID = @MonthID AND
                          Slu_AW_Years_ID = @ThisYearID
                    GROUP BY Slu_AW_Months_ID, Slu_AW_Years_ID
                ), 0) AS [SumCurrent],
        ISNULL(
                (
                    SELECT SUM(AB_Transaction_Amount)
                    FROM AB_GL_Transactions
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          AB_Accounts_ID = @GLAccount AND
                          Slu_AW_Months_ID = @MonthID AND
                          Slu_AW_Years_ID = @PrevYearID
                    GROUP BY Slu_AW_Months_ID, Slu_AW_Years_ID
                ), 0) AS [SumPrior],
--         ISNULL(
--                 (
--                     SELECT ISNULL(Budget_Amount, 0)
--                     FROM AB_Budgets
--                     WHERE AW_User_Companies_ID = @CompanyID AND
--                         AB_Accounts_ID = @GLAccount AND
--                         Slu_AW_Months_ID = @MonthID AND
--                         Slu_AW_Years_ID = @ThisYearID
--                 ), 0) AS [CurrentBudget],
-- 
--         ISNULL(
--                 (
--                     SELECT ISNULL(Budget_Amount, 0)
--                     FROM AB_Budgets
--                     WHERE AW_User_Companies_ID = @CompanyID AND
--                           AB_Accounts_ID = @GLAccount AND
--                           Slu_AW_Months_ID = @MonthID AND
--                           Slu_AW_Years_ID = @NextYearID
--                 ), 0) AS [NextBudget]
        ISNULL(
                (
                    SELECT TOP 1 ISNULL(Budget_Amount, 0)
                    FROM AB_Budgets
                    WHERE AW_User_Companies_ID = @CompanyID AND
                        AB_Accounts_ID = @GLAccount AND
                        Slu_AW_Months_ID = @MonthID AND
                        Slu_AW_Years_ID = @ThisYearID
                    ORDER BY Date_Captured DESC
                ), 0) AS [CurrentBudget],
        ISNULL(
                (
                    SELECT TOP 1 ISNULL(Budget_Amount, 0)
                    FROM AB_Budgets
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          AB_Accounts_ID = @GLAccount AND
                          Slu_AW_Months_ID = @MonthID AND
                          Slu_AW_Years_ID = @NextYearID
                    ORDER BY Date_Captured DESC
                ), 0) AS [NextBudget]


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Transactions
--Purpose       :Fetch GL Transaction History
--Functionality :uses BETWEEN
--Date          :2002/03/22
--Authors       :TB
--Version       :1.0.0
--Mods          :17/12/02 - Added Month and Year descriptions and sort by their IDs
--              :29/08/03 - Reworked as dynamic SQL for new input parameters
--              :16/11/04 - Changed @Amount search to be system-wide (if @ChkAmount = 1)
--              :12/12/04 - Added [Source Ref] and changed [Ref] to [Ref ID]
--              :12/12/04 - Changed PRIMARY SORT ORDER as a.AB_GL_Transactions_ID DESC
--              :14/01/05 - Converted Amount search to a general STRING search
--              :30/03/06 - Added [TranTypeID] for GL Transaction Popup
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AB_Select_GL_Transactions
    (
        @GLAccountID int,
        @ChkTranType tinyint,
        @TransactionTypeID int = 0,
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkPeriod tinyint,
        @MonthID int = 0,
        @YearID int = 0,
        @chkSearch tinyint,
        @Search varchar(50),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)

-- SET @GLAccountID = 16        --155
-- SET @ChkTranType = 0
-- SET @TransactionTypeID = 5    --Accounts Payable - Invoice
-- SET @ChkDate = 0
-- SET @FromDate = '2003/01/01 01:36:33 PM'
-- SET @ToDate = '2003/04/30 01:36:33 PM'
-- SET @ChkPeriod = 0
-- SET @MonthID = 3
-- SET @YearID = 4
-- SET @chkSearch = 1
-- SET @Search = 'refund'
-- SET @CompanyID = 1


    IF @chkSearch = 1
        BEGIN
        	SET @Filter = '%' + RTRIM(LTRIM(@Search)) + '%'
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [FK ID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [GLTranTypeID], '

    SET @sql = @sql + ' b.[Description] AS [Transaction Type], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '
    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + ' a.AB_Transaction_Date AS [Date], '
    SET @sql = @sql + ' c.[Description] AS [Month], '
    SET @sql = @sql + ' d.[Description] AS [Year], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' e.UserName AS [User] '


    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     INNER JOIN Sys_AB_Transaction_Types b '
    SET @sql = @sql + '         ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON a.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

    IF @chkSearch <> 1
        BEGIN
            SET @sql = @sql + ' AND a.AB_Accounts_ID = '  + CONVERT(varchar(10), @GLAccountID) + ' '
        END

    IF @ChkTranType = 1
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TransactionTypeID) + ' ' 
        END
    
    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + '  AND (a.AB_Transaction_Date BETWEEN ' +
                                        '''' + LEFT(CONVERT(CHAR(19), @FromDate, 121), 19) + '''' + ' '
            SET @sql = @sql + '                                AND  ' +
                                        '''' + LEFT(CONVERT(CHAR(19), @ToDate, 121), 19) + '''' + ') '
        END
    
    IF @ChkPeriod = 1
        BEGIN
            SET @sql = @sql + ' AND a.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' '
            SET @sql = @sql + ' AND a.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '
        END
    
    IF @chkSearch = 1
        BEGIN
            SET @sql = @sql + ' AND (a.AB_Source_Ref LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), a.AB_Transaction_Ref) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  a.[Description] LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(50), a.AB_Transaction_Amount) LIKE ' + '''' + @Filter+ ''''  + ') '
        END
    

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID DESC '



--PRINT @sql

    EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Transactions_BFWD
--Purpose       :Fetch GL Account Transactions from a SELECTED ACCOUNTING PERIOD
--Functionality :uses BETWEEN
--Date          :2005/01/16
--MODS          :30/03/06 - Added field [GLTranTypeID] for GL Transaction Popup
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Select_GL_Transactions_BFWD
    (
        @GLAccountID int,
        @MonthID tinyint,
        @YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartPeriod varchar(6)


-- SET @GLAccountID = 16
-- SET @MonthID = 1
-- SET @YearID = 6
-- SET @CompanyID = 1


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [AccountID], '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [FK ID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [GLTranTypeID], '

    SET @sql = @sql + ' ISNULL(f.[Description], '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), f.AB_Accounts_ID) + '')''  AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(f.Account_Number, '''')  AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(g.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(h.[Description], '''') AS [GLType], '

    SET @sql = @sql + ' f.AB_Account_Balance AS [GLBalance], '
    SET @sql = @sql + ' CONVERT(varchar(20), d.[Description]) + '', ''' +
                      '     + CONVERT(varchar(20), c.[Long_Description]) AS [Period], '

    SET @sql = @sql + ' b.[Description] AS [Transaction Type], '
    SET @sql = @sql + ' b.Transaction_Code AS [Type], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '
    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount], '

--    SET @sql = @sql + ' a.AB_Transaction_Date AS [Date], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '

    SET @sql = @sql + ' c.[Description] AS [Month], '
    SET @sql = @sql + ' d.[Description] AS [Year], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' e.UserName AS [User] '

    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     INNER JOIN Sys_AB_Transaction_Types b '
    SET @sql = @sql + '         ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON a.[User_ID] = e.AW_Users_ID '

    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Types h '
    SET @sql = @sql + '         ON h.Sys_AB_Account_Types_ID = g.Sys_AB_Account_Types_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       a.AB_Accounts_ID = '  + CONVERT(varchar(10), @GLAccountID) + ' AND '
    SET @sql = @sql + '       dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + '''' + ' '
    

--    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '

    SET @sql = @sql + ' ORDER BY ISNULL(f.[Description], ''''), '
    SET @sql = @sql + '          a.Slu_AW_Years_ID, '
    SET @sql = @sql + '          a.Slu_AW_Months_ID, '
    SET @sql = @sql + '          a.AB_Transaction_Date ASC '



--PRINT @sql

    EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Transactions_Current
--Purpose       :Fetch Current Month GL Account Transactions for an ACCOUNTING PERIOD
--Functionality :
--Date          :2009/03/08
--MODS          :08/03/09 - Added field [GLTranTypeID] for GL Transaction Popup
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AB_Select_GL_Transactions_Current
    (
        @GLAccountID int,
        @MonthID tinyint,
        @YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT b.Transaction_Code AS [Type],
           a.[Description] AS [Narration],
           a.AB_Transaction_Amount AS [Amount],
           LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date],
           a.AB_Source_Ref AS [Source Ref],
           a.AB_Transaction_Ref AS [Ref No],
           u.UserName AS [User],
           a.AW_User_Companies_ID AS [CompanyID],
           a.AB_Accounts_ID AS [AccountID],
           a.AB_GL_Transactions_ID AS [ID],
           a.AB_Accounts_ID AS [FK ID],
           a.Sys_AB_Transaction_Types_ID AS [GLTranTypeID]
    FROM AB_GL_Transactions a
        INNER JOIN Sys_AB_Transaction_Types b
            ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID
        LEFT JOIN AW_Users u
            ON a.[User_ID] = u.AW_Users_ID
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.AB_Accounts_ID = @GLAccountID AND
          a.Slu_AW_Months_ID = @MonthID AND
          a.Slu_AW_Years_ID = @YearID
    ORDER BY a.AB_Transaction_Date DESC









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   : sp_AB_Select_Journal_Details
--Purpose       : Retrieves a General Journals Details
--Functionality :
--Parameters    :
--Date          : 2002/12/27
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Select_Journal_Details
    (
    	@AB_Journals_ID int 
    )

AS


SET NOCOUNT ON

	SELECT
        AB_Journal_Details_ID AS [ID], 
        AB_Journals_ID AS [FK ID], 
        AB_Accounts_ID AS [GL Account], 
        Amount AS [Amount], 
        Notes AS [Notes], 
        Slu_AW_Active_ID AS [Active], 
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company] 
	FROM AB_Journal_Details
	WHERE AB_Journals_ID = @AB_Journals_ID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--------------------------------------------------------------------------------
--Description   :sp_AB_Select_Journal_Details_History
--Purpose       :Select GL Journal Detail for Journal History into SHAPE
--Functionality :
--Parameters    :
--Date          :2002/02/16
--Authors       :TB
--Version       :1.0.1
--------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AB_Select_Journal_Details_History
    (
    	@AB_Journals_ID int 
    )

AS

SET NOCOUNT ON

	SELECT
        a.AB_Journal_Details_ID AS [ID], 
        a.AB_Journals_ID AS [FK ID], 
        b.Description AS [GL_Account], 
        a.Amount AS [Amount], 
        a.Notes AS [Notes]
	FROM AB_Journal_Details a
        LEFT JOIN AB_Accounts b
            ON a.AB_Accounts_ID = b.AB_Accounts_ID
	WHERE AB_Journals_ID = @AB_Journals_ID


SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Journal_Lups
--Purpose       :Returns the Lups for GL Journals
--Functionality : 
--Parameters    : 
--Date          :2001/11/17
--Authors       :TB
--Version       :1.0
--Mods          :24/06/02 - Changed sort order of GL Account Lookup to Alphabetic
--              :26/05/04 - Added to select ONLY ACTIVE GL Accounts
--2004.2.7      :25/03/06 - Added GL Account with Account Number in option 5
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Select_Journal_Lups
    (
        @Choice tinyint,
    	@Company_ID int = 0
    )

AS
SET NOCOUNT ON

    --> Years
    IF @Choice = 1 
    
    	SELECT Slu_AW_Years_ID AS [ID], 
            	[Description] AS [Year] 
    	FROM Slu_AW_Years
    
    --> Months
    ELSE 
    IF @Choice = 2
    
    	SELECT Slu_AW_Months_ID AS [ID], 
            	[Description] AS [Month] 
    	FROM Slu_AW_Months
    
    --> GL Accounts
    ELSE 
    IF @Choice = 3
    
    	SELECT AB_Accounts_ID AS [ID], 
            	[Description] AS [GL_Account] 
    	FROM AB_Accounts 
    	WHERE AW_User_Companies_ID = @Company_ID AND
              Slu_AW_Active_ID = 1
        ORDER BY [Description]
    
    --> Active
    ELSE 
    IF @Choice = 4
    
    	SELECT Slu_AW_Active_ID AS [ID], 
            	[Description] AS [Active] 
    	FROM Slu_AW_Active


    --> GL Account with Account Number
    ELSE
    IF @Choice = 5
    	SELECT AB_accounts_ID AS [ID], 
               ISNULL(LEFT(LTRIM(RTRIM(Account_Number)), 6) + ' ', '') + [Description] AS [GL_Account] 
    	FROM AB_Accounts
    	WHERE AW_User_Companies_ID = @Company_ID AND
              Slu_AW_Active_ID = 1
    	ORDER BY [Description]


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--------------------------------------------------------------------------------
--Description   :sp_AB_Select_Journals
--Purpose       :Select GL Journal History
--Functionality :
--Parameters    :
--Date          :2002/02/16
--Authors       :TB
--MODS          :
--2004.4.3      :13/03/09 - Modified [User] field to include Surname and Firstname
--------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AB_Select_Journals
    (
    	@FromDate datetime = 0,
    	@ToDate Datetime = 0,
    	@MonthsID int = 0,
    	@YearsID int = 0,
    	@RefNo varchar(30)= 0,
    	@Amount money = 0,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    IF @Amount = 0 
    
        BEGIN
        --> 1
        	IF 
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo = 0

        		SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @Company_ID

        -- 2 ----------------------------------------------------------------------------------------------
        	ELSE 
        	IF 
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Journal_Date >= @FromDate AND
        			  a.Journal_Date <= @ToDate AND
        			  a.AW_User_Companies_ID = @Company_ID
        -- 3 ----------------------------------------------------------------------------------------------	
        	ELSE 
        	IF 
        	
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Slu_AW_Months_ID = @MonthsID AND
        			  a.Slu_AW_Years_ID = @YearsID AND
        			  a.AW_User_Companies_ID = @Company_ID
        -- 4 ----------------------------------------------------------------------------------------------	
        	ELSE 
        	IF 
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Journal_Reference = @RefNo AND
        			  a.AW_User_Companies_ID = @Company_ID
        -- 5 ----------------------------------------------------------------------------------------------
        	ELSE 
        	IF 
        	
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Journal_Date >= @FromDate AND
        			  a.Journal_Date <= @ToDate AND
        			  a.Slu_AW_Months_ID = @MonthsID AND
        			  a.Slu_AW_Years_ID = @YearsID AND
        			  a.AW_User_Companies_ID = @Company_ID
        -- 6 ----------------------------------------------------------------------------------------------
        	ELSE 
        	IF 
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Journal_Date >= @FromDate AND
        			  a.Journal_Date <= @ToDate AND
        			  a.Journal_Reference = @RefNo AND
        			  a.AW_User_Companies_ID = @Company_ID
        -- 7 ----------------------------------------------------------------------------------------------
        
        	ELSE 
        	IF		
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Slu_AW_Months_ID = @MonthsID AND
        			  a.Slu_AW_Years_ID = @YearsID AND
        			  a.Journal_Reference = @RefNo AND
        			  a.AW_User_Companies_ID = @Company_ID
        -- 8 ----------------------------------------------------------------------------------------------
        
        	ELSE 
        	IF 
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        		WHERE a.Journal_Date >= @FromDate AND
        			  a.Journal_Date <= @ToDate AND
        			  a.Slu_AW_Months_ID = @MonthsID AND
        			  a.Slu_AW_Years_ID = @YearsID AND
        			  a.Journal_Reference = @RefNo AND
        			  a.AW_User_Companies_ID = @Company_ID
        END
    
    ---------------------------------------------------------------------------------------------------
    ---------------------------------------------------------------------------------------------------

    ELSE 
    IF @Amount<> 0
        BEGIN
        
        -- 1 ----------------------------------------------------------------------------------------------
        	IF 
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
        	    WHERE a.AB_Journals_ID in
                        (SELECT DISTINCT e.AB_Journals_ID 
        				FROM AB_Journal_Details e
        				WHERE e.Amount = @Amount) AND 
		              a.Journal_Date >= @FromDate AND
		              a.Journal_Date <= @ToDate AND
		              a.Slu_AW_Months_ID = @MonthsID AND
		              a.Slu_AW_Years_ID = @YearsID AND
		              a.Journal_Reference = @RefNo AND
		              a.AW_User_Companies_ID = @Company_ID
        -- 2 ----------------------------------------------------------------------------------------------		
        	IF 
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND 
               		  a.Slu_AW_Months_ID = @MonthsID AND
            		  a.Slu_AW_Years_ID = @YearsID AND
            		  a.Journal_Reference = @RefNo AND
            		  a.AW_User_Companies_ID = @Company_ID
        -- 3 ----------------------------------------------------------------------------------------------
        	IF 
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND
            		  a.AW_User_Companies_ID = @Company_ID
        -- 4 -----------------------------------------------------------------------------------------------
        	IF 	
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND 
            		  a.Journal_Date >= @FromDate AND
            		  a.Journal_Date <= @ToDate AND
            		  a.AW_User_Companies_ID = @Company_ID
        -- 5 -----------------------------------------------------------------------------------------------
        	IF 
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND 
            		  a.Journal_Date >= @FromDate AND
            		  a.Journal_Date <= @ToDate AND
            		  a.Journal_Reference = @RefNo AND
            		  a.AW_User_Companies_ID = @Company_ID
        -- 6 -----------------------------------------------------------------------------------------------
        	IF 
        		@FromDate <> 0 AND @ToDate <> 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND 
            		  a.Journal_Date >= @FromDate AND
            		  a.Journal_Date <= @ToDate AND
            		  a.Slu_AW_Months_ID = @MonthsID AND
            		  a.Slu_AW_Years_ID = @YearsID AND
            		  a.AW_User_Companies_ID = @Company_ID
        -- 7 -----------------------------------------------------------------------------------------------
        
        	IF 
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID <> 0 AND @YearsID <> 0 AND 
        		@RefNo = 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND 
            		  a.Slu_AW_Months_ID = @MonthsID AND
            		  a.Slu_AW_Years_ID = @YearsID AND
            		  a.AW_User_Companies_ID = @Company_ID
        -- 8 -----------------------------------------------------------------------------------------------
        	IF 
        		@FromDate = 0 AND @ToDate = 0 AND
        		@MonthsID = 0 AND @YearsID = 0 AND 
        		@RefNo <> 0
                SELECT
                    a.AB_Journals_ID AS [ID], 
                    a.Journal_Narration AS [Narration], 
                    a.Journal_Date AS [Date], 
                    a.Journal_Reference AS [Ref No], 
                    b.[Description] AS [Month], 
                    c.[Description] AS [Year], 
                    d.Surname + ISNULL(', ' + d.FirstName, '') AS [User]
        		FROM AB_Journals a
                    LEFT JOIN Slu_AW_Months b
                        ON a.Slu_AW_Months_ID = b.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years c
                        ON a.Slu_AW_Years_ID = c.Slu_AW_Years_ID
                    LEFT JOIN AW_Users d
                        ON a.[User_ID] = d.AW_Users_ID
            	WHERE a.AB_Journals_ID in
                            (SELECT DISTINCT e.AB_Journals_ID 
            				FROM AB_Journal_Details e
            				WHERE e.Amount = @Amount) AND 
            		  a.Journal_Reference = @RefNo AND
            		  a.AW_User_Companies_ID = @Company_ID
        END

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Next_AB_Transaction_Number
--Purpose       :RETURNS next available AB Transaction Number without INCREMENTING COUNTER
--Functionality :Tables: Sys_AB_Transaction_Numbers
--Parameters    :
--Date          :2002/01/30
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Select_Next_AB_Transaction_Number

   (
        @TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @Num int
	
	BEGIN 

		SELECT @Num = ISNULL(Last_Number, 0)
		FROM Sys_AB_Transaction_Numbers
		WHERE AW_User_Companies_ID = @CompanyID 
			AND Sys_AB_Transaction_Types_ID = @TransactionType
		
	    SET @TransactionNumber = CONVERT(varchar(15), @Num + 1)

	END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Top_GLAccount_ID
--Purpose       :Select FIRST or LAST GL Accounts ID
--Functionality :
--Date          :2002/12/31
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Select_Top_GLAccount_ID
	(
    	@CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AB_Accounts_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AB_Accounts_ID
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AB_Accounts_ID
        END

    ELSE

--> Get the LAST AB_Accounts_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AB_Accounts_ID
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AB_Accounts_ID DESC
        END

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















----------------------------------------------------------------------------
--Description   :sp_AB_Set_Cash_Book_IBS_Batch
--Purpose       :De-activate a posted Bank Statement batch
--Date          :2010/03/03
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AB_Set_Cash_Book_IBS_Batch
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int


    SET @RetCode = 0


    BEGIN
        UPDATE AB_Cash_Book_IBS_Header
        SET Slu_AW_Active_ID = 5
        WHERE AB_Cash_Book_IBS_Header_ID = @HeaderID AND
              AW_User_Companies_ID = @CompanyID

        SET @RetCode = 1
    END


    BEGIN
        UPDATE AB_Cash_Book_IBS_Detail
        SET Slu_AW_Active_ID = 5
        WHERE AB_Cash_Book_IBS_Header_ID = @HeaderID AND
              AW_User_Companies_ID = @CompanyID
        SET @RetCode = 2
    END



RETURN @RetCode









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AB_Shape_Cash_Book_IBS_Detail
--Purpose       :Selects Cask Book IBS Post History Detail Shaped
--Date          :27 FEB 2010
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE                        PROCEDURE sp_AB_Shape_Cash_Book_IBS_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT d.AB_Cash_Book_IBS_Detail_ID AS [ID],
           d.AB_Cash_Book_IBS_Header_ID AS [HeaderID],
           d.Post AS [Post],
           d.Transaction_Date AS [Date],
           tt.Transaction_Code AS [Transaction Type],
           d.Ref_No AS [Ref No],
           d.Post_Description AS [Description],
           gl.[Description] AS [GL Account],
           d.AB_Accounts_ID AS [GLAccountID],
           tm.[Description] AS [Tax Method],
           d.Amount AS [Amount],
           d.Tax_Amount AS [Tax],
           d.Net_Amount AS [Net],
           d.Comments AS [Comments]
    FROM AB_Cash_Book_IBS_Detail d
        LEFT JOIN AB_Accounts gl
            ON d.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN Sys_AB_Transaction_Types tt
            ON d.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
        INNER JOIN Sys_AW_Tax_Methods tm
            ON d.Sys_AW_Tax_Methods_ID = tm.Sys_AW_Tax_Methods_ID
    WHERE d.AB_Cash_Book_IBS_Header_ID = @HeaderID AND
          d.AW_User_Companies_ID = @CompanyID
    ORDER BY [ID]























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























-------------------------------------------------------------------------------
--Description   :sp_AB_Shape_Cash_Book_IBS_Detail_Splits
--Purpose       :Selects Cash Book IBS Post History Detail Splits Shaped
--Date          :16 MAR 2010
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Shape_Cash_Book_IBS_Detail_Splits
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT ds.AB_Cash_Book_IBS_Detail_Splits_ID AS [ID],
           ds.AB_Cash_Book_IBS_Detail_ID AS [DetailID],
           gl.[Description] AS [GL Acct],
           tm.[Description] AS [Method],
           ds.Amount AS [Split Amount],
           ds.Tax_Amount AS [Split Tax],
           ds.Net_Amount AS [Split Net]
    FROM AB_Cash_Book_IBS_Detail_Splits ds
        LEFT JOIN AB_Accounts gl
            ON ds.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN Sys_AW_Tax_Methods tm
            ON ds.Sys_AW_Tax_Methods_ID = tm.Sys_AW_Tax_Methods_ID
    WHERE ds.AB_Cash_Book_IBS_Header_ID = @HeaderID AND
          ds.AW_User_Companies_ID = @CompanyID
    ORDER BY [AB_Cash_Book_IBS_Detail_Splits_ID]










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























-------------------------------------------------------------------------------
--Description   :sp_AB_Shape_Cash_Book_IBS_Header
--Purpose       :Selects Cask Book IBS Post History Header Shaped
--Date          :27 FEB 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                             PROCEDURE sp_AB_Shape_Cash_Book_IBS_Header
	(
        @CompanyBanksID int,
        @MonthID tinyint,
        @YearID smallint,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT h.AB_Cash_Book_IBS_Header_ID AS [ID],
           h.Posting_Type AS [Posting Type],
           h.AW_Company_Banks_ID AS [CompanyBanksID],
           b.[Description] AS [Bank],
           h.Date_Posted AS [Date Posted],
           h.Start_Date AS [Start Date],
           h.End_Date AS [End Date],
           m.[Description] AS [Month],
           y.[Description] AS [Year],
           h.Import_Filename AS [Import File],
           CONVERT(bit, h.Auto_Recon) AS [Recon],
           ISNULL(u.FirstName + ' ', '') + ISNULL(u.Surname, '') AS [User],
           a.[Description] AS [Active],
           h.Slu_AW_Active_ID AS [ActiveID]
    FROM AB_Cash_Book_IBS_Header h
        LEFT JOIN AW_Company_Banks cb
            ON h.AW_Company_Banks_ID = cb.AW_Company_Banks_ID
        LEFT JOIN Slu_AW_Banks b
            ON h.Slu_AW_Banks_ID = b.Slu_AW_Banks_ID
        INNER JOIN Slu_AW_Months m
            ON h.Slu_AW_Months_ID = m.Slu_AW_Months_ID
        INNER JOIN Slu_AW_Years y
            ON h.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        LEFT JOIN AW_Users u
            ON h.[User_ID] = u.AW_Users_ID
        LEFT JOIN Slu_AW_Active a
            ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID
    WHERE h.AW_Company_Banks_ID = @CompanyBanksID AND
          h.AW_User_Companies_ID = @CompanyID AND
          h.Slu_AW_Months_ID = @MonthID AND
          h.Slu_AW_Years_ID = @YearID
    ORDER BY h.Date_Posted DESC













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AB_Transaction_Numbers_Select
--Purpose       :Select GL Transaction Numbers
--Date          :2006/01/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AB_Transaction_Numbers_Select
	(
		@CompanyID int
	)

AS

	SELECT
		Sys_AB_Transaction_Numbers_ID as [ID],
		Sys_AB_Transaction_Types_ID as [TransactionType],
		Last_Number as [Last Number],
		Number_Suffix as [Suffix]
	FROM Sys_AB_Transaction_Numbers
	WHERE AW_User_Companies_ID = @CompanyID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AB_Transaction_Types_Select
--Purpose       :Select GL Transaction Types
--Date          :2006/01/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AB_Transaction_Types_Select

AS

	SELECT 
		Sys_AB_Transaction_Types_ID as [ID],
		Description,
		Transaction_Code as [Code]
	FROM Sys_AB_Transaction_Types






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AB_Transfer_GL_Account
--Purpose       :Transfers GL Account Balance from one account to another
--Date          :2009/05/09
--Authors       :TB
--MODS          :
--2004.4.8      :14/02/10 - Added new tables referencing AB_Accounts_ID
--              :16/03/10 - Added more new tables referencing AB_Accounts_ID - Cash_Book_IBS
--              :25/03/10 - Modified 'UPDATE the @TrfToGLID Account Balance' section to
--              :           SET AB_Accounts.AB_Account_Balance for the @TrfToGLID equal to
--              :           the SUM(AB_GL_Transactions.AB_Transaction_Amount) after transfer
--              :06/05/10 - Fixed set @GetNewAccountBalance - Used AB_GL_Transactions_ID
--              :           instead of AB_Accounts_ID !!!!!!!!!!!!!!!!!!!!!!!
--              :06/05/10 - Fixed Clear SOURCE GL Account balances if TRANSFER SUCCESSFUL
--              :           and added set Opening_Date, Opening_Month and Opening_Year
--              :09/05/10 - REMOVED DROP CONTRAINTS because NO DELETE is used when
--              :           TRANSFER AB_Accounts_ID's to NEW Account
--2004.5.0      :23/03/11 - Added Periodic Billing tables
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Transfer_GL_Account
    (
        @TrfFromGLID int,
        @TrfToGLID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @Account varchar(50),
            @TranTotal money,
            @TranCount int,
            @TransferGLDescription varchar(50),
            @TrfFromOpeningBalance money,
            @TrfToAccountBalance money,
            @TrfToOpeningBalance money,
            @GetNewAccountBalance money,
            @OpeningDate datetime,
            @RetCode int


    SET @TranTotal = 0
    SET @TranCount = 0
    SET @RetCode = 0


    ---------------------------------------------------------------
    --> Get the SOURCE Transaction Total and TarnCount
    ---------------------------------------------------------------
    SELECT @TranTotal = ISNULL(SUM(ISNULL(AB_Transaction_Amount, 0)), 0),
           @TranCount = count(*)
    FROM AB_GL_Transactions
    WHERE AB_Accounts_ID = @TrfFromGLID


    ---------------------------------------------------------------
    --> Get the SOURCE Opening Date - When TARGET is a NEW account
    ---------------------------------------------------------------
    SELECT @OpeningDate = Opening_Date
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID AND
          AB_Accounts_ID = @TrfFromGLID


    ---------------------------------------------------------------
    --> Transfer the @TrfFromGLID to the @TrfToGLID
    ---------------------------------------------------------------
    IF @TranCount <> 0
        BEGIN
            UPDATE AB_GL_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Budgets
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Cash_Book_Batches
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Cash_Book_Transaction_Details
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Journal_Details
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Recurring_Details
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AO_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AO_Transactions_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AS_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AS_Transactions_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_GL_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_GL_Transactions
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            -----------------------------------
            -- 2004.4.8 - 14/02/10 - Added new tables referencing AB_Accounts_ID
            -----------------------------------

            UPDATE AB_Control_Accounts
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AS_Till_Payouts
            SET AB_Account_DR_ID = @TrfToGLID
            WHERE AB_Account_DR_ID = @TrfFromGLID

            UPDATE AS_Till_Payouts
            SET AB_Account_CR_ID = @TrfToGLID
            WHERE AB_Account_CR_ID = @TrfFromGLID

            UPDATE AO_Remittance_Details_Temp
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AO_Statement_Details
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            -----------------------------------
            -- 2004.4.8 - 25/03/10 - more Cash_Book_IBS tables
            -----------------------------------

            UPDATE AB_Cash_Book_IBS_Map
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Cash_Book_IBS_Detail
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Cash_Book_IBS_Detail_Splits
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            UPDATE AB_Cash_Book_IBS_Map_Splits
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            ---------------------------------------------------------------
            --> RE_ASSIGN any existing LINKS to the deleted GL account
            ---------------------------------------------------------------

            UPDATE AW_Company_Banks
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID

            -----------------------------------
            -- 2004.5.0 - 23/03/11 - Periodic Billing tables
            -----------------------------------

            UPDATE AC_Periodic_Billing_Detail
            SET AB_Accounts_ID = @TrfToGLID
            WHERE AB_Accounts_ID = @TrfFromGLID


            ---------------------------------------------------------------
            --> UPDATE the @TrfToGLID Account Balance
            ---------------------------------------------------------------
            SELECT @TrfFromOpeningBalance = Opening_Balance
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AB_Accounts_ID = @TrfFromGLID


            SELECT @GetNewAccountBalance = SUM(AB_Transaction_Amount)
            FROM AB_GL_Transactions
            WHERE AB_Accounts_ID = @TrfToGLID


            --> Get TARGET account Opening Balances - if MERGING accounts
            SELECT @TrfToOpeningBalance = Opening_Balance
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AB_Accounts_ID = @TrfToGLID


            SET @TrfToOpeningBalance = @TrfToOpeningBalance + @TrfFromOpeningBalance


            --> Set TARGET account balances
            UPDATE AB_Accounts
            SET AB_Account_Balance = @GetNewAccountBalance,
                Opening_Balance = @TrfToOpeningBalance,
                Opening_Date = @OpeningDate
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AB_Accounts_ID = @TrfToGLID


            SET @RetCode = 1

        END


    ---------------------------------------------------------------
    --> Clear SOURCE GL Account balances if TRANSFER SUCCESSFUL
    ---------------------------------------------------------------
    IF @RetCode = 1
        BEGIN
            UPDATE AB_Accounts
            SET AB_Account_Balance = 0,
                Opening_Balance = 0,
                Opening_Date = NULL,
                Opening_Month = 0,
                Opening_Year = 0
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AB_Accounts_ID = @TrfFromGLID
        END


RETURN @RetCode


SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








CREATE   PROCEDURE sp_AB_Trial_Balance_Check
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

    BEGIN
        SELECT SUM(AB_Account_Balance) AS [AccountsTotal],
               COUNT(*) AS [AccountsNumber],
              (SELECT SUM(AB_Transaction_Amount)
               FROM AB_GL_Transactions) AS [TransTotal],
              (SELECT COUNT(*)
               FROM AB_GL_Transactions) AS [TransNumber]
        FROM AB_Accounts
        WHERE AW_User_Companies_ID = @CompanyID AND
              AB_Account_Balance <> 0
    
        SET @ReturnValue = 1
    END

RETURN @ReturnValue








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AB_Update_Cash_Book_Recon_History
--Purpose       :Updates Cash Book Reconciliation Transactions
--              :for specific Bank, Transaction Type, Accounting Period
--Functionality :Update
--Parameters    :
--Date          :2002/11/23
--Authors       :TB
--Version       :1.0.0
--MODS          :27/11/02 - Removed Recon-Chk field
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AB_Update_Cash_Book_Recon_History
    (
        @CBTranID int,
        @ReconcileAmount money,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    UPDATE AB_Cash_Book_Transactions
    SET Recon_Amount = @ReconcileAmount
    WHERE AB_Cash_Book_Transactions_ID = @CBTranID AND
          AW_User_Companies_ID = @CompanyID
 
SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AB_Update_GL_Account_Filters
--Purpose       :Update GL Accounts Filters
--Date          :2007/09/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Update_GL_Account_Filters
	(
        @GLAccountID int,
        @Description varchar(50),
        @AccountNo varchar(16),
        @CategoryID int,
        @DivisionID int,
        @GroupID int,
        @Active int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AB_Accounts_ID
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @GLAccountID

        )
        BEGIN
            UPDATE AB_Accounts
            SET Description = @Description,
                Account_Number = @AccountNo,
                Sys_AB_Account_Categories_ID = @CategoryID,
                Lup_AB_Account_Divisions_ID = @DivisionID,
                Lup_AB_Account_Groups_ID = @GroupID,
                Slu_AW_Active_ID = @Active
            WHERE AB_Accounts_ID = @GLAccountID

            SET @ReturnValue = 1

        END





RETURN @ReturnValue
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AB_Update_GL_Editor
--Functionality :Update an edited GL Transaction and Subsidiary Book Transactions AMOUNTS !!!!
--Date          :2006/03/03
--Authors       :TB
--MODS:         :12/03/06 - Added WHERE filter to also match on @TranTypeID in UPDATE
--              :           to AB_Cash_Book_Transactions and AB_Cash_Book_Transactions
--2004.4.2      :07/01/09 - NO LONGER USED - WE DO NOT UPDATE AMOUNTS - ALSO COMMENTED IN UI
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AB_Update_GL_Editor
    (
            @CompanyID int,
            @GLAccountID int,
            @GLTranID int,
            @TranTypeID as tinyint,
            @RefNo int,
            @Narration varchar(50),
            @PrevAmount money,
            @Amount money,
            @SourceRef varchar(20)
    )
AS

SET NOCOUNT ON


    DECLARE @CBTranID int,
            @ReturnValue int


    SET @CBTranID = 0
    SET @ReturnValue = 0


    --> UPDATE the Cash Book
    IF (@TranTypeID >= 9 AND @TranTypeID <= 14) OR (@TranTypeID >= 17 AND @TranTypeID <= 21)
        BEGIN
            UPDATE AB_Cash_Book_Transactions
            SET Transaction_Description = @Narration,
                Amount = (@Amount * -1),
                Reference_No = @SourceRef
            WHERE AB_Cash_Book_Transactions_ID = @RefNo AND
                  Sys_AB_Transaction_Types_ID = @TranTypeID


            --> GET the FIRST matching row (if multiple matches)
            SELECT TOP 1 @CBTranID = AB_Cash_Book_Transaction_Details_ID
            FROM AB_Cash_Book_Transaction_Details
            WHERE AB_Cash_Book_Transactions_ID = @RefNo
              AND AB_Accounts_ID = @GLAccountID
              AND Amount = @PrevAmount


            IF @CBTranID <> 0
                BEGIN
                    UPDATE AB_Cash_Book_Transaction_Details
                    SET Amount = @Amount
                    WHERE AB_Cash_Book_Transaction_Details_ID = @CBTranID
                END
        END


    --> UPDATE the General Journal
    IF @TranTypeID = 15 OR @TranTypeID = 16
        BEGIN
            UPDATE AB_Journals
            SET Journal_Narration = @Narration,
                Journal_Reference = @SourceRef
            WHERE AB_Journals_ID = @RefNo
        END


    --> UPDATE the General Journal Details
    IF @TranTypeID = 15 OR @TranTypeID = 16
        BEGIN
            UPDATE AB_Journal_Details
            SET Amount = @Amount
            WHERE AB_Journals_ID = @RefNo
              AND AB_Accounts_ID = @GLAccountID
              AND Amount = @PrevAmount
        END


    --> UPDATE the GL Transactions
    UPDATE AB_GL_Transactions
    SET [Description] = LEFT(@Narration, 50),
        AB_Transaction_Amount = ROUND(@Amount, 2),
        AB_Source_Ref = LEFT(@SourceRef, 20)
    FROM AB_GL_Transactions
    WHERE AW_User_Companies_ID = @CompanyID
      AND AB_GL_Transactions_ID = @GLTranID
      AND Sys_AB_Transaction_Types_ID = @TranTypeID


    --> UPDATE the GL Account Balance with the OLD Amount
    UPDATE AB_Accounts
    SET AB_Account_Balance = ROUND(AB_Account_Balance - @PrevAmount, 2)
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID
      AND AB_Accounts_ID = @GLAccountID


    --> UPDATE the GL Account Balance with the NEW Amount
    UPDATE AB_Accounts
    SET AB_Account_Balance = ROUND(AB_Account_Balance + @Amount, 2)
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID
      AND AB_Accounts_ID = @GLAccountID


    SET @ReturnValue = 1


RETURN @ReturnValue


SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AB_Update_GL_Editor
--Functionality :Update ALL Subsidiary Book component entries of an edited GL Transaction
--              :    if Date, Month, Year or Narration of one component entry is changed
--              :Also UPDATES AB_Cash_Book_Transactions and AB_Journals
--Date          :2006/03/03
--Authors       :TB
--MODS:         :12/03/06 - Added @Narration to UPDATE AB_GL_Transactions
--              :12/03/06 - Added WHERE filter to also match on @TranTypeID
--              :           in UPDATE to AB_GL_Transactions
--2004.4.2      07/01/09 - Added Transaction_Description = @Narration if Cash Book Transaction
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AB_Update_GL_Editor_Components
    (
            @CompanyID int,
            @GLTranID int,
            @TranTypeID as tinyint,
            @RefNo int,
            @SourceRef varchar(20),
            @PrevTranDate datetime,
            @NewTranDate datetime,
            @NewMonth tinyint,
            @NewYear int,
            @Narration varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    --> UPDATE the Cash Book
    IF (@TranTypeID >= 9 AND @TranTypeID <= 14) OR (@TranTypeID >= 17 AND @TranTypeID <= 21)
        BEGIN
            UPDATE AB_Cash_Book_Transactions
            SET Transaction_Date = @NewTranDate,
                Slu_AW_Months_ID = @NewMonth,
                Slu_AW_Years_ID = @NewYear,
                Transaction_Description = @Narration
            WHERE AB_Cash_Book_Transactions_ID = @RefNo
              AND Reference_No = @SourceRef
        END


    --> UPDATE the General Journal
    IF @TranTypeID = 15 OR @TranTypeID = 16
        BEGIN
            UPDATE AB_Journals
            SET Journal_Date = @NewTranDate,
                Slu_AW_Months_ID = @NewMonth,
                Slu_AW_Years_ID = @NewYear
            WHERE AB_Journals_ID = @RefNo
              AND Journal_Reference = @SourceRef
        END


    --> UPDATE the COMPONENT GL transactions
    UPDATE AB_GL_Transactions
    SET AB_Transaction_Date = @NewTranDate,
        Slu_AW_Months_ID = @NewMonth,
        Slu_AW_Years_ID = @NewYear,
        [Description] = @Narration
    FROM AB_GL_Transactions
    WHERE AW_User_Companies_ID = @CompanyID
      AND LEFT(CONVERT(CHAR(10), AB_Transaction_Date, 121), 10) = LEFT(CONVERT(CHAR(10), @PrevTranDate, 121), 10)
      AND AB_Transaction_Ref = @RefNo
      AND Sys_AB_Transaction_Types_ID = @TranTypeID

    SET @ReturnValue = 1


RETURN @ReturnValue


SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AB_Update_Last_AB_Transaction_Number
--Purpose       :Update GL Transaction numbers
--Date          :2002/01/19
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AB_Update_Last_AB_Transaction_Number

    (
    	@TransactionType int, 
        @CompanyID int,
        @TransactionNumber varchar(15)
    )

AS

SET NOCOUNT ON


	UPDATE Sys_AB_Transaction_Numbers
    SET Last_Number = @TransactionNumber
	WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AB_Transaction_Types_ID = @TransactionType









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_1800
--Purpose       :Fetch list of Customers for a company
--Functionality :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           Procedure sp_AC_1800
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT AC_Customers_ID AS [ID],
           Surname AS [Name]
    FROM AC_Customers
    WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AC_1801
--Purpose       :Update E-Mail Addresses and Cell Numbers
--              :    of Customer Contacts and Pricipals 
--Functionality :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :19/06/04 - Added Orders_URL = @AccountsEmail
-------------------------------------------------------------------------------

CREATE             Procedure sp_AC_1801
    (
        @CustomerID int,
        @ContactName varchar(30),
        @ContactCellNo varchar(16),
        @ContactEmail varchar(30),
        @PrincipalSurname varchar(30),
        @PrincipalFirstname varchar(20),
        @PrincipalBirthday datetime,
        @PrincipalCellNo varchar(16),
        @PrincipalEmail varchar(30),
        @AccountsEmail varchar(100)
    )

AS

SET NOCOUNT ON

	IF @CustomerID > 0 
		BEGIN
			UPDATE AC_Customers
            SET
                Contact_Name = @ContactName,
                Cell_No = @ContactCellNo,
                Orders_URL = @AccountsEmail,
                Home_Email = @ContactEmail,
                Work_Email = @PrincipalEmail,
                Sys_AW_Delivery_Methods_ID = 2,
                Principal_Name = @PrincipalSurname,
                Principal_Firstname = @PrincipalFirstname,
                Principal_Birthday = @PrincipalBirthday,
                Principal_Cell_No = @PrincipalCellNo,
                Principal_Contact_Method_ID = 2
			WHERE AC_Customers_ID = @CustomerID

		END


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AC_3000
--Purpose       :Retrieves List of Customers based on Search Filter for CRM
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2001/07/02
--Authors       :TB
--Version       :08 JUL 2001
--MODS          :05/07/04 - Added missing ELSE before 'Salesperson' (@SearchFilter = 6)
--              :07/07/04 - Changed [Customer Number] field to [Number] in options
--              :           3, 4 and 5 to fit PickList in E-mail Marketing
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_3000
    (
        @CompanyID int, 
        @SearchFilter int,
        @FetchChoice int,
        @Value int,
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON

-->ALL Customers
    IF @SearchFilter = 0
        SELECT c.AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               c.Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->All Customers with Sales
    IF @SearchFilter = 1
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->All Customers with No Sales
    IF @SearchFilter = 2
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID not in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->TOP 20%
    IF @SearchFilter = 3
        SELECT  ID, [Customer Name], [Number]
        FROM dbo.fn_AS_Top20Perc_Customers_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate)
    ELSE
-->NEXT 30%
    IF @SearchFilter = 4
        SELECT  a.ID, a.[Customer Name], a.[Number]
        FROM dbo.fn_AS_Top50Perc_Customers_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top20Perc_Customers_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.ID = b.ID
        WHERE b.ID is null
    ELSE
-->LAST 50%
    IF @SearchFilter = 5        SELECT  a.ID, a.[Customer Name], a.[Number]
        FROM dbo.fn_AS_Top100Perc_Customers_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top50Perc_Customers_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.ID = b.ID
        WHERE b.ID is null
    ELSE
-->Salesperson
    IF @SearchFilter = 6
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AS_Reps_ID = @Value AND
              c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4))  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->Sales Area
    IF @SearchFilter = 7
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Sales_Areas_ID = @Value AND
              c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4))  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->Language
    IF @SearchFilter = 8
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Languages_ID = @Value AND
              c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4))  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->Customer Type
    IF @SearchFilter = 9
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Types_ID = @Value AND
              c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4))  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->Credit Terms
    IF @SearchFilter = 10
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Credit_Terms_ID = @Value AND
              c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4))  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]
    ELSE
-->Discount Category
    IF @SearchFilter = 11
        SELECT AC_Customers_ID as ID,
               CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END as [Customer Name],
               Customer_Number as [Customer Number]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Discount_Categories_ID = @Value AND
              c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4))  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]



SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AC_3010
--Purpose       : Retrieves Sales for One Customer from AS_Transactions for CRM
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          : 19 JUL 2001
--Authors       : TB
--Version       : 1.0.0
---------------------------------------------------------------------------------------
--Returns a recordset of:
--    prior 24 WEEKS sales, aggregated by WEEK NUMBER 
--    prior 24 MONTH sales, aggregated by MONTH NUMBER
---------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE                     PROCEDURE sp_AC_3010
	@CustomerID int,
    @DataChoice int,
	@StartDate datetime,
	@EndDate datetime,
	@StartWeekNo int OUTPUT,
	@EndWeekNo int OUTPUT 

AS

SET NOCOUNT ON

IF @DataChoice = 0    --Weeks
    BEGIN
        SET @StartWeekNo = CONVERT(int, @StartDate) / 7
        SET @EndWeekNo = CONVERT(int, @EndDate) / 7

        SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
               SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
               SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
               SUM(d.Discount_Amount) as Discount,
               SUM(d.Quantity * d.Unit_Cost) as Cost,
               SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
               SUM(d.Quantity) as Quantity
        FROM  AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
              CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4)
        GROUP BY CONVERT(int, h.Transaction_Date) / 7
        ORDER BY WeekNo DESC
    END

ELSE    --Months
    BEGIN
        SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
        SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
        
        SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
               SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
               SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
               SUM(d.Discount_Amount) as Discount,
               SUM(d.Quantity * d.Unit_Cost) as Cost,
               SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
               SUM(d.Quantity) as Quantity
        FROM  AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
              dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4)
        GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
        ORDER BY DateString DESC
    END

SET NOCOUNT OFF





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   : sp_AC_3020
--Purpose       : Retrieves Quotes, Sales Orders, Job Cards
--              : for One Customer from AS_Transactions for CRM
--Parameters    :
--Date          : 13 JUL 2001
--Authors       : TB
--Version       : 1.0.0
--MODS          : 2002/04/21 - Changed Sales Orders to Invoices & Credit Notes
--              :24/06/04 - Added Status field to Job Cards in @DataChoice = 2
-------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE             PROCEDURE sp_AC_3020
	@CustomerID int,
    @DataChoice int,
	@StartDate datetime,
	@EndDate datetime

AS

SET NOCOUNT ON
-->Quotes
    IF @DataChoice = 0
        BEGIN
            SELECT h.Transaction_Number as [Number],
                   h.Transaction_Date as [Date],
                   h.Expiry_Date as [Expires],
                   p.Description as [Product],
                   d.Quantity as [Qty],
                   d.Extended_Amount as [Amount],
                   d.Tax_Amount as [Tax],
                  (d.Quantity * d.Unit_Cost) as [Total Cost],
                  (d.Unit_Price - d.Original_Price) * d.Quantity as [Price Disc],
                   d.Discount_Amount as [Sales Disc],
                  (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost) as [Income]
            FROM  AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = 1 AND    --Quote
                  h.Slu_AW_Active_ID <> 3 AND
                 (d.Date_captured >= @StartDate AND 
                  d.Date_captured <= @EndDate)
            ORDER BY [Date] DESC, [Number] 
        END
    ------------------------------------------------------------------------------------
    ELSE
-->Invoices and Refunds        -- WAS: Sales Orders
    IF @DataChoice = 1
        BEGIN
            SELECT h.Transaction_Number as [Number],
                   h.Transaction_Date as [Date],
                   p.Description as [Product],
                   d.Quantity as [Qty],
                   d.Extended_Amount as [Amount],
                   d.Tax_Amount as [Tax],
                  (d.Quantity * d.Unit_Cost) as [Total Cost],
                  (d.Unit_Price - d.Original_Price) * d.Quantity as [Price Disc],
                   d.Discount_Amount as [Sales Disc],
                  (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost) as [Income]
            FROM  AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
--                  (h.Sys_AW_Transaction_Types_ID = 16 OR      --Sales Order
--                   h.Sys_AW_Transaction_Types_ID = 17) AND    --Sales Order Reversal
                 (h.Sys_AW_Transaction_Types_ID = 3 OR          --Tax Invoice
                  h.Sys_AW_Transaction_Types_ID = 4) AND        --Tax Credit Note
                 (d.Date_captured >= @StartDate AND 
                  d.Date_captured <= @EndDate)
            ORDER BY [Date] DESC, [Number]
        END
    ------------------------------------------------------------------------------------
    ELSE
-->Job Cards
    IF @DataChoice = 2
        BEGIN
            SELECT h.Transaction_Number as [Number],
                   h.Transaction_Date as [Date],
                   p.Description as [Product],
                   d.Quantity as [Qty],
                   d.Extended_Amount as [Amount],
                   d.Tax_Amount as [Tax],
                  (d.Quantity * d.Unit_Cost) as [Total Cost],
                  (d.Unit_Price - d.Original_Price) * d.Quantity as [Price Disc],
                   d.Discount_Amount as [Sales Disc],
                  (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost) as [Income],
                   CASE WHEN h.Slu_AW_Active_ID = 1
                        THEN 'Open'
                        ELSE 'Closed'
                        END AS [Status]
            FROM  AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = 2 AND    --Job Cards
                 (d.Date_captured >= @StartDate AND 
                  d.Date_captured <= @EndDate)
            ORDER BY [Date] DESC, [Number]
        END

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AC_3030
--Purpose       :Retrieves One Customer from Customer Catalog for CRM
--Parameters    :
--Date          :09 JUL 2001
--Authors       :TB
--Version       :1.0.0
--MODS          :37/06/04 - Fixed Customer Type alias from ct. to ty.
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_3030
    (
        @CustomerID int,
        @D0 datetime = NULL,
        @D1 datetime = NULL,
        @D2 datetime = NULL,
        @D3 datetime = NULL,
        @D4 datetime = NULL,
        @D5 datetime = NULL,
        @D6 datetime = NULL,
        @D7 datetime = NULL
    )

AS

DECLARE @Now datetime
SET @Now = getdate()

SET NOCOUNT ON

SELECT
    c.AC_Customers_ID AS ID, 
	c.Customer_Number AS [Customer No], 
	c.Surname AS [Name], 
	c.Firstnames AS [First Names], 
	CASE WHEN t.Description = '<None>' OR t.Description IS NULL
         THEN ''
         ELSE t.Description
         END AS [Title], 
	c.Initials AS [Initials], 
	l.Description AS [Language], 
	c.IDReg_Number AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	a.Description AS [Active], 
	s.Description AS [Account Status],
	c.Contact_Name AS [Contact Name], 
	r.Description AS [Salesperson],
	c.Post_Box AS [Post Box], 
	c.Post_Office AS [Post Office], 
	c.Post_Code AS [Post Code], 
	c.Street_Address AS [Street Address], 
	c.Suburb AS [Suburb], 
	c.City AS [City], 
	c.Street_Post_Code AS [Street Code], 
	cu.Description + ' (' + cu.Country_Code3 + ')' AS [Country], 
	c.Delivery_Address AS [Delivery Address], 
	c.Delivery_Suburb AS [Delivery Suburb], 
	c.Delivery_City AS [Delivery City], 
	c.Delivery_Post_Code AS [Delivery Post Code], 
	c.Web_Site_URL AS [Web Site URL], 
	c.Orders_URL AS [Order URL], 
	c.Home_Email AS [E-mail Home], 
	c.Work_Email AS [E-mail Work],
	c.Home_Tel_No AS [Home Tel No], 
	c.Work_Tel_No AS [Work Tel No], 
	c.Cell_No AS [Cell No], 
	c.Fax_No AS [Fax No], 
	dc.Description AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ct.Description AS [Credit Terms],
	c.Credit_Insurers_Reference AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ci.Description AS [Charge Interest],
	sa.Description AS [Sales Area], 
	c.Head_Office AS [Head Office], 
	ty.Description AS [Customer Type], 
	tc.Description AS [Tax Code], 
	c.Tax_Number AS [Tax Number],
	act.Description AS [Account Types],
	ctt.Description AS [Credit Term Types],
	ISNULL(c.Account_Balance,0) AS [Account Balance],
	ISNULL(ag.[Current],0) AS [Current],
	ISNULL(ag.[30 Days],0) AS [30 Days],
	ISNULL(ag.[60 Days],0) AS [60 Days],
	ISNULL(ag.[90 Days],0) AS [90 Days],
	ISNULL(ag.[120 Days],0) AS [120 Days], 
	ISNULL(ag.[150 Days],0) AS [150 Days],
	ISNULL(ag.[180+ Days],0) AS [180+ Days],
	c.Notes,
    ag.CURRENTDATE,
    ag.DAYS30DATE,
    ag.DAYS60DATE,
    ag.DAYS90DATE,
    ag.DAYS120DATE,
    ag.DAYS150DATE,
    ag.DAYS180DATE

FROM AC_Customers c
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
        LEFT JOIN dbo.fn_AC_Customer_Ageing_Values(@CustomerID, @D0,@D1,@D2,@D3,@D4,@D5,@D6,@D7) ag
            ON c.AC_Customers_ID = ag.CustomerID
WHERE c.AC_Customers_ID = @CustomerID 

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








---------------------------------------------------------------------------------------
--Description   :sp_AC_3040
--Purpose       :Retrieves the MOST POPULAR Products for CRM
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--              :for One Customer from AS_Transactions for CRM
--Date          :14 JUL 2001
--Authors       :TB
--Version       :1.0.0
--MODS          :29/04/04 - Added [Last Sale] field
--2004.3.2      :30/09/06 - Added [Code] field
---------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE                     PROCEDURE sp_AC_3040
    (
    	@CustomerID int,
    	@StartDate datetime,
    	@EndDate datetime
    )

AS

SET NOCOUNT ON

    SELECT
        MAX(p.Description) AS [Product],
        MAX(p.Product_Code) AS [Code],
        MAX(CONVERT(datetime, CONVERT(CHAR(10), h.Transaction_Date, 121))) AS [Last Sale],
        CONVERT(money,SUM(d.Quantity)) AS [Qty],
        CONVERT(money,SUM(d.Extended_Amount)) AS [Amount],
        CONVERT(money,SUM(d.Tax_Amount)) AS [Tax],
        CONVERT(money,SUM((d.Quantity * d.Unit_Cost))) AS [Total Cost],
        CONVERT(money,SUM((d.Unit_Price - d.Original_Price) * d.Quantity)) AS [Price Disc],
        CONVERT(money,SUM(d.Discount_Amount)) AS [Sales Disc],
        CONVERT(money,SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost))) AS [Income],
        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
             THEN CONVERT(smallmoney,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
             ELSE 0.00
             END AS [Act GP%],
        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
             THEN CONVERT(smallmoney,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
             ELSE 0.00
             END AS [Std GP%]
    FROM AS_Transaction_Details d
        INNER JOIN AS_Transactions h
            ON h.AS_Transactions_ID = d.AS_Transactions_ID
        INNER JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
    WHERE h.AC_Customers_ID = @CustomerID AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4) AND
         (d.Date_Captured >= @StartDate AND
          d.Date_Captured <= @EndDate)
    GROUP BY p.AP_Products_ID
    ORDER BY [Income] DESC

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AC_3050
--Purpose       : Retrieves the Customer Interactions for CRM
--              : for One Customer from AW_Comments
--Parameters    :
--Date          : 14 JUL 2001
--Authors       : TB
--Version       : 1.0.0
---------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE          PROCEDURE sp_AC_3050
	@CompanyID int,
	@CustomerID int,
	@StartDate datetime,
	@EndDate datetime

AS

SET NOCOUNT ON

    SELECT i.AW_Comments_ID as [ID],
           i.Date_Captured AS [Date],
           CASE WHEN u.Firstname IS NULL
                THEN ISNULL(u.Surname,'')
                ELSE ISNULL(u.Surname,'') + ', ' + 
                     LTRIM(ISNULL(u.Firstname,''))
                END AS [User Name],
           i.[Comment] AS Message
    FROM AW_Comments i INNER JOIN AW_Users u
             ON i.User_ID = u.AW_Users_ID
    WHERE i.AW_User_Companies_ID = @CompanyID AND
          i.Sys_AT_Actor_Types_ID = -1 AND        --Customers
          i.Actor_ID = @CustomerID AND
         (i.Date_Captured >= @StartDate AND
          i.Date_Captured <= @EndDate)
    ORDER BY i.Date_Captured DESC

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AC_3060
--Purpose       :Retrieves List of constituent Sales Transactions in POPUP for CRM
--              :that make up the aggregated SALES COMPONENTS
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :Uses SHAPE and is part of sp_AC_3070
--Date          :2001/07/18
--Authors       :TB
--Version       :1.0.0
--MODS          :01/10/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :12/08/04 - Added h.Amount AS [Total], h.Comment AS [Notes]
--              :           and removed h.User_ID for Sales Analyst
-------------------------------------------------------------------------------

CREATE            PROCEDURE  sp_AC_3060
	(
        @PeriodType tinyint,        --Typically 0 = WEEKS, 1 = MONTHS
        @PeriodString varchar(6),   --Typically WEEKNO or YEARMONTHNO (5297 or 200106)
        @Component_Type tinyint,    --0 = SALES, 1 = Price Discount, 2 = Sales Discount etc
	    @CustomerID int
    )

AS

SET NOCOUNT ON

-----------------------------
IF @PeriodType = 0    --WEEKS
-----------------------------
-->Sales
    IF @Component_Type = 0
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
              d.Extended_Amount - d.Tax_Amount <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC
    ELSE
-->Price Discount
    IF @Component_Type = 1
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
            ((d.Original_Price - d.Unit_Price) * d.Quantity) <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC
    ELSE
-->Sales Discount
    IF @Component_Type = 2
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
             (d.Discount_Amount) <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC
    ELSE
-->Cost
    IF @Component_Type = 3
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
             (d.Quantity * d.Unit_Cost) <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC

------------------------------
IF @PeriodType = 1    --MONTHS
------------------------------
-->Sales
    IF @Component_Type = 0
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
             (d.Extended_Amount - d.Tax_Amount) <> 0 AND
             (MONTH(h.Transaction_Date) = CONVERT(int,SUBSTRING(@PeriodString,5,2)) AND
              YEAR(h.Transaction_Date) = CONVERT(int,SUBSTRING(@PeriodString,1,4)))
        ORDER BY h.Transaction_Date ASC
    ELSE
-->Price Discount
    IF @Component_Type = 1
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
            ((d.Original_Price - d.Unit_Price) * d.Quantity) <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC
    ELSE
-->Sales Discount
    IF @Component_Type = 2
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
              d.Discount_Amount <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC
    ELSE
-->Cost
    IF @Component_Type = 3
        SELECT h.AS_Transactions_ID as [ID],
               ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
               h.Amount AS [Total],
               h.Transaction_Date AS [Date],
               h.Transaction_Number AS [No],
               tt.Type_Code AS [Type],
               h.Customer_Reference AS [Order],
               h.Comment AS [Notes]
        FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users csh
                    ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
        WHERE h.AC_Customers_ID = @CustomerID AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4) AND
             (d.Quantity * d.Unit_Cost) <> 0 AND
              CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
        ORDER BY h.Transaction_Date ASC

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AC_3070
--Purpose       : Retrieves Sales Transaction Details in POPUP for CRM
--              : that make up the aggregated SALES COMPONENTS
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    : Uses SHAPE and is part of sp_AC_3060
--Date          : 2001/07/18
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE        PROCEDURE sp_AC_3070
	(@TransactionID int)

AS

SET NOCOUNT ON

SELECT td.AS_Transaction_Details_ID AS ID, 
       td.AS_Transactions_ID AS FKID, 
       p.Description as [Description                        ], 
      (td.Extended_Amount - td.Tax_Amount) AS [Sales    ],
     ((td.Unit_Price - td.Original_Price) * td.Quantity) AS [Price Adj],
      (td.Discount_Amount) AS [Discount ],
      (td.Quantity * td.Unit_Cost) AS [Cost    ],
     ((td.Extended_Amount - td.Tax_Amount) - (td.Quantity * td.Unit_Cost)) AS [Income  ],
      (td.Quantity) AS [Qty ]
FROM AS_Transaction_Details td
        LEFT JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
WHERE td.AS_Transactions_ID = @TransactionID

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--Description   : sp_AC_3080
--Purpose       : Retrieves Customers Lookups list based on Search Filter for CRM
--              :
--Parameters    :
--Date          : 2001/07/02
--Authors       : TB
--Version       : 08 AUG 2001
-------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AC_3080


   @Option varchar(30) = '',
--   @ID smallint = -1,
   @CompanyID int

AS

SET NOCOUNT ON

    IF @Option = 'Language'
        SELECT Slu_AW_Languages_ID AS [ID], Description AS [Language]
        FROM Slu_AW_Languages
    ELSE
    IF @Option = 'Type'
        SELECT Lup_AC_Customer_Types_ID AS [ID], Description AS [Type]
        FROM Lup_AC_Customer_Types
        WHERE AW_User_Companies_ID = @CompanyID
    ELSE
    IF @Option = 'Discount Category'
        SELECT Lup_AC_Discount_Categories_ID AS [ID], Description AS [Discount Category]
        FROM Lup_AC_Discount_Categories
        WHERE AW_User_Companies_ID = @CompanyID
    ELSE
    IF @Option ='Credit Terms'
        SELECT Slu_AW_Credit_Terms_ID AS [ID], Description AS [Credit Terms]
        FROM Slu_AW_Credit_Terms
    ELSE
    IF @Option = 'Salesperson'
        SELECT Lup_AS_Reps_ID AS [ID], Description AS [Salesperson]
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID
    ELSE
    IF @Option = 'Sales Area'
        SELECT Lup_AC_Sales_Areas_ID AS [ID], Description AS [Sales Area]
        FROM Lup_AC_Sales_Areas
        WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AC_Age_Transaction_Details
--Purpose       :Customer Metrics - Customer Ageing Popup
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :12/08/04 - Added new columns and re-formatted
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Age_Transaction_Details
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT     
    	td.AS_Transaction_Details_ID AS [ID], 
    	td.AS_Transactions_ID AS [FKID], 
    	p.[Description] as [Description], 
        p.Product_Code as [Code],
    	td.Unit_Price as [Unit Price],  
    	td.Quantity as [Qty], 
    	td.Extended_Amount AS [Amount],
    	td.Tax_Amount AS [Tax]
    FROM AS_Transaction_Details td
        LEFT JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
    WHERE AS_Transactions_ID = @TransactionID

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AC_Age_Transactions
--Purpose       :Customer Metrics - Customer Ageing Popup
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :12/08/04 - Added new columns and re-formatted
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Age_Transactions
	(
        @StartDate datetime,   --Typically ME Start Date
	    @EndDate datetime,     --Typically Month End Date
	    @CustomerID int
    )
AS

SET NOCOUNT ON

    SELECT
        t.AS_Transactions_ID AS [ID], 
        ISNULL(t.Customer_Reference, '') + ISNULL('/' + t.Comment, '') AS [Order / Notes],
        t.Transaction_Number AS [No],
        tt.Type_Code AS [Type],
        t.Transaction_Date AS [Date], 
        t.Total_Amount AS [Amount],
        (t.Total_Amount + t.Payment_Amount) AS [Owing]
    FROM AS_Transactions t
        INNER JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    WHERE (t.AC_Customers_ID = @CustomerID) AND
          (t.Sys_AW_Transaction_Types_ID = 3 OR
           t.Sys_AW_Transaction_Types_ID = 4 OR
           t.Sys_AW_Transaction_Types_ID = 5 OR
           t.Sys_AW_Transaction_Types_ID = 7 OR
           t.Sys_AW_Transaction_Types_ID = 15 OR
           t.Sys_AW_Transaction_Types_ID = 18) AND
          (t.Total_Amount + t.Payment_Amount <> 0) AND
          (t.Transaction_Date between @StartDate AND @EndDate)
    ORDER BY Transaction_Date ASC

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Check_Cellphone
--Purpose       :Format Cellphone Numbers
--Date          :2012-10-01
--Authors       :RGL
--MODS          :
--RL	V6.0	:2014-04-10 Added garbage removal and formating
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Check_Cellphone]
    (
        @intCountryID           int,
        @intCustomerID          int,        
        @strCellphone	        varchar(20),
        @strCellphone_Formated	varchar(20)OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE @strCountry_Code varchar(5),
            @strFirst_2      varchar(2),
            @strCell_Code	 varchar(2)
    
    Set @strCountry_Code = ''
    Set @strCell_Code = ''
    Set @strCellphone_Formated = ''
    Set @strCellphone = Ltrim(Rtrim(@strCellphone))
    Set @strCellphone = Replace(@strCellphone,'   ','')
    Set @strCellphone = Replace(@strCellphone,'  ','')
    Set @strCellphone = Replace(@strCellphone,' ','')
    Set @strCellphone = Replace(@strCellphone,'-','')
    Set @strCellphone = Replace(@strCellphone,'(','')
    Set @strCellphone = Replace(@strCellphone,')','')
   
    IF (@intCustomerID <> -1 AND @intCustomerID <> 0) 
    BEGIN
      Select @intCountryID = Slu_AW_Countries_ID
      From Ac_Customers
      Where AC_Customers_ID = @intCustomerID   
    
      SELECT @strCountry_Code = Country_Dialing_Code
      FROM Slu_AW_Countries
      WHERE Slu_AW_Countries_ID = @intCountryID    		
    END

	IF @strCountry_Code = ''
	BEGIN
		SELECT @strCountry_Code = Control_Value
		FROM Sys_AW_Options 
		WHERE Control_Name = 'txtCountryRegionCode'
	
		SELECT @intCountryID = Slu_AW_Countries_ID
		FROM Slu_AW_Countries
		WHERE IsNull(Country_Dialing_Code,'') = @strCountry_Code    		
	END
	
	IF @strCountry_Code = ''
	BEGIN		
		Set @intCountryID = 193
		
		SELECT @strCountry_Code = Country_Dialing_Code
		FROM Slu_AW_Countries
		WHERE Slu_AW_Countries_ID = @intCountryID    
	END

	IF Left(@strCellphone,5) = '00270'
		SET @strCellphone = Substring(@strCellphone,6,20)
		
	IF Left(@strCellphone,4) = '+270'
		SET @strCellphone = Substring(@strCellphone,4,20)
		
	IF Left(@strCellphone,4) = '0027'
		SET @strCellphone = Substring(@strCellphone,5,20)

	IF Left(@strCellphone,3) = '+27'
		SET @strCellphone = Substring(@strCellphone,4,20)

	IF Left(@strCellphone,3) = '027'
		SET @strCellphone = Substring(@strCellphone,4,20)

	IF Left(@strCellphone,2) = '27'
		SET @strCellphone = Substring(@strCellphone,3,20)

	IF Left(@strCellphone,1) <> '0'
		SET @strCellphone = '0' + @strCellphone
		
    SELECT @strFirst_2 = Substring(@strCellphone,1,2)
   
    SELECT @strCell_Code = Mobile_Dialing_Code
    FROM Slu_AW_Countries_Mobile
    WHERE Slu_AW_Countries_ID = @intCountryID
    AND Mobile_Dialing_Code = @strFirst_2
       
	IF @strCountry_Code != ''
	BEGIN   
		IF @strCell_Code != ''
		BEGIN
			IF Len(@strCellphone) = 10
			BEGIN
				SET @strCellphone_Formated = @strCountry_Code + Right(@strCellphone,9)
			END	
		END          
	END
    
    SELECT @strCellphone_Formated
    
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Clear_CBilling_Temp
--Functionality :DROP and CREATE sp_AC_Clear_CBilling_Temp
--Date          :2005/10/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Clear_CBilling_Temp]

AS

SET NOCOUNT ON


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AS_Transactions_CBilling_Temp]
        
        
        CREATE TABLE [dbo].[AS_Transactions_CBilling_Temp] (
        	[AS_Transactions_CBilling_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AS_Transactions_ID] [int] NULL ,
        	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
        	[cat_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[trs_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[trs_date] [datetime] NULL ,
        	[qty] [decimal](18,3) NULL ,
        	[amount] [money] NULL ,
        	[gls_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[narr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[stock_group] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_apply] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[sys_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[updated] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[interfaced] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_age_month] [smallint] NULL ,
        	[stock_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[area] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_alpha] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[branch] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[vat_amount] [money] NULL ,
        	[cost_amount] [money] NULL ,
        	[rep_comm] [money] NULL ,
        	[process_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[rep_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[acct_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[disc_amnt] [money] NULL ,
        	[std_sell_price] [money] NULL ,
        	[drs_trs_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[trs_type] [smallint] NULL ,
        	[acc_month] [smallint] NULL ,
        	[acc_year] [smallint] NULL ,
        	[con_acct_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_int01] [smallint] NULL ,
        	[cntno] [smallint] NULL ,
        	[line_disc1] [decimal](18, 3) NULL ,
        	[line_disc2] [decimal](18, 3) NULL ,
        	[stock_sell1] [money] NULL ,
        	[no_of_deals] [smallint] NULL ,
        	[zz_date01] [datetime] NULL ,
        	[zz_date02] [datetime] NULL ,
        	[zz_date03] [datetime] NULL ,
        	[special_instr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[deals_flag] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[deals_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[vat_exempt_member] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[cmonth] [smallint] NULL ,
        	[cyear] [smallint] NULL ,
        	[rep_call_status] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drsdiv_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[crs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[creation_date] [datetime] NULL ,
        	[creation_time] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[creation_userid] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[creation_proc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[item_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[rep_code2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[qty2] [decimal](18,3) NULL ,
        	[deposit_amount] [decimal](18, 3) NULL ,
        	[job_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[line_disc_amnt] [decimal](18, 3) NULL ,
        	[carhire_cntno] [smallint] NULL ,
        	[currency] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[exch_rate] [money] NULL ,
        	[cyear_month] [smallint] NULL ,
        	[zz_date04] [datetime] NULL ,
        	[zz_date05] [datetime] NULL ,
        	[zz_int02] [smallint] NULL ,
        	[zz_int03] [smallint] NULL ,
        	[zz_int04] [smallint] NULL ,
        	[zz_int05] [smallint] NULL ,
        	[zz_dec01] [decimal](18,3) NULL ,
        	[zz_dec02] [decimal](18,3) NULL ,
        	[zz_dec03] [decimal](18,3) NULL ,
        	[zz_dec04] [decimal](18,3) NULL ,
        	[zz_dec05] [decimal](18,3) NULL ,
        	[zz_log01] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log02] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log03] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log04] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log05] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log06] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log07] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char01] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char02] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char03] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char04] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char05] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[key_glstrs] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[key_history] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[dumped] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[company_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[branch_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[crs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[prd_grp_descr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[stk_descry] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[status_ind] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[customer_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments3] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments4] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments5] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments6] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments7] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments8] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[database_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[system_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[vat_reg_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[email] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[customer_cell_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[customer_email_address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
        
        
        ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AS_Transactions_CBilling_Temp] PRIMARY KEY  CLUSTERED 
        	(
        		[AS_Transactions_CBilling_Temp_ID]
        	)  ON [PRIMARY] 
        
        
        ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] ADD 
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_acc] DEFAULT ('SPIRAL') FOR [drs_acc],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_gls_acc] DEFAULT ('N/A') FOR [gls_acc],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_sys_code] DEFAULT ('SPI') FOR [sys_code],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_updated] DEFAULT ('no') FOR [updated],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_interfaced] DEFAULT ('no') FOR [interfaced],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_area] DEFAULT ('N/A') FOR [area],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_acct_type] DEFAULT ('N/A') FOR [acct_type],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_trs_code] DEFAULT ('100') FOR [drs_trs_code],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_vat_exempt_member] DEFAULT ('no') FOR [vat_exempt_member],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_rep_call_status] DEFAULT ('no') FOR [rep_call_status],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log01] DEFAULT ('no') FOR [zz_log01],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log02] DEFAULT ('no') FOR [zz_log02],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log03] DEFAULT ('no') FOR [zz_log03],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log04] DEFAULT ('no') FOR [zz_log04],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log05] DEFAULT ('no') FOR [zz_log05],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log06] DEFAULT ('no') FOR [zz_log06],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log07] DEFAULT ('no') FOR [zz_log07],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_dumped] DEFAULT ('no') FOR [dumped],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_status_ind] DEFAULT ('NE') FOR [status_ind],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_database_id] DEFAULT ('SPIRAL') FOR [database_id]
        
        
        setuser
        
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling_Temp].[AW_User_Companies_ID]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AS_Transactions_CBilling_Temp].[Date_Captured]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[drs_age_month]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling_Temp].[Slu_AW_Active_ID]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[trs_type]'
        
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling_Temp].[User_ID]'
        
        
        setuser

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AC_Contract_Product_Lups
--Purpose       :Returns LUPS for Contract Products
--Functionality :
--Date          :2004/03/12
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE          Procedure sp_AC_Contract_Product_Lups
    (
    	@Option int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


    	IF @Option = 1    --> Active
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] AS [Active]
    		FROM Slu_AW_Active

        ELSE
        IF @Option = 2    --> Yes No
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description] AS [YesNo]
            FROM Slu_AW_YesNo

        ELSE
        IF @Option = 3    --> Credit Terms
          	SELECT Slu_AW_Credit_Terms_ID AS [ID],
                [Description] AS [Terms]
            FROM Slu_AW_Credit_Terms
            WHERE Slu_AW_Credit_Terms_ID > 1    --To ALWAYS incude <None>

        ELSE
    	IF @Option = 4    --> Supplier
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name ASC
    	ELSE 
    	IF @Option = 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]
    	ELSE 
    	IF @Option = 6    --> Type
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			  [Description] AS [Type] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 7    --> Group
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			  [Description] AS [Group] 
    		FROM Lup_AP_Product_Groups	
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 8    --> Department
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			  [Description] AS [Department] 
    		FROM Lup_AP_Product_Departments
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 9    --> Location
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			  [Description] AS [Location] 
    		FROM Lup_AP_Product_Locations
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 10    --> Users
          	SELECT AW_Users_ID as [ID],
                   ISNULL(FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
            FROM AW_Users 
            ORDER BY [User]
        ELSE
    	IF @Option = 11    --> ALL Suppliers
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY Supplier_Name ASC

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Ageing_Select_All
--Purpose       :Retrieve Customer Statement date for AR2 Statement Printing
--              :Age Areas are Current to 120+ days
--Parameters    :
--Date          :2002/03/04
--Authors       :TB
--MODS          :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AC_Customer_Ageing_Select_All
	(
        @CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime

	SET @Now = getdate()

--> Retrieves last (up to) 7 Month-Ends DATES
	EXEC sp_AW_Period_Procedures_Select
        @Now,
        @D1 OUTPUT,
        @D2 OUTPUT,
        @D3 OUTPUT,
        @D4 OUTPUT,
        @D5 OUTPUT,
        @D6 OUTPUT,
        @D7 OUTPUT,
        1,
        @CompanyID

	SELECT 
		CustomerID, 
		Customer AS Customer, 
		SUM(Amount  + Payment) 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] + [150 Days] + [180+ Days]) AS [120+ Days]
	FROM fn_AC_Customer_Ageing_Non_Grouped_All_Customers
        (
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7,
            @CompanyID
        ) 
    GROUP BY CustomerID, Customer

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Ageing_Select_All_Detail
--Purpose       :Retrieve Customer Ageing With Customer Details
--              :Age Areas are Current to 180+ days
--Parameters    :
--Date          :2014/08/12
--Authors       :RL
------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Customer_Ageing_Select_All_Detail]
	(
        @CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime

	SET @Now = getdate()

--> Retrieves last (up to) 7 Month-Ends DATES
	EXEC sp_AW_Period_Procedures_Select
        @Now,
        @D1 OUTPUT,
        @D2 OUTPUT,
        @D3 OUTPUT,
        @D4 OUTPUT,
        @D5 OUTPUT,
        @D6 OUTPUT,
        @D7 OUTPUT,
        1,
        @CompanyID

	SELECT 
    c.AC_Customers_ID AS [ID], 
	ISNULL(c.Customer_Number,'') AS [Customer No], 
	ISNULL(c.Surname,'') AS [Name], 
	ISNULL(c.Firstnames,'') AS [First Names], 
	CASE WHEN t.[Description] = '<None>' OR t.[Description] IS NULL
         THEN ''
         ELSE t.[Description]
         END AS [Title], 
	ISNULL(c.Initials,'') AS [Initials], 
	ISNULL(l.[Description],'') AS [Language], 
	ISNULL(c.IDReg_Number,'') AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	ISNULL(a.[Description],'') AS [Active], 
	ISNULL(s.[Description],'') AS [Account Status],
	ISNULL(c.Contact_Name,'') AS [Contact Name], 
	ISNULL(r.[Description],'') AS [Salesperson],
	ISNULL(c.Post_Box,'') AS [Post Box], 
	ISNULL(c.Post_Office,'') AS [Post Office], 
	ISNULL(c.Post_Code,'') AS [Post Code], 
	ISNULL(c.Street_Address,'') AS [Street Address], 
	ISNULL(c.Suburb,'') AS [Suburb], 
	ISNULL(c.City,'') AS [City], 
	ISNULL(c.Street_Post_Code,'') AS [Street Code], 
	ISNULL(cu.[Description],'') + ' (' + ISNULL(cu.Country_Code3,'') + ')' AS [Country], 
	ISNULL(c.Delivery_Address,'') AS [Delivery Address], 
	ISNULL(c.Delivery_Suburb,'') AS [Delivery Suburb], 
	ISNULL(c.Delivery_City,'') AS [Delivery City], 
	ISNULL(c.Delivery_Post_Code,'') AS [Delivery Post Code], 
	ISNULL(c.Web_Site_URL,'') AS [Web Site URL], 
	ISNULL(c.Orders_URL,'') AS [Order URL], 
	ISNULL(c.Home_Email,'') AS [E-mail Home], 
	ISNULL(c.Work_Email,'') AS [E-mail Work],
	ISNULL(c.Home_Tel_No,'') AS [Home Tel No], 
	ISNULL(c.Work_Tel_No,'') AS [Work Tel No], 
	ISNULL(c.Cell_No,'') AS [Cell No], 
	ISNULL(c.Fax_No,'') AS [Fax No], 
	ISNULL(dc.[Description],'') AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ISNULL(ct.[Description],'') AS [Credit Terms],
	ISNULL(c.Credit_Insurers_Reference,'') AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ISNULL(ci.[Description],'') AS [Charge Interest],
	ISNULL(sa.[Description],'') AS [Sales Area], 
	ISNULL(c.Head_Office,'') AS [Head Office], 
	ISNULL(ct.[Description],'') AS [Customer Type], 
	ISNULL(tc.[Description],'') AS [Tax Code], 
	ISNULL(c.Tax_Number,'') AS [Tax Number],
	ISNULL(act.[Description],'') AS [Account Types],
	ISNULL(ctt.[Description],'') AS [Credit Term Types],
	ISNULL(c.Notes,'') AS [Notes],
	ISNULL(x.Amount,0) AS Amount,
	ISNULL(x.Payment,0) As Payment, 
	ISNULL(x.[Current],0) AS [Current], 
	ISNULL(x.[30 Days],0) AS [30 Days], 
	ISNULL(x.[60 Days],0) AS [60 Days], 
	ISNULL(x.[90 Days],0) AS [90 Days], 
	ISNULL(x.[120 Days],0) As [120 Days],
	ISNULL(x.[150 Days],0) As [150 Days],
	ISNULL(x.[180+ Days],0) AS [180+ Days]
	FROM fn_AC_Customer_Ageing_Grouped_All_Customers
        (
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7
        ) x
        RIGHT OUTER JOIN AC_Customers c
			On c.AC_Customers_ID = x.CustomerID
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID			 

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Ageing_Values
--Purpose       :Retrieves Customer Statement and Age Analaysis Ageing Data
--Tables        :dbo.fn_AC_Customer_Ageing_Values
--Parameters    :rptCustomerStatements, rptCustomerAgeing
--Date          :2002/03/07
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AC_Customer_Ageing_Values
	(
		@CustomerID int,
		@Now DateTime,
		@D1 DateTime,
		@D2 DateTime,
		@D3 DateTime,
		@D4 DateTime,
		@D5 DateTime,
		@D6 DateTime,
		@D7 DateTime
	)
AS
	SELECT *
    FROM dbo.fn_AC_Customer_Ageing_Values
        (
            @CustomerID,
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7
        )








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Assets_Insert_Update
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :21/07/03 - Added Addition fields:
--              :           Model_Year, Engine_No, Chassis_No, VIN_No, Mileage_Date
--              :06/03/04 - Added Tyre_Size, Tyre_Qty
--V6.0	RL	2014-10-29	:Added AS_Transactions_ID
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Customer_Assets_Insert_Update]
    (
    	@AssetID int,
    	@CustomerID int,
    	@AssetTypeID smallint,
    	@Make varchar(30),
    	@Model varchar(30),
        @ModelYear varchar(10),
    	@RegNo varchar(10),
        @Engine varchar(24),
        @Chassis varchar(24),
        @VIN varchar(24),
    	@Mileage varchar(10),
        @MileageDate varchar(10),
        @TyreSize varchar(20),
        @TyreQty varchar(10),
        @AS_Transactions_ID int,
    	@CompanyID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    IF @AssetID > 0
		BEGIN
			UPDATE AC_Assets
            SET AC_Customers_ID = @CustomerID,
                Lup_AC_Asset_Types_ID = @AssetTypeID,
                Make = @Make,
                Model = @Model,
                Model_Year = @ModelYear,
                Reg_No = @RegNo,
                Engine_No = @Engine,
                Chassis_No = @Chassis,
                VIN_No = @VIN,
                Mileage = @Mileage,
                Mileage_Date = @MileageDate,
                Tyre_Size = @TyreSize,
                Tyre_Qty = @TyreQty,
                AW_User_Companies_ID = @CompanyID,
                [User_ID] = @UserID,
                Date_Captured = getdate(),
                AS_Transactions_ID = @AS_Transactions_ID
			WHERE AC_Assets_ID = @AssetID			
		END
	ELSE
		BEGIN	
			INSERT AC_Assets 
				(
                    AC_Customers_ID,
                    Lup_AC_Asset_Types_ID,
                    Make,
                    Model,
                    Model_Year,
                    Reg_No,
                    Engine_No,
                    Chassis_No,
                    VIN_No,
                    Mileage,
                    Mileage_Date,
                    Tyre_Size,
                    Tyre_Qty,
                    AW_User_Companies_ID,
                    [User_ID],
                    Date_Captured,
                    AS_Transactions_ID
				)
            VALUES
				(
					@CustomerID,
                    @AssetTypeID,
                    @Make,
                    @Model,
                    @ModelYear,
                    @RegNo,
                    @Engine,
                    @Chassis,
                    @VIN,
                    @Mileage,
                    @MileageDate,
                    @TyreSize,
                    @TyreQty,
                    @CompanyID,
                    @UserID,
                    GetDate(),
                    @AS_Transactions_ID
				)

			SELECT @AssetID = Scope_Identity()
			
		END

RETURN @AssetID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Assets_Select
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :21/07/03 - Added Addition fields:
--              :           Model_Year, Engine_No, Chassis_No, VIN_No, Mileage_Date
--              :06/03/04 - Added Tyre_Size, Tyre_Qty
------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AC_Customer_Assets_Select
    (
    	@CustomerID int
    )

AS

SET NOCOUNT ON

    SELECT
        AC_Assets_ID AS [AssetID],
        AC_Customers_ID AS [CustomerID],
        Lup_AC_Asset_Types_ID AS [AssetTypeID],
        Make AS [Make],
        Model AS [Model],
        Model_Year AS [ModelYear],
        Reg_No AS [RegNo],
        Engine_No AS [Engine],
        Chassis_No AS [Chassis],
        VIN_No AS [VIN],
        Mileage AS [Mileage],
        Mileage_Date AS [MileageDate],
        Tyre_Size AS [TyreSize],
        Tyre_Qty AS [TyreQty],
        AW_User_Companies_ID AS [CompanyID],
        [User_ID] AS [UserID]
    FROM AC_Assets
    WHERE AC_Customers_ID = @CustomerID

SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















---------------------------------------------------------------------------------
--Description   :sp_AC_Customer_CostPlus_Filter_Lups
--Purpose       :Filters Customers to set Customer Cost+Plus Categories globally
--Date          :2007/07/29
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AC_Customer_CostPlus_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    --> Cost+Plus Groups
          	SELECT Lup_AP_Markup_Groups_ID AS [ID],
                [Description] 	
            FROM Lup_AP_Markup_Groups

        ELSE
        IF @Option = 8    --> Credit Terms
          	SELECT Slu_AW_Credit_Terms_ID AS [ID],
                [Description] 	
            FROM Slu_AW_Credit_Terms

    	ELSE 
    	IF @Option = 9    --> Cost+Plus Categories
    		SELECT Lup_AC_Markup_Categories_ID AS [ID],
    			[Description]
    		FROM Lup_AC_Markup_Categories

        ELSE
        IF @Option = 10   --> Yes No
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description]  	
            FROM Slu_AW_YesNo



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













---------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Discount_Filter_Lups
--Purpose       :Filters Customers to set Customer Discount Categories globally
--Date          :2006/10/07
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Customer_Discount_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    --> Discount Groups
          	SELECT Lup_AP_Discount_Groups_ID AS [ID],
                [Description] 	
            FROM Lup_AP_Discount_Groups

        ELSE
        IF @Option = 8    --> Credit Terms
          	SELECT Slu_AW_Credit_Terms_ID AS [ID],
                [Description] 	
            FROM Slu_AW_Credit_Terms

    	ELSE 
    	IF @Option = 9    --> Discount Categoeris
    		SELECT Lup_AC_Discount_Categories_ID AS [ID],
    			[Description]
    		FROM Lup_AC_Discount_Categories



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Has_Message
--Purpose       :Returns @ReturnCode if CUSTOMER has received MessageID
--              :    for a specific MONTH
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Customer_Has_Message
	(
		@CompanyID int,
        @CustomerID int,
        @MessageID int,
        @Date datetime
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnCode bit

    SET @ReturnCode = 0

    SELECT @ReturnCode = dbo.fn_AC_Customer_Has_Message(@CompanyID, @CustomerID, @MessageID, @Date)

    RETURN @ReturnCode










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Has_Message_Span_Period
--Purpose       :Returns @ReturnCode if CUSTOMER has received MessageID
--              :    for a PERIOD SPAN in MONTHS
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Customer_Has_Message_Span_Period
	(
		@CompanyID int,
        @CustomerID int,
        @MessageID int,
        @Date datetime,
        @Months int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnCode bit

    SET @ReturnCode = 0

    SELECT @ReturnCode = dbo.fn_AC_Customer_Has_Message_Span_Period(@CompanyID, @CustomerID, @MessageID, @Date, @Months)

    RETURN @ReturnCode










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AC_Customer_Interest_Jnl_Select_All
--Purpose       :Retrieves overdue Customers eligible for Interest Journals
--              :
--Parameters    :
--Date          :2002/06/25
--Authors       :TB
--Version       :1.0.0
--MODS          :16/07/02 - Added SELECT AW_YesNo_Charge_Interest_ID
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--              :01/05/05 - Added [TermsValue] field to widen the net
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Customer_Interest_Select_All
   (        
        @TranDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime

-----------------------------
--     SET @TranDate = getdate()
--     SET @CompanyID = 1
-----------------------------

	SET @Now = @TranDate
    
--> Retrieves last (up to) 7 Month-Ends DATES
	EXEC sp_AW_Period_Procedures_Select
        @Now,
        @D1 OUTPUT,
        @D2 OUTPUT,
        @D3 OUTPUT,
        @D4 OUTPUT,
        @D5 OUTPUT,
        @D6 OUTPUT,
        @D7 OUTPUT,
        1,            --1 = Customers
        @CompanyID

	SELECT
		a.CustomerID, 
		RTRIM(LTRIM(ISNULL(a.Customer, ''))) AS [Customer],
        MAX(ISNULL(c.Customer_Number, '')) AS [CustNo],
        MAX(ISNULL(c.Post_Box, '')) AS [Post Box],
        MAX(ISNULL(c.Post_Office, '')) AS [Post Office],
        MAX(ISNULL(c.Post_Code, '')) AS [Post Code],
        MAX(ISNULL(c.Slu_AW_Credit_Terms_ID, 1)) AS [CTID],
        MAX(RTRIM(LTRIM(ISNULL(t.[Description], '')))) AS [Terms],
        MAX(RTRIM(LTRIM(ISNULL(t.Terms_Value, 0)))) AS [TermsValue],
        MAX(ISNULL(c.AW_YesNo_Charge_Interest_ID, 0)) AS [ChargeInterest],
		SUM(a.Amount + a.Payment) AS [Balance], 
        SUM(a.[Current]) AS [Current], 
        SUM(a.[30 Days]) AS [30 Days], 
        SUM(a.[60 Days]) AS [60 Days], 
        SUM(a.[90 Days]) AS [90 Days], 
        SUM(a.[120 Days]) AS [120 Days], 
        SUM(a.[150 Days]) AS [150 Days], 
        SUM(a.[180+ Days]) AS [180 Days]
    FROM dbo.fn_AC_Customer_Ageing_Non_Grouped_All_Customers
        (
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7,
            @CompanyID
        ) a
        LEFT JOIN AC_Customers c
            ON c.AC_Customers_ID = a.CustomerID
        LEFT JOIN Slu_AW_Credit_Terms t
            ON c.Slu_AW_Credit_Terms_ID = t.Slu_AW_Credit_Terms_ID
    GROUP BY CustomerID, Customer
    ORDER BY Customer


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Journals_Insert_Update
--Purpose       :Posts Customer Journals
--Functionality :Used in Customer Journals
--Parameters    :
--Date          :2002/02/26
--Authors       :TB
--Mods          :11/06/02 - Added UPDATE Customer Account_Balance
--              :11/06/18 - Removed INSERT of Date_Captured in AS_Transactions
--              :24/06/02 - Reduced @Comment to varchar(20) per DB Definition
--              :25/06/02 - Differentiate between Normal JNL and Interest JNL
--              :           in sp_AB_Insert_GL_Transactions with @GLTranTypeID
--              :NB NB NB   REQUIRES MOD TO ID=23 of Sys_AB_Transaction_Types
--              :07/07/02 - Removed GL UPDATE. This is done in the DAY-END sp:
--              :                sp_AS_Day_End
--              :28/07/02 - Put back GL Update (was never put into sp_AS_Day_End)
--              :07/01/03 - Put back update of AB_Accounts_ID in AS_Transactions
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :06/08/04 - Added Lup_AS_Cashiers_ID and insert @UserID to standarize
--2004.3.2      :17/10/06 - Added Customer Surname to GL Description
--2004.5.0      :25/01/11 - Renamed @ID to @@DocumentID, replaced SET with SELECT for Scope_Identity()
--              :           and added RETURN @DocumentID for Periodic Billing Journals
--V6.2	2016-08-02	:Added Accounts Receivable - Bad Debt for TAX Report distinction
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Customer_Journals_Insert_Update]
	(
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(20),
		@Amount money,
		@Tax money,
		@Total money,
		@Account int,
		@Month int, 
		@Year int,
		@TransactionType int,
		@FKID int,
		@CompanyID int,
		@UserID int
	)
AS     

SET NOCOUNT ON

    DECLARE @DocumentID int,
            @GLAccountID int,
            @GLTranTypeID tinyint,
            @GLSourceRef varchar(20),
            @NextGLTranID int,
            @Surname varchar(40),
            @GLDescription varchar(50),
            @CommentLen smallint

    IF @TransactionType = 5
        SET @GLTranTypeID = 22    --Sys_AB_Transaction_Types_ID - Accounts Receivable - Journal
    ELSE
    IF @TransactionType = 15
        SET @GLTranTypeID = 23    --Sys_AB_Transaction_Types_ID - Accounts Receivable - Interest
    ELSE
    --V6.2	Rl	2016-08-04 --Changed to display in own section on TAX report
    IF @TransactionType = 36
        SET @GLTranTypeID = 32    --Sys_AB_Transaction_Types_ID - Accounts Receivable - Bad Debt

	--V6.3 RL 2017-05-15 Fix. System does not pick up transaction type 36
   IF @TransactionType = 36
        SET @TransactionType = 5

-------------------------------------------------------------------------------
--> UPDATE CUSTOMER
-------------------------------------------------------------------------------
	INSERT AS_Transactions 
		(
	         Transaction_Number,
		     Transaction_Date,
	         [Amount] ,
	         Total_Tax_Amount,
	         Total_Amount,
	         AB_Accounts_ID ,
	         Comment,
	         Sys_AW_Transaction_Types_ID ,
	         AC_Customers_ID ,	
             Lup_AS_Cashiers_ID,
		     AW_User_Companies_ID,
		     [User_ID]
		)
	VALUES
		(
			@RefNo,
			@Date,
			@Amount,
			@Tax,
			@Total,
			@Account,
			@Comment,
			@TransactionType ,
			@FKID,
            @UserID,
			@CompanyID,
			@UserID
		)

    SELECT @DocumentID = Scope_Identity()


--> UPDATE Customer Account Balance
	UPDATE AC_Customers
    SET Account_Balance = Account_Balance + @Total
    WHERE AC_Customers_ID = @FKID


-------------------------------------------------------------------------------
--> UPDATE GL
-------------------------------------------------------------------------------

    SELECT @Surname = Surname
    FROM AC_Customers
    WHERE AC_Customers_ID = @FKID


    SET @CommentLen = LEN(@Comment) + 2
    SET @GLDescription = LEFT(LEFT(@Comment, 20) + ' ' + LEFT(@Surname, (50 - @CommentLen)), 50)


--> Create NORMAL JOURNAL header for the Year-End - 22 = Accounts Receivable - Journal
	EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    22,
                                    @CompanyID


    SELECT @GLAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 101	
	
--> INSERT a GL Transaction for the Debtors Control GL Account
    EXEC sp_AB_Insert_GL_Transactions
            @GLDescription,
            @GLTranTypeID,
            @GLAccountID,
            @Date,
            @RefNo,
            @Month,
            @Year,
            @DocumentID,
            @Total,
            @UserID,
            @CompanyID
		
	SET @Amount = -@Amount
	SET @Tax = -@Tax

--> INSERT a GL Transaction for the VAT GL Account
	IF @Tax <> 0 
		BEGIN
			SELECT @GLAccountID = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 401	
			
            EXEC sp_AB_Insert_GL_Transactions
                    @GLDescription,
                    @GLTranTypeID,
                    @GLAccountID,
                    @Date,
                    @RefNo,
                    @Month,
                    @Year,
                    @DocumentID,
                    @Tax,
                    @UserID,
                    @CompanyID
		END

--> INSERT a GL Transaction for the SELECTED GL Account
	EXEC sp_AB_Insert_GL_Transactions
            @GLDescription,
            @GLTranTypeID,
            @Account,
            @Date,
            @RefNo,
            @Month,
            @Year,
            @DocumentID,
            @Amount,
            @UserID,
            @CompanyID	




RETURN @DocumentID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_List_Select
--Purpose       :Gets a Customer List 
--Functionality :Used in Journal and Interest Journal
--Parameters    :
--Date          :2002/02/19
--Authors       :TB
--Version       :1.0.0
--Mods          :29/06/02 - Added 'InterestControl' as mlngDefaultGLAccountID
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AC_Customer_List_Select
    (
    	@CompanyID int,
    	@Option varchar(20) = ''
    )

AS

SET NOCOUNT ON

	IF @Option = 'Account'
		SELECT
            AB_Accounts_ID AS [ID],
            [Description] 
		FROM AB_Accounts 
		WHERE AW_User_Companies_ID = @CompanyID AND
              NOT(AB_Accounts_ID = 1)
		ORDER BY [Description]

	ELSE
	IF @Option = 'Tax'
		SELECT
            Sys_AW_Tax_Codes_ID AS [ID],
            [Description],
            Tax_Rate AS [Tax] 
		FROM Sys_AW_Tax_Codes

    ELSE
    IF @Option = 'InterestControl'
        SELECT AB_Accounts_ID AS [ID]
        FROM AB_Control_Accounts
        WHERE Control_Number = 104

	ELSE
		SELECT 
			c.AC_Customers_ID AS [ID],
			c.Surname + ISNULL(', ' +  c.Firstnames,'') AS [Customer Name],
			ISNULL(t.Tax_Rate/100,0) as [Tax]
		FROM AC_Customers c
            LEFT JOIN Sys_AW_Tax_Codes t 
			    ON c.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
		WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer Name]

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











----------------------------------------------------------------------------
--Description   :sp_AC_Customer_Message_Info
--Purpose       :Retrieves ONE Customer for a company
--              :
--Parameters    :
--Date          :2004/01/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Customer_Message_Info
   (        
        @CompanyID int,
        @CustomerID int
    )

AS

SET NOCOUNT ON

-- SET @CompanyID = 1

	SELECT
        ISNULL(a.Surname, '') + ISNULL(', ' + a.FirstNames, '') AS [Customer],
        ISNULL(a.Principal_Name, '') AS [Principal],
        ISNULL(a.Principal_Firstname, '') AS [Firstname],
        ISNULL(a.Principal_Birthday, '') AS [Birthday],
        ISNULL(e.[Description], '') AS [PrinMethod],
        ISNULL(a.Work_Email, '') AS [Work Email],
        ISNULL(a.Principal_Cell_No, '') AS [PrinCell],
        a.AW_YesNo_Pre_Notify_ID AS [Pre Notify],
        a.AW_YesNo_Post_Notify_ID AS [Post Notify],
        ISNULL(b.[Description], '') AS [Credit Terms],
        ISNULL(b.Terms_Value, 0) AS [Terms Value],
        a.Sys_AC_Credit_Term_Types_ID AS [TermsTypeID],
        ISNULL(c.[Description], '') AS [Terms Type],
        a.Slu_AW_Controllers_ID AS [ControllerID],
        ISNULL(f.Surname, '') + ISNULL(', ' + f.FirstName, '') AS [Controller],
        ISNULL(f.User_Cell_Number, '') AS [ControllerCellNo],
        ISNULL(f.User_Email, '') AS [ControllerEmail],
        ISNULL(h.[Description], '') AS [ControllerMethod],
--         a.Slu_AW_Analysts_ID AS [AnalystID],
--         ISNULL(g.Surname, '') + ISNULL(', ' + g.FirstName, '') AS [Analyst],
--         ISNULL(g.User_Cell_Number, '') AS [AnalystCellNo],
--         ISNULL(g.User_Email, '') AS [AnalystEmail],
--         ISNULL(i.[Description], '') AS [AnalystMethod],
        ISNULL(a.Cell_No, '') AS [ContactCellNo],
        ISNULL(a.Contact_Name, '') AS [Contact],
        ISNULL(a.Home_Email, '') AS [Home Email],
        ISNULL(d.[Description], '') AS [Method],
        j.User_CRM_ID AS [CRMID],
        ISNULL(k.Surname, '') + ISNULL(', ' + k.FirstName, '') AS [CRM],
        ISNULL(k.User_Cell_Number, '') AS [CRMCellNo],
        ISNULL(k.User_Email, '') AS [CRMEmail],
        ISNULL(l.[Description], '') AS [CRMMethod]
    FROM AC_Customers a
        LEFT JOIN Slu_AW_Credit_Terms b
            ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Credit_Term_Types c
            ON c.Sys_AC_Credit_Term_Types_ID = a.Sys_AC_Credit_Term_Types_ID
        LEFT JOIN Sys_AW_Delivery_Methods d
            ON d.Sys_AW_Delivery_Methods_ID = a.Sys_AW_Delivery_Methods_ID
        LEFT JOIN Sys_AW_Delivery_Methods e
            ON e.Sys_AW_Delivery_Methods_ID = a.Principal_Contact_Method_ID
        LEFT JOIN AW_Users f
            ON f.AW_Users_ID = a.Slu_AW_Controllers_ID
--         LEFT JOIN AW_Users g
--             ON g.AW_Users_ID = a.Slu_AW_Analysts_ID
        LEFT JOIN Sys_AW_Delivery_Methods h
            ON h.Sys_AW_Delivery_Methods_ID = f.Sys_AW_Delivery_Methods_ID
--         LEFT JOIN Sys_AW_Delivery_Methods i
--             ON i.Sys_AW_Delivery_Methods_ID = g.Sys_AW_Delivery_Methods_ID
        LEFT JOIN AW_User_Companies j
            ON j.AW_User_Companies_ID = a.AW_User_Companies_ID
        LEFT JOIN AW_Users k
            ON k.AW_Users_ID = j.User_CRM_ID
        LEFT JOIN Sys_AW_Delivery_Methods l
            ON l.Sys_AW_Delivery_Methods_ID = k.Sys_AW_Delivery_Methods_ID
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.AC_Customers_ID = @CustomerID


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















----------------------------------------------------------------------------
--Description   :sp_AC_Customer_Message_Scan
--Purpose       :Retrieves ALL Customers for a company
--              :
--Parameters    :
--Date          :4 JAN 2004
--Authors       :TB
--MODS          :04/01/04 - Added @CreditTerms input parameter
--              :24/01/04 - Added [CustTypeID] column
--2004.3.4      :08/01/07 - Added [CustTypeID] column to ELSE (IF @CreditTerms <> 1)
--2004.4.0      :21/07/08 - Replaced Lup_AC_Account_Types_ID with Sys_AC_Account_Types_ID
--              :           caused by the switching of Account Types to the latter
--2004.4.1      :22/09/08 - Replaced Home_Email with Orders_URL (Accounts E-mail)
--2004.4.2      :20/12/08 - Added WHERE ISNULL(b.Terms_Value, 0) >= @CreditTerms
--2004.4.5      :27/05/09 - Added [SendEmail] field to EXCLUDE selected customers
----------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AC_Customer_Message_Scan
   (
        @CompanyID int,
        @CreditTerms tinyint
    )

AS

SET NOCOUNT ON

-- SET @CompanyID = 1

--     IF @CreditTerms = 1
--         BEGIN

        	SELECT
                a.AC_Customers_ID AS [CustomerID],
                a.Sys_AC_Account_Types_ID AS [CustTypeID],
                ISNULL(a.Surname, '') + ISNULL(', ' + a.FirstNames, '') AS [Customer],
                ISNULL(a.Principal_Name, '') AS [Principal],
                ISNULL(a.Principal_Firstname, '') AS [Firstname],
                ISNULL(a.Principal_Birthday, '') AS [Birthday],
                ISNULL(e.[Description], '') AS [PrinMethod],
                ISNULL(a.Work_Email, '') AS [Work Email],
                ISNULL(a.Orders_URL, '') AS [Work Email],
                ISNULL(a.Principal_Cell_No, '') AS [PrinCell],
                a.AW_YesNo_Pre_Notify_ID AS [Pre Notify],
                a.AW_YesNo_Post_Notify_ID AS [Post Notify],
                ISNULL(b.[Description], '') AS [Credit Terms],
                ISNULL(b.Terms_Value, 0) AS [Terms Value],
                a.Sys_AC_Credit_Term_Types_ID AS [TermsTypeID],
                ISNULL(c.[Description], '') AS [Terms Type],
                a.Slu_AW_Controllers_ID AS [ControllerID],
                ISNULL(f.Surname, '') + ISNULL(', ' + f.FirstName, '') AS [Controller],
                ISNULL(f.User_Cell_Number, '') AS [ControllerCellNo],
                ISNULL(f.User_Email, '') AS [ControllerEmail],
                ISNULL(h.[Description], '') AS [ControllerMethod],
                ISNULL(a.Cell_No, '') AS [ContactCellNo],
                ISNULL(a.Contact_Name, '') AS [Contact],
--                ISNULL(a.Home_Email, '') AS [Home Email],
                ISNULL(a.Orders_URL, '') AS [Home Email],
                ISNULL(d.[Description], '') AS [Method],
                j.User_CRM_ID AS [CRMID],
                ISNULL(k.Surname, '') + ISNULL(', ' + k.FirstName, '') AS [CRM],
                ISNULL(k.User_Cell_Number, '') AS [CRMCellNo],
                ISNULL(k.User_Email, '') AS [CRMEmail],
                ISNULL(l.[Description], '') AS [CRMMethod],
                a.AW_YesNo_Send_Email_ID AS [SendEmail],
                ISNULL(
                        (
                            SELECT TOP 1 UPPER(LEFT(RTRIM(LTRIM(y.Description)), 1))
                            FROM AC_History_Ratings x
                               INNER JOIN Slu_AC_Ratings y
                                   ON y.Slu_AC_Ratings_ID = x.Slu_AC_Ratings_ID
                            WHERE x.AC_Customers_ID = a.AC_Customers_ID AND
                                  x.AW_User_Companies_ID = @CompanyID AND
                                  x.Slu_AW_Active_ID = 1
                            ORDER BY x.Effective_date DESC
                        ), '') AS [Rating],
                ISNULL(
                        (
                            SELECT TOP 1 x.Effective_Date
                            FROM AC_History_Ratings x
                            WHERE x.AC_Customers_ID = a.AC_Customers_ID AND
                                  x.AW_User_Companies_ID = @CompanyID AND
                                  x.Slu_AW_Active_ID = 1
                            ORDER BY x.Effective_date DESC
                        ), '') AS [LastRatingDate],
                ISNULL(
                        (
                            SELECT TOP 1 v.Statement_Date
                            FROM AC_History_Balance_Sheets v
                            WHERE v.AC_Customers_ID = a.AC_Customers_ID AND
                                  v.AW_User_Companies_ID = @CompanyID AND
                                  v.Slu_AW_Active_ID = 1
                            ORDER BY v.Statement_Date DESC
                        ), '') AS [LastBalanceSheetDate],
                ISNULL(
                        (
                            SELECT TOP 1 w.Date_Changed
                            FROM AC_History_Credit_Limits w
                            WHERE w.AC_Customers_ID = a.AC_Customers_ID AND
                                  w.AW_User_Companies_ID = @CompanyID AND
                                  w.Slu_AW_Active_ID = 1
                            ORDER BY w.Date_Changed DESC
                        ), '') AS [LastCreditLimitDate]
        
            FROM AC_Customers a
                LEFT JOIN Slu_AW_Credit_Terms b
                    ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
                LEFT JOIN Sys_AC_Credit_Term_Types c
                    ON c.Sys_AC_Credit_Term_Types_ID = a.Sys_AC_Credit_Term_Types_ID
                LEFT JOIN Sys_AW_Delivery_Methods d
                    ON d.Sys_AW_Delivery_Methods_ID = a.Sys_AW_Delivery_Methods_ID
                LEFT JOIN Sys_AW_Delivery_Methods e
                    ON e.Sys_AW_Delivery_Methods_ID = a.Principal_Contact_Method_ID
                LEFT JOIN AW_Users f
                    ON f.AW_Users_ID = a.Slu_AW_Controllers_ID
                LEFT JOIN Sys_AW_Delivery_Methods h
                    ON h.Sys_AW_Delivery_Methods_ID = f.Sys_AW_Delivery_Methods_ID
                LEFT JOIN AW_User_Companies j
                    ON j.AW_User_Companies_ID = a.AW_User_Companies_ID
                LEFT JOIN AW_Users k
                    ON k.AW_Users_ID = j.User_CRM_ID
                LEFT JOIN Sys_AW_Delivery_Methods l
                    ON l.Sys_AW_Delivery_Methods_ID = k.Sys_AW_Delivery_Methods_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
                  a.Slu_AW_Credit_Terms_ID >= @CreditTerms
            ORDER BY Customer



SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Payments_PickList
--Purpose       :Customer Payments Picklist
--Functionality :Selects ONLY Customers with Outstanding Transactions
--Parameters    :
--Date          :2009/02/07
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE        Procedure sp_AC_Customer_Payments_PickList
    (
    	@CompanyID int,
        @Option tinyint
    )

AS

SET NOCOUNT ON


	SELECT AC_Customers_ID AS [ID], 
           ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
           ISNULL(Customer_Number, '') AS [No] 
	FROM AC_Customers
	WHERE AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AC_Customer_Has_Outstanding_Transactions(AC_Customers_ID, @Option) = 1
 	ORDER BY [Name]



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--This is for the customer statements
--2001/10/09
CREATE   PROCEDURE sp_AC_Customer_Statement_Ageing_Values
	(
        @PeriodProcedureID int,
        @CustomerID int,
        @Now DateTime,
        @D1 DateTime,
        @D2 DateTime,
        @D3 DateTime,
        @D4 DateTime,
        @D5 DateTime,
        @D6 DateTime,
        @D7 DateTime
	)

AS
	SELECT *
    FROM dbo.fn_AC_Customer_Statements_Ageing_Values
        (
            @PeriodProcedureID,
            @CustomerID,
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7
        )







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Statement_Now
--Purpose       :E-Mail Customer Statement now
--Functionality :Uses TABLE datatype
--Date          :2006/03/11
--Authors       :TB
--MODS          :
--2004.3.8      :11/02/08 - Added [OrderNo], [OrderNotes] and [CreditTerms] fields
--              :           to sync with sp_RPT_AC_Customer_Statements and added
--              :           JOINS to extract [CreditTerms]
--2004.4.2      :01/11/08 - Modified WHERE clause to include CURRENT MONTH transactions
--              :           that have ZERO owing from LAST MONTH-END to @DatePicked
--              :02/11/08 - Added insert validation if Customer @HasBalance or zero balance
--              :           with non-zero ageing
------------------------------------------------------------------------------


CREATE              PROCEDURE sp_AC_Customer_Statement_Now
	(
        @CustomerID int, 
        @CompanyID int
	)

AS

SET NOCOUNT ON

	DECLARE
        @DatePicked DateTime, 
        @LastPeriodProcedureDate DateTime,
        @PeriodProcedureID int,
        @CustomerName varchar(90),
        @CustomerNumber varchar(10),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @WorkEmail varchar(40),
        @AccountBalance money,
        @StatementID int,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @UserID int,
        @HasBalance tinyint


--  Returns midnite tonight
    SET @DatePicked = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, getdate()), 0, 1)))
    SET @PeriodProcedureID = 0
    SET @HasBalance = 0

--------------------------
--     SET @CustomerID = 864
--     SET @CompanyID = 1
--     SET @UserID = 2
--------------------------

------------------------------------------------------------------------------
--> Source from: sp_AC_Customer_Statements_Temp_Insert
------------------------------------------------------------------------------

    DECLARE @AC_Statement_Details_Temp table
                (
                	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
                	[AC_Statements_Temp_ID] [int] NULL ,
                	[Transaction_Date] [datetime] NULL ,
                	[Sys_AW_Transaction_Types_ID] [int] NULL ,
                	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Amount] [money] DEFAULT 0 NULL ,
                	[Payment] [money] DEFAULT 0 NULL ,
                	[Date_Captured] [datetime] DEFAULT getdate() NULL ,
                	[User_ID] [int] DEFAULT 1 NULL ,
                	[AW_User_Companies_ID] [int] DEFAULT 1 NOT NULL 
                )

    DECLARE @AC_Statements_Temp table
                (
                	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
                	[AW_Period_Procedures_ID] [int] NULL ,
                	[AC_Customers_ID] [int] NULL ,
                	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                	[Amount] [money] DEFAULT 0 NULL ,
                	[Payment] [money] DEFAULT 0 NULL ,
                	[Account_Balance] [money] DEFAULT 0 NULL ,
                	[Current] [money] DEFAULT 0 NULL ,
                	[30Days] [money] DEFAULT 0 NULL ,
                	[60Days] [money] DEFAULT 0 NULL ,
                	[90Days] [money] DEFAULT 0 NULL ,
                	[120Days] [money] DEFAULT 0 NULL ,
                	[150Days] [money] DEFAULT 0 NULL ,
                	[180+Days] [money] DEFAULT 0 NULL ,
                	[Date_Captured] [datetime] DEFAULT getdate() NULL ,
                	[User_ID] [int] DEFAULT 1 NULL ,
                	[AW_User_Companies_ID] [int] DEFAULT 1 NOT NULL
                )

--> Step 1: Get the date of the LAST Month-End done
	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date 
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
	ORDER BY Month_End_Date DESC

--> Step 2: Initialize M/E date if this is the FIRST Month-End procedure
	IF @LastPeriodProcedureDate IS NULL 
		SET @LastPeriodProcedureDate = '1900/01/01'

--> Step 3: Get the last 7 Month-End dates to insert ageing for each Account
    EXEC sp_AW_Period_Procedures_Select
            @DatePicked,
            @D1 OUTPUT,
            @D2 OUTPUT,
            @D3 OUTPUT,
            @D4 OUTPUT,
            @D5 OUTPUT,
            @D6 OUTPUT,
            @D7 OUTPUT,
            1,
            @CompanyID

--> Step 4: Get the Customer info
    SELECT @CustomerName = ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''),
           @PostBox = ISNULL(c.Post_Box, ''),
           @PostOffice = ISNULL(c.Post_Office, ''),
           @PostCode = ISNULL(c.Post_Code, ''),
           @WorkEmail = ISNULL(c.Work_Email, ''),
           @CustomerNumber = ISNULL(c.Customer_Number, '')
    FROM AC_Customers c
    WHERE c.AW_User_Companies_ID = @CompanyID AND
          c.AC_Customers_ID = @CustomerID


--> Clear the Ageing Balances Customer
    SET @AgePayment = 0
    SET @AgeAmount = 0
    SET @AgeCurrent = 0
    SET @Age30Days = 0
    SET @Age60Days = 0
    SET @Age90Days = 0
    SET @Age120Days = 0
    SET @Age150Days = 0
    SET @Age180Days = 0


	SELECT
        @AgePayment = Payment,
        @AgeAmount = Amount,
        @AgeCurrent = [Current],
        @Age30Days = [30 Days],
        @Age60Days = [60 Days],
        @Age90Days = [90 Days],
        @Age120Days = [120 Days],
        @Age150Days = [150 Days],
        @Age180Days = [180+ Days]
	FROM dbo.fn_AC_Customer_Ageing_Values
        (
            @CustomerID,
            @DatePicked,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7
        )

    SET @AccountBalance = @AgeCurrent + 
                          @Age30Days + 
                          @Age60Days + 
                          @Age90Days + 
                          @Age120Days + 
                          @Age150Days + 
                          @Age180Days

    --> 2004.4.2
    SET @HasBalance = 0

    IF @AccountBalance <> 0
        BEGIN
            SET @HasBalance = 1
        END

    IF @HasBalance = 0
        BEGIN
            IF @AgeCurrent <> 0 OR
                @Age30Days <> 0 OR
                @Age60Days <> 0 OR
                @Age90Days <> 0 OR
                @Age120Days <> 0 OR
                @Age150Days <> 0 OR
                @Age180Days <> 0
                BEGIN
                    SET @HasBalance = 1
                END
        END

    IF @HasBalance = 1
        BEGIN
    		INSERT INTO @AC_Statements_Temp
    			(
                    AW_Period_Procedures_ID,
                    AC_Customers_ID,
                    FullName,
                    Customer_Number,
                    Post_Address,
                    Post_Office,
                    Post_Code,
                    Work_Email,
                    [User_ID],
                    AW_User_Companies_ID,
                    Amount,
                    Payment,
                    Account_Balance,
                    [Current],
                    [30Days],
                    [60Days],
                    [90Days],
                    [120Days],
                    [150Days],
                    [180+Days]
                )
    		VALUES
    			(
                    @PeriodProcedureID,    --initialized to 0 ??
                    @CustomerID,
                    rtrim(ltrim(@CustomerName)),
                    @CustomerNumber,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @UserID,
                    @CompanyID,
                    @AgeAmount,
                    @AgePayment,
                    @AccountBalance,
                    @AgeCurrent,
                    @Age30Days,
                    @Age60Days,
                    @Age90Days,
                    @Age120Days,
                    @Age150Days,
                    @Age180Days
                )

    	  	SELECT @StatementID = Scope_Identity()

    		--Insert Transactions since LAST Period Procedure Date
    		INSERT INTO @AC_Statement_Details_Temp
    			(
                    AC_Statements_Temp_ID,
                    Transaction_Date,
                    Sys_AW_Transaction_Types_ID,
                    Transaction_Number,
                    Amount,
                    Payment,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
            SELECT 
                    @StatementID,
                    Transaction_Date,
                    Sys_AW_Transaction_Types_ID,
                    Transaction_Number,
                    Total_Amount,
                    Payment_Amount,
                    getdate(),
                    [User_ID],
                    AW_User_Companies_ID
                    
            FROM AS_Transactions
--             WHERE AC_Customers_ID = @CustomerID AND
--                   ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
--                   DATEDIFF(d, Transaction_Date, @DatePicked) >= 0 AND
--                  (Sys_AW_Transaction_Types_ID = 3 OR
--                   Sys_AW_Transaction_Types_ID = 4 OR
--                   Sys_AW_Transaction_Types_ID = 5 OR
--                   Sys_AW_Transaction_Types_ID = 7 OR
--                   Sys_AW_Transaction_Types_ID = 15 OR
--                   Sys_AW_Transaction_Types_ID = 18 OR
--                   Sys_AW_Transaction_Types_ID = 21 OR
--                   Sys_AW_Transaction_Types_ID = 22)
    
            --> Show ALL TRANSACTIONS NON-ZERO owing
            WHERE (AC_Customers_ID = @CustomerID AND
                  (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                   DATEDIFF(d, Transaction_Date, @DatePicked) >= 0)) AND
                 (Sys_AW_Transaction_Types_ID = 3 OR
                  Sys_AW_Transaction_Types_ID = 4 OR
                  Sys_AW_Transaction_Types_ID = 5 OR
                  Sys_AW_Transaction_Types_ID = 7 OR
                  Sys_AW_Transaction_Types_ID = 15 OR
                  Sys_AW_Transaction_Types_ID = 18 OR
                  Sys_AW_Transaction_Types_ID = 21 OR
                  Sys_AW_Transaction_Types_ID = 22) OR
    
            --> Show CURRENT MONTH transactions that have ZERO owing
            --       from LAST MONTH-END to @DatePicked
                 (AC_Customers_ID = @CustomerID AND
                 (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) = 0 AND
                  Transaction_Date > @D1 AND
                  DATEDIFF(d, Transaction_Date, @DatePicked) >= 0)) AND
                 (Sys_AW_Transaction_Types_ID = 3 OR
                  Sys_AW_Transaction_Types_ID = 4 OR
                  Sys_AW_Transaction_Types_ID = 5 OR
                  Sys_AW_Transaction_Types_ID = 7 OR
                  Sys_AW_Transaction_Types_ID = 15 OR
                  Sys_AW_Transaction_Types_ID = 18 OR
                  Sys_AW_Transaction_Types_ID = 21 OR
                  Sys_AW_Transaction_Types_ID = 22)

        END
    --> 2004.4.2


------------------------------------------------------------------------------
--> Source from: sp_RPT_AC_Customer_Statements_Temp
------------------------------------------------------------------------------

    SELECT 
        CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
        tt.[Description] AS Type, 
        RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
        ISNULL(d.Amount, 0) AS [Amount], 
        ISNULL(d.Payment, 0) AS [Payment], 
        ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
        t.AC_Customers_ID AS [CustomerID], 
        t.FullName AS [Customer],
		ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
        t.Post_Address AS [CustomerPostAddress],
        t.Post_Office AS [CustomerPostOffice],
        t.Post_Code AS [CustomerPostCode],
        ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
        t.Work_Email AS [CustomerEmail],
        t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
        t.[Current],
        t.[30Days],
        t.[60Days],
        t.[90Days],
        (ISNULL(t.[120Days], 0) +
         ISNULL(t.[150Days], 0) +
         ISNULL(t.[180+Days], 0)) AS [120+Days],
        RTRIM(LTRIM(z.Comment)) AS [Notes],
        RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
        RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
    FROM @AC_Statements_Temp t 
        JOIN @AC_Statement_Details_Temp d
            ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
        INNER JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
        LEFT OUTER JOIN Sys_AW_Transaction_Types tt
            ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AS_Transactions z
            ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
               z.Transaction_Date = d.Transaction_Date AND
               z.Transaction_Number = d.Transaction_Number
    WHERE t.AW_Period_Procedures_ID = @PeriodProcedureID             --AND
--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
    ORDER BY t.FullName, [CustomerNo], TransactionDate

------------------------------------------------------------------------------


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   : sp_AC_Customer_Statements
--Purpose       : Retrieves Customer Statement data
--              :
--Parameters    :
--Date          : 2002/03/04
--Authors       : TB
--Version       : 1.0.0
--MODS          :03/11/02 - Removed Sys_AW_Period_Procedure_Types_ID validation
--              :                from @Choice = 1 (Period Procedure PICKLIST)
------------------------------------------------------------------------------
--------------------------------------------------------------
-- NB NB NB 03/11/02  *** @Choice = 1 NO LONGER USED BY PP ***
--------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Customer_Statements
	(
		@Choice int,
		@CompanyID int,
		@PeriodProcedureID int = NULL,
		@CustomerName varchar(50)  = ''
	)
AS

SET NOCOUNT ON


	IF @Choice = 1    --Period Procedure PICKLIST data
--------------------------------------------------
-- NB NB NB 03/11/02  *** NO LONGER USED BY PP ***
--------------------------------------------------
		SELECT
            AW_Period_Procedures_ID as [ID],
            [Description],
            [Month_End_Date],
            [Month],
            [Year] 
		FROM AW_Period_Procedures
-- 		WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
--               AW_User_Companies_ID = @CompanyID

		WHERE AW_User_Companies_ID = @CompanyID
		ORDER BY Month_End_Date DESC

	ELSE
	IF @Choice = 2
		BEGIN
			--DECLARE @Now DateTime, @D1 DateTime, @D2 DateTime, @D3 DateTime, @D4 DataTime, @D5 DateTime, @D6 DataTime, @D7 DateTime

			IF @CustomerName = ''
                SELECT     
                    csc.AC_Customers_ID AS CustomerID, 
                    csc.FullName AS [Full Name], 
                    csc.Post_Address AS [Post Address], 
                    csc.Post_Office AS [Post Office], 
                    csc.Post_Code AS [Post Code], 
                    csc.Work_Email AS [E-mail], 
                    csc.[Current] as [Current],
                    csc.[30Days] as [30 Days],
                    csc.[60Days] as [60 Days],
                    csc.[90Days] as [90 Days],
                   (csc.[120Days] + csc.[150Days] + csc.[180+Days]) as [120+ Days],
                   (csc.Payment + csc.Amount) as CustomerTotal,				
                    cst.Transaction_Date AS [Date], 
                    tt.[Description] AS [Transaction Type], 
                    cst.Transaction_Number AS [No], 
                    cst.Amount AS Amount, 
                    cst.Payment AS Payment, 
                    cst.Payment + cst.Amount as Total,
                    csc.AW_Period_Procedures_ID AS PeriodProcedureID, 
                    csc.AW_User_Companies_ID AS CompanyID
                FROM AC_Statements csc 
                    INNER JOIN AC_Statement_Details cst
                        ON csc.AC_Statements_ID = cst.AC_Statements_ID 
                    INNER JOIN Sys_AW_Transaction_Types tt
                        ON cst.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                WHERE csc.AW_Period_Procedures_ID = @PeriodProcedureID AND 
                		 csc.AW_User_Companies_ID = @CompanyID

			ELSE
				SELECT     
                    csc.AC_Customers_ID AS CustomerID, 
                    csc.FullName AS [Full Name], 
                    csc.Post_Address AS [Post Address], 
                    csc.Post_Office AS [Post Office], 
                    csc.Post_Code AS [Post Code], 
                    csc.Work_Email AS [E-mail], 
                    cst.Transaction_Date AS Date, 
                    tt.[Description] AS [Transaction Type], 
                    cst.Transaction_Number AS No, 
                    cst.Amount AS Amount, 
                    cst.Payment AS Payment, 
                    csc.AW_Period_Procedures_ID AS PeriodProcedureID, 
                    csc.AW_User_Companies_ID AS CompanyID
				FROM 
					AC_Statements csc 
						INNER JOIN AC_Statement_Details cst
                            ON csc.AC_Statements_ID = cst.AC_Statements_ID 
						INNER JOIN Sys_AW_Transaction_Types tt
                            ON cst.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				WHERE csc.AW_Period_Procedures_ID =@PeriodProcedureID AND 
                      csc.AW_User_Companies_ID = @CompanyID AND
                      csc.fullname Like '%' + @CustomerName + '%'

		END


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--IS THIS SP USED ANYWHERE ????????????????


CREATE   PROCEDURE sp_AC_Customer_Statements_Ageing_Select_All
	(@PeriodProcedureID int)
AS
SET NOCOUNT ON

	SELECT 
		AC_Customers_ID, 
		FullName as Customer, 
		(Amount  + Payment) as Amount, 
		[Current] as [Current], 
		[30Days] as [30 Days], 
		[60Days] as [60 Days], 
		[90Days] as [90 Days], 
		([120Days] + [150Days] + [180+Days]) as [120+ Days]
	FROM AC_Customer_Statements_Customers
	WHERE AW_Period_Procedures_ID = @PeriodProcedureID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Statements_Customers_Insert
--Purpose       :Saves a snapshot of Account Customer Transactions up to
--              :    the month-end Period Procedure date @ProcedureDate
--Functionality :ONLY Customers that have transactions OWING are selected
--Calls         :fn_AC_Customer_Period_Procedure_Ageing_Values
--Parameters    :
--Date          :2002/03/24
--Authors       :TB
--MODS          :10/07/02 - Remove AC_Customer.Account_Balance field and
--              :           replaced with @AccountBalance = SUM(Ageing_Balances)
--              :07/08/02 - Clear the Ageing Balances BEFORE NEXT FETCH
--              :16/08/02 - Added Sys_AW_Transaction_Types_ID = 21 & 22 from
--              :               21=Back Office Receipt, 22=EFT Receipt
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :31/12/02 - Added Return Code @ReturnCode to validate success
--              :22/01/03 - Added Stock Valuation into NEW Stock_Valuation field
--              :           and insert a STOCK VALUATION at CUSTOMER Month-End
--              :22/01/03 - Added BEGIN TRANSACTION to procedure
--              :15/09/03 - Added @CompanyID in WHERE clause of Customer_Cursor
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--2004.2.9      :14/05/06 - Changed Stock Valuation to use SysOptions setting
--2004.3.2      :13/09/06 - Added update Date_Captured as @Date in AC_Statements
--              :           and AC_Statement_Details
--              :15/09/06 - Rename @Date to @ProcedureDate and replace @Now with
--              :           @ProcedureDate
--              :19/09/06 - Added @ProcedureDate input parameter to in Stock Valuation
--              :           sp_AP_Products_History_Insert. Required for Enterprise
--              :           Stock Valuation
--              :30/09/06 - Replaced fn_AC_Customer_Ageing_Values with Customer Period
--              :           Procedure-specific fn_AC_Customer_Period_Procedure_Ageing_Values
--              :30/09/06 - Changed conditions for INSERT into AC_Statement_Details
--              :           to select only transaction where REMAINING BALANCE <> 0
--              :           and Transaction_Date <= @ProcedureDate
--2004.3.4      :08/03/07 - Removed fetching @LastPeriodProcedureDate - Not used
--2004.4.2      :25/10/08 - Added new Standard Cost Inventory Valuation method
--              :01/11/08 - Modified WHERE clause to include CURRENT MONTH transactions
--              :           that have ZERO owing from LAST MONTH-END to @ProcedureDate
--              :02/11/08 - Added insert validation if Customer @HasBalance or zero balance
--              :           with non-zero ageing
--              :27/11/08 - Added ISNULL validation on all ageing fields
--2004.5.2      :02/07/11 - Add and insert NEW AS_Transactions_ID in AC_Statement_Details
--V6.2	RL	2016-03-30 - Moved Filter to cursor select for speed performance
--V6.2	RL	2016-03-30 - Removed balance <> 0 check. This prevented paid up accounts from displaying for the current month
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Customer_Statements_Customers_Insert]
	(
        @MonthID int,
        @YearID int,
        @ProcedureDate DateTime, 
        @Description varchar(50),
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @PeriodProcedureID int,
            @CustomerID int,
            @CustomerName varchar(90),
            @CustomerNumber varchar(10),
            @PostBox varchar(20),
            @PostOffice varchar(30),
            @PostCode varchar(10),
            @WorkEmail varchar(40),
            @AccountBalance money,
            @StatementID int,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime,
            @AgePayment money,
            @AgeAmount money,
            @AgeCurrent money,
            @Age30Days money,
            @Age60Days money,
            @Age90Days money,
            @Age120Days money,
            @Age150Days money,
            @Age180Days money,
            @StockValuation money,
            @ValuationMethod smallint,
            @ReturnCode int,
            @HasBalance tinyint


    SET @PeriodProcedureID = 0
    SET @ReturnCode = 0            --0 = Unsuccessful
    SET @HasBalance = 0


    BEGIN TRANSACTION

    --> Stock Valuation (theoretical now)
        SELECT @ValuationMethod = ISNULL(Control_Index, 0)
        FROM Sys_AW_Options
        WHERE Control_Type = 'OptionButton' AND
              Control_Name = 'optInventoryValuation' AND
              Control_Value = 'True' AND
              AW_User_Companies_ID = @CompanyID


        IF @ValuationMethod = 0
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Average_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
    
            END
        ELSE
        IF @ValuationMethod = 1
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Last_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END
        ELSE
        IF @ValuationMethod = 2
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Standard_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END


    --> Step 2: Insert a Period Procedure record and get its ID
    	INSERT AW_Period_Procedures
            (
                Sys_AW_Period_Procedure_Types_ID,
                [Description],
                [Month],
                [Year],
                Month_End_Date,
                Stock_Valuation,
                [User_ID],
                AW_User_Companies_ID
            )
    	VALUES
            (
                1,    -- 1 = Customers Month-End
                @Description,
                @MonthID,
                @YearID,
                @ProcedureDate,
                @StockValuation,                @UserID,
                @CompanyID
            )
    
    	SELECT @PeriodProcedureID = Scope_Identity()


    --> INSERT a STOCK VALUATION
        -----------------------------------------
        EXEC sp_AP_Products_History_Insert 2, @Description, @UserID, @CompanyID, @ProcedureDate


    --> Step 3: Get the last 7 Month-End dates to insert ageing for each Account
        EXEC sp_AW_Period_Procedures_Select
                @ProcedureDate,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT,
                1,
                @CompanyID
 
 --Select @D1 As '@D1'
    
    --> Step 4: Define a CURSOR for AC_Customers
    	DECLARE Customer_Cursor CURSOR FOR
            (
                SELECT DISTINCT
                    c.AC_Customers_ID,
                    ISNULL(c.Surname, '') +
                    ISNULL(', ' + c.FirstNames, '') AS [FullName],
                    ISNULL(c.Post_Box, ''),
                    ISNULL(c.Post_Office, ''),
                    ISNULL(c.Post_Code, ''),
                    ISNULL(c.Work_Email, ''),
                    ISNULL(c.Customer_Number, '')
				--V6.3 Added filter here to improve speed	
                --> Show ALL TRANSACTIONS NON-ZERO owing
                 FROM AC_Customers c
                    INNER JOIN AS_Transactions t
                        ON c.AC_Customers_ID = t.AC_Customers_ID
                 WHERE c.AW_User_Companies_ID = @CompanyID AND
					(
						Sys_AW_Transaction_Types_ID = 3 OR
						Sys_AW_Transaction_Types_ID = 4 OR
						Sys_AW_Transaction_Types_ID = 5 OR
						Sys_AW_Transaction_Types_ID = 7 OR
						Sys_AW_Transaction_Types_ID = 15 OR
						Sys_AW_Transaction_Types_ID = 18 OR
						Sys_AW_Transaction_Types_ID = 21 OR
						Sys_AW_Transaction_Types_ID = 22
					 ) AND
                     (
						ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 OR
						t.Transaction_Date Between @D1 AND @ProcedureDate		--All new transactions
					  )
                
            )
    
    	OPEN Customer_Cursor
    
        	FETCH NEXT FROM Customer_Cursor 
        	INTO
                @CustomerID,
                @CustomerName,
                @PostBox,
                @PostOffice,
                @PostCode,
                @WorkEmail,
                @CustomerNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
--        		FROM dbo.fn_AC_Customer_Ageing_Values
                FROM dbo.fn_AC_Customer_Period_Procedure_Ageing_Values
                    (
                        @CustomerID,
                        @ProcedureDate,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = ISNULL(@AgeCurrent, 0) + 
                                      ISNULL(@Age30Days, 0) + 
                                      ISNULL(@Age60Days, 0) + 
                                      ISNULL(@Age90Days, 0) + 
                                      ISNULL(@Age120Days, 0) + 
                                      ISNULL(@Age150Days, 0) + 
                                      ISNULL(@Age180Days, 0)

                --> 2004.4.2
                SET @HasBalance = 0
                
                --V6.2 Already did filtering in cursor select
                --If you check for balance here you will miss paid up accounts for this month
                SET @HasBalance = 1

                --IF @AccountBalance <> 0
                --    BEGIN
                --        SET @HasBalance = 1
                --    END

                --IF @HasBalance = 0
                --    BEGIN
                --        IF ISNULL(@AgeCurrent, 0) <> 0 OR
                --            ISNULL(@Age30Days, 0) <> 0 OR
                --            ISNULL(@Age60Days, 0) <> 0 OR
                --            ISNULL(@Age90Days, 0) <> 0 OR
                --            ISNULL(@Age120Days, 0) <> 0 OR
                --            ISNULL(@Age150Days, 0) <> 0 OR
                --            ISNULL(@Age180Days, 0) <> 0
                --            BEGIN
                --                SET @HasBalance = 1
                --            END
                --    END

                IF @HasBalance = 1
                    BEGIN
                		INSERT INTO AC_Statements
                			(
                                AW_Period_Procedures_ID,
                                AC_Customers_ID,
                                FullName,
                                Customer_Number,
                                Post_Address,
                                Post_Office,
                                Post_Code,
                                Work_Email,
                                [User_ID],
                                AW_User_Companies_ID,
                                Amount,
                                Payment,
                                Account_Balance,
                                [Current],
                                [30Days],
                                [60Days],
                                [90Days],
                                [120Days],
                                [150Days],
                                [180+Days],
                                Date_Captured
                            )
                		VALUES
                			(
                                @PeriodProcedureID,
                                @CustomerID,
                                rtrim(ltrim(@CustomerName)),
                                @CustomerNumber,
                                @PostBox,
                                @PostOffice,
                                @PostCode,
                                @WorkEmail,
                                @UserID,
                                @CompanyID,
                                ISNULL(@AgeAmount, 0),
                                ISNULL(@AgePayment, 0),
                                ISNULL(@AccountBalance, 0),
                                ISNULL(@AgeCurrent, 0),
                                ISNULL(@Age30Days, 0),
                                ISNULL(@Age60Days, 0),
                                ISNULL(@Age90Days, 0),
                                ISNULL(@Age120Days, 0),
                                ISNULL(@Age150Days, 0),
                                ISNULL(@Age180Days, 0),
                                @ProcedureDate
                            )
            
                	  	SELECT @StatementID = Scope_Identity()
                
                		--Insert Transactions from LAST Period Procedure Date
                		INSERT INTO AC_Statement_Details
                			(
                                AC_Statements_ID,
                                Transaction_Date,
                                AS_Transactions_ID,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                [User_ID],
                                AW_User_Companies_ID,
                                Date_Captured
                            )
                        SELECT 
                                @StatementID,
                                t.Transaction_Date,
                                t.AS_Transactions_ID,
                                t.Sys_AW_Transaction_Types_ID,
                                t.Transaction_Number,
                                t.Total_Amount,
                                t.Payment_Amount,
                                t.[User_ID],
                                t.AW_User_Companies_ID,
                                @ProcedureDate
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AS_Transactions t
						 WHERE 
							t.AC_Customers_ID = @CustomerID AND
							t.AW_User_Companies_ID = @CompanyID AND 
							(
								Sys_AW_Transaction_Types_ID = 3 OR
								Sys_AW_Transaction_Types_ID = 4 OR
								Sys_AW_Transaction_Types_ID = 5 OR
								Sys_AW_Transaction_Types_ID = 7 OR
								Sys_AW_Transaction_Types_ID = 15 OR
								Sys_AW_Transaction_Types_ID = 18 OR
								Sys_AW_Transaction_Types_ID = 21 OR
								Sys_AW_Transaction_Types_ID = 22
							 ) AND
							 (
								ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 OR
								t.Transaction_Date Between @D1 AND @ProcedureDate 	--All new transactions
							  )							
	               END
            --> 2004.4.2


            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Customer_Cursor 
            	INTO
                    @CustomerID,
                    @CustomerName,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @CustomerNumber
    
        	END
    	
    	CLOSE Customer_Cursor
    
    	DEALLOCATE Customer_Cursor


        SET @ReturnCode = 1


    COMMIT TRANSACTION


SET NOCOUNT OFF


RETURN @ReturnCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Statements_Temp_Insert
--Purpose       :Saves an Ad-Hoc snapshot of Account Customer Transactions
--              :between month-end Period Procedures 
--Functionality :ONLY Customers that have had transactions are selected
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Version       :1.0.0
--MODS          :07/08/02 - Clear the Ageing Balances BEFORE NEXT FETCH
--              :09/08/02 - Replaced @Now with (renamed @Date to @DatePicked)
--              :16/08/02 - Added Sys_AW_Transaction_Types_ID = 21 & 22 from
--              :               21=Back Office Receipt, 22=EFT Receipt
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :27/01/03 - Modified @DatePicked to reflect date and ending time
--              :           as at 12 midnight of the date of @DatePicked
--              :15/09/03 - Added @CompanyID in WHERE clause of Customer_Cursor
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--2004.3.2      :13/09/06 - Added update Date_Captured as @Date in AC_Statements_Temp
--              :           and AC_Statement_Details_Temp
--2004.4.2      :01/11/08 - Modified WHERE clause to include CURRENT MONTH transactions
--              :           that have ZERO owing from LAST MONTH-END to @DatePicked
--              :02/11/08 - Added insert validation if Customer @HasBalance or zero balance
--              :           with non-zero ageing
--V6.2	RL	2016-03-30 - Moved Filter to cursor select for speed performance
--V6.2	RL	2016-03-30 - Removed balance <> 0 check. This prevented paid up accounts from displaying for the current month
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Customer_Statements_Temp_Insert]
	(
        @DatePicked			DateTime,
		@CustomerID_Single	int,
		@ShowZeroBalance	int, 
        @CompanyID			int,
        @UserID				int
	)

AS

SET NOCOUNT ON

	DECLARE
        @LastPeriodProcedureDate DateTime,
        @PeriodProcedureID int,
        @CustomerID int,
        @CustomerName varchar(90),
        @CustomerNumber varchar(10),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @WorkEmail varchar(40),
        @AccountBalance money,
        @StatementID int,
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @HasBalance tinyint,
		@ZeroBalance money

--	SET @DatePicked = getdate()  --REMOVE THIS: Selected in Statement Print datepicker

--	SET @Now = @DatePicked

--> (27/01/03) Truncates the decimal of today's date e.g.
--        '2002-09-24 13:33:45.076' as '2002-09-24 00:00:00.000',
--        and adds 1 day which equals midnite tonight
--        which returns '2002-09-25 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @DatePicked), 0, 1)))

    SET @DatePicked = @Now

    SET @PeriodProcedureID = 0
    SET @HasBalance = 0

--------------------------
-- 	SET @CompanyID = 1
-- 	SET @UserID = 2
--------------------------

--Wipe the TEMP table-------
    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Statement_Details_Temp]
        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Statements_Temp]
        
        CREATE TABLE [dbo].[AC_Statement_Details_Temp] (
        	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AC_Statements_Temp_ID] [int] NULL ,
        	[Transaction_Date] [datetime] NULL ,
        	[Sys_AW_Transaction_Types_ID] [int] NULL ,
        	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL 
        ) ON [PRIMARY]
        
        CREATE TABLE [dbo].[AC_Statements_Temp] (
        	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AW_Period_Procedures_ID] [int] NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Account_Balance] [money] NULL ,
        	[Current] [money] NULL ,
        	[30Days] [money] NULL ,
        	[60Days] [money] NULL ,
        	[90Days] [money] NULL ,
        	[120Days] [money] NULL ,
        	[150Days] [money] NULL ,
        	[180+Days] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL 
        ) ON [PRIMARY]
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Amount]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details_Temp].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details_Temp].[Date_Captured]'

        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Payment]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details_Temp].[User_ID]'
        
        setuser
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[120Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[150Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[180+Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[30Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[60Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[90Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Account_Balance]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Amount]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements_Temp].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Current]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements_Temp].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Payment]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements_Temp].[User_ID]'

        setuser

    END
----------------------------

    BEGIN
    --> Step 1: Get the date of the LAST Month-End done
    	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date 
    	FROM AW_Period_Procedures 
    	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
    	ORDER BY Month_End_Date DESC
    
        --> Initialize M/E date if this is the FIRST Month-End procedure
    	IF @LastPeriodProcedureDate IS NULL 
    		SET @LastPeriodProcedureDate = '1900/01/01'
   
    --> Step 3: Get the last 7 Month-End dates to insert ageing for each Account
        EXEC sp_AW_Period_Procedures_Select
                @DatePicked,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT,
                1,
                @CompanyID
   
		IF @CustomerID_Single = 0
		BEGIN
			IF @ShowZeroBalance = 0
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers @CustomerID_Single = 0 And @ShowZeroBalance = 0
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0))
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
							INNER JOIN AS_Transactions t
								ON c.AC_Customers_ID = t.AC_Customers_ID
						 WHERE c.AW_User_Companies_ID = @CompanyID AND
							(
								Sys_AW_Transaction_Types_ID = 3 OR
								Sys_AW_Transaction_Types_ID = 4 OR
								Sys_AW_Transaction_Types_ID = 5 OR
								Sys_AW_Transaction_Types_ID = 7 OR
								Sys_AW_Transaction_Types_ID = 15 OR
								Sys_AW_Transaction_Types_ID = 18 OR
								Sys_AW_Transaction_Types_ID = 21 OR
								Sys_AW_Transaction_Types_ID = 22
							 ) OR
							 ( t.Transaction_Date > @D1 )		--All new transactions
						GROUP BY c.AC_Customers_ID,
								ISNULL(c.Surname, '') +
								ISNULL(', ' + c.FirstNames, ''),
								ISNULL(c.Post_Box, ''),
								ISNULL(c.Post_Office, ''),
								ISNULL(c.Post_Code, ''),
								ISNULL(c.Work_Email, ''),
								ISNULL(c.Customer_Number, '')
						HAVING SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)) <> 0
					)
			END
			ELSE
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers AC_Customers @CustomerID_Single = 0 And @ShowZeroBalance = 1
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							0
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
							INNER JOIN AS_Transactions t
								ON c.AC_Customers_ID = t.AC_Customers_ID
						 WHERE c.AW_User_Companies_ID = @CompanyID AND
							(
								Sys_AW_Transaction_Types_ID = 3 OR
								Sys_AW_Transaction_Types_ID = 4 OR
								Sys_AW_Transaction_Types_ID = 5 OR
								Sys_AW_Transaction_Types_ID = 7 OR
								Sys_AW_Transaction_Types_ID = 15 OR
								Sys_AW_Transaction_Types_ID = 18 OR
								Sys_AW_Transaction_Types_ID = 21 OR
								Sys_AW_Transaction_Types_ID = 22
							 ) AND
							 (
								ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 OR     --If there are not transactions after the last month end, you should still return customers with a balance
								t.Transaction_Date > @D1		--All new transactions
							  )
                
					)
			END
		END
		ELSE
		BEGIN
			IF @ShowZeroBalance = 0
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers AC_Customers @CustomerID_Single <> 0 And @ShowZeroBalance = 0
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0))
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
							INNER JOIN AS_Transactions t
								ON c.AC_Customers_ID = t.AC_Customers_ID
						 WHERE	c.AW_User_Companies_ID = @CompanyID AND
								c.AC_Customers_ID = @CustomerID_Single AND
							(
								Sys_AW_Transaction_Types_ID = 3 OR
								Sys_AW_Transaction_Types_ID = 4 OR
								Sys_AW_Transaction_Types_ID = 5 OR
								Sys_AW_Transaction_Types_ID = 7 OR
								Sys_AW_Transaction_Types_ID = 15 OR
								Sys_AW_Transaction_Types_ID = 18 OR
								Sys_AW_Transaction_Types_ID = 21 OR
								Sys_AW_Transaction_Types_ID = 22
							 ) OR
							 ( t.Transaction_Date > @D1 )		--All new transactions
						GROUP BY c.AC_Customers_ID,
								ISNULL(c.Surname, '') +
								ISNULL(', ' + c.FirstNames, ''),
								ISNULL(c.Post_Box, ''),
								ISNULL(c.Post_Office, ''),
								ISNULL(c.Post_Code, ''),
								ISNULL(c.Work_Email, ''),
								ISNULL(c.Customer_Number, '')
						HAVING SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)) <> 0
					)
			END
			ELSE
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers AC_Customers @CustomerID_Single <> 0 Show all, even if no transaction for month
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							0
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
						WHERE c.AW_User_Companies_ID = @CompanyID AND
							c.AC_Customers_ID = @CustomerID_Single
                
					)
			END
		END
    
    	OPEN Customer_Temp_Cursor
    
        	FETCH NEXT FROM Customer_Temp_Cursor 
        	INTO
                @CustomerID,
                @CustomerName,
                @PostBox,
                @PostOffice,
                @PostCode,
                @WorkEmail,
                @CustomerNumber,
				@ZeroBalance
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
        		FROM dbo.fn_AC_Customer_Ageing_Values
                    (
                        @CustomerID,
                        @DatePicked,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = @AgeCurrent + 
                                      @Age30Days + 
                                      @Age60Days + 
                                      @Age90Days + 
                                      @Age120Days + 
                                      @Age150Days + 
                                      @Age180Days

                --> 2004.4.2
                --SET @HasBalance = 0
                
                --V6.2 Already did filtering in cursor select
                --If you check for balance here you will miss paid up accounts for this month
                SET @HasBalance = 1

                --IF @AccountBalance <> 0
                --    BEGIN
                --        SET @HasBalance = 1
                --    END

                --IF @HasBalance = 0
                --    BEGIN
                --        IF @AgeCurrent <> 0 OR
                --            @Age30Days <> 0 OR
                --            @Age60Days <> 0 OR
                --            @Age90Days <> 0 OR
                --            @Age120Days <> 0 OR
                --            @Age150Days <> 0 OR
                --            @Age180Days <> 0
                --            BEGIN
                --                SET @HasBalance = 1
                --            END
                --    END
                    
                IF @HasBalance = 1
                    BEGIN
                		INSERT INTO AC_Statements_Temp
                			(
                                AW_Period_Procedures_ID,
                                AC_Customers_ID,
                                FullName,
                                Customer_Number,
                                Post_Address,
                                Post_Office,
                                Post_Code,
                                Work_Email,
                                [User_ID],
                                AW_User_Companies_ID,
                                Amount,
                                Payment,
                                Account_Balance,
                                [Current],
                                [30Days],
                                [60Days],
                                [90Days],
                                [120Days],
                                [150Days],
                                [180+Days],
                                Date_Captured
                            )
                		VALUES
                			(
                                @PeriodProcedureID,    --initialized to 0 ??
                                @CustomerID,
                                rtrim(ltrim(@CustomerName)),
                                @CustomerNumber,
                                @PostBox,
                                @PostOffice,
                                @PostCode,
                                @WorkEmail,
                                @UserID,
                                @CompanyID,
                                @AgeAmount,
                                @AgePayment,
                                @AccountBalance,
                                @AgeCurrent,
                                @Age30Days,
                                @Age60Days,
                                @Age90Days,
                                @Age120Days,
                                @Age150Days,
                                @Age180Days,
                                @DatePicked
                            )
            
                	  	SELECT @StatementID = Scope_Identity()
                
                		--Insert Transactions since LAST Period Procedure Date
                		INSERT INTO AC_Statement_Details_Temp
                			(
                                AC_Statements_Temp_ID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                Date_Captured,
                                [User_ID],
                                AW_User_Companies_ID
                            )
                        SELECT 
                                @StatementID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Total_Amount,
                                Payment_Amount,
                                @DatePicked,
                                [User_ID],
                                AW_User_Companies_ID
                        FROM AS_Transactions
                        --> Show ALL TRANSACTIONS NON-ZERO owing
                        WHERE AC_Customers_ID = @CustomerID AND
							(
								Sys_AW_Transaction_Types_ID = 3 OR
								Sys_AW_Transaction_Types_ID = 4 OR
								Sys_AW_Transaction_Types_ID = 5 OR
								Sys_AW_Transaction_Types_ID = 7 OR
								Sys_AW_Transaction_Types_ID = 15 OR
								Sys_AW_Transaction_Types_ID = 18 OR
								Sys_AW_Transaction_Types_ID = 21 OR
								Sys_AW_Transaction_Types_ID = 22
							) AND
							(
								ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 OR
								Transaction_Date Between @D1 AND @DatePicked 	--All new transactions
							)
                END
            --> 2004.4.2


            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Customer_Temp_Cursor 
            	INTO
                    @CustomerID,
                    @CustomerName,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @CustomerNumber,
					@ZeroBalance
    
        	END
    	
    	CLOSE Customer_Temp_Cursor
    
    	DEALLOCATE Customer_Temp_Cursor

    END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AC_Delete_Customer_Transaction
--Purpose       :Deletes a selected Customer Transaction
--Date          :2004/04/07
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Delete_Customer_Transaction
    (
        @TranID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AS_Transactions_ID
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @TranID

        )
        BEGIN
            DELETE AS_Transactions
            WHERE AS_Transactions_ID = @TranID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AC_Drop_Enterprise_Customer_Ageing
--Purpose       :Drops and re-creates AC_Enterprise_Customer_Ageing table
--Date          :2007/03/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AC_Drop_Enterprise_Customer_Ageing

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Customer_Ageing]

    
    CREATE TABLE [dbo].[AC_Enterprise_Customer_Ageing] (
    	[AC_Enterprise_Customer_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Customer_Ageing] ON [dbo].[AC_Enterprise_Customer_Ageing]([Filter], [Customer], [CustNo]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Enterprise_Customer_Ageing] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Customer_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Customer_Ageing_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Enterprise_Customer_Ageing].[CompanyID]'

    
    setuser







    SET @ReturnValue = 1


RETURN @ReturnValue
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























------------------------------------------------------------------------------
--Description   :sp_AC_Enterprise_Ageing_Temp_Insert
--Purpose       :Saves an Ad-Hoc snapshot of Account Customer Transactions
--              :AS AT Now
--Functionality :ONLY Customers that have had transactions are selected
--Date          :2007/03/29
--Authors       :TB
--MODS          :
--2004.3.7      :07/10/07 - Added and RETURN @ReturnValue
------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AC_Enterprise_Ageing_Temp_Insert
	(
        @DatePicked DateTime, 
        @Filter varchar(50),
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE
        @FilterDesc varchar(50),
        @CustomerID int,
        @CustomerName varchar(90),
        @CustomerNumber varchar(10),
        @AccountBalance money,
        @StatementID int,
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @ReturnValue int

--> Truncates the decimal of today's date e.g.
--        '2007-03-29 13:33:45.076' as '2007-03-29 00:00:00.000',
--        and adds 1 day which equals midnite tonight
--        which returns '2007-03-30 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @DatePicked), 0, 1)))
    SET @DatePicked = @Now
    SET @ReturnValue = 1

--------------------------
-- 	SET @CompanyID = 1
-- 	SET @UserID = 2
--------------------------

--Wipe the TEMP table-------
    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Enterprise_Ageing_Temp]

        
        CREATE TABLE [dbo].[AC_Enterprise_Ageing_Temp] (
        	[AC_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Account_Balance] [money] NULL ,
        	[Current] [money] NULL ,
        	[30Days] [money] NULL ,
        	[60Days] [money] NULL ,
        	[90Days] [money] NULL ,
        	[120Days] [money] NULL ,
        	[150Days] [money] NULL ,
        	[180+Days] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Ageing_Temp] ON [dbo].[AC_Enterprise_Ageing_Temp]([Filter], [FullName], [Customer_Number]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AC_Enterprise_Ageing_Temp] ADD 
        	CONSTRAINT [PK_AC_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AC_Enterprise_Ageing_Temp_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[120Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[150Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[180+Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[30Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[60Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[90Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Account_Balance]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Current]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Enterprise_Ageing_Temp].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Payment]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Enterprise_Ageing_Temp].[User_ID]'

        
        setuser


    END
----------------------------

    BEGIN
    --> Get the last 7 Month-End dates to insert ageing for each Account
        EXEC sp_AW_Period_Procedures_Select
                @DatePicked,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT,
                1,
                @CompanyID
    
    --> Define a CURSOR for AC_Customers
    	DECLARE Customer_Temp_Cursor CURSOR FOR
            (
                SELECT DISTINCT
                    c.AC_Customers_ID,
                    ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, '') AS [FullName],
                    ISNULL(c.Customer_Number, '')
                FROM AC_Customers c
                    INNER JOIN AS_Transactions t
                        ON c.AC_Customers_ID = t.AC_Customers_ID
                WHERE c.AW_User_Companies_ID = @CompanyID
            )
    
    	OPEN Customer_Temp_Cursor
    
        	FETCH NEXT FROM Customer_Temp_Cursor 
        	INTO
                @CustomerID,
                @CustomerName,
                @CustomerNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN

                IF @Filter = 'Type'
                    BEGIN
                        SELECT @FilterDesc = RTRIM(LTRIM(f.Description))
                        FROM Lup_AC_Customer_Types f
                            INNER JOIN AC_Customers c
                                ON c.Lup_AC_Customer_Types_ID = f.Lup_AC_Customer_Types_ID
                        WHERE c.AC_Customers_ID = @CustomerID
                    END
                ELSE
                IF @Filter = 'Group'
                    BEGIN
                        SELECT @FilterDesc = RTRIM(LTRIM(f.Description))
                        FROM Lup_AC_Customer_Groups f
                            INNER JOIN AC_Customers c
                                ON c.Lup_AC_Customer_Groups_ID = f.Lup_AC_Customer_Groups_ID
                        WHERE c.AC_Customers_ID = @CustomerID
                    END
                ELSE
                IF @Filter = 'AcctType'
                    BEGIN
                        SELECT @FilterDesc = RTRIM(LTRIM(f.Description))
                        FROM Sys_AC_Account_Types f
                            INNER JOIN AC_Customers c
                                ON c.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID
                        WHERE c.AC_Customers_ID = @CustomerID
                    END
                ELSE
                IF @Filter = 'Status'
                    BEGIN
                        SELECT @FilterDesc = RTRIM(LTRIM(f.Description))
                        FROM Sys_AC_Account_Status f
                            INNER JOIN AC_Customers c
                                ON c.Sys_AC_Account_Status_ID = f.Sys_AC_Account_Status_ID
                        WHERE c.AC_Customers_ID = @CustomerID
                    END


        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
        		FROM dbo.fn_AC_Customer_Ageing_Values
                    (
                        @CustomerID,
                        @DatePicked,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = @AgeCurrent + 
                                      @Age30Days + 
                                      @Age60Days + 
                                      @Age90Days + 
                                      @Age120Days + 
                                      @Age150Days + 
                                      @Age180Days

                IF NOT @AccountBalance = 0             --AND
--                         @AgeCurrent = 0 AND
--                         @Age30Days = 0 AND
--                         @Age60Days = 0 AND
--                         @Age90Days = 0 AND
--                         @Age120Days = 0 AND
--                         @Age150Days = 0 AND
--                         @Age180Days = 0

                BEGIN
            		INSERT INTO AC_Enterprise_Ageing_Temp
            			(
                            Filter,
                            AC_Customers_ID,
                            FullName,
                            Customer_Number,
                            [User_ID],
                            AW_User_Companies_ID,
                            Amount,
                            Payment,
                            Account_Balance,
                            [Current],
                            [30Days],
                            [60Days],
                            [90Days],
                            [120Days],
                            [150Days],
                            [180+Days],
                            Date_Captured
                        )
            		VALUES
            			(
                            @FilterDesc,
                            @CustomerID,
                            rtrim(ltrim(@CustomerName)),
                            @CustomerNumber,
                            @UserID,
                            @CompanyID,
                            @AgeAmount,
                            @AgePayment,
                            @AccountBalance,
                            @AgeCurrent,
                            @Age30Days,
                            @Age60Days,
                            @Age90Days,
                            @Age120Days,
                            @Age150Days,
                            @Age180Days,
                            @DatePicked
                        )
                END

            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Customer_Temp_Cursor 
            	INTO
                    @CustomerID,
                    @CustomerName,
                    @CustomerNumber
    
        	END
    	
    	CLOSE Customer_Temp_Cursor
    
    	DEALLOCATE Customer_Temp_Cursor

        SET @ReturnValue = 1

    END


SET NOCOUNT OFF


RETURN @ReturnValue























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_Exists_PBilling_Post
--Purpose       :Periodic Billing - Check if transactions posted
--Date          :2011/01/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Exists_PBilling_Post
	(
        @Date datetime,
        @Month int,
        @Year int,
        @CustomerID int,
        @Amount money,
		@Test int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @Test = 0


	SELECT TOP 1 @Test = AC_Periodic_Billing_Detail_ID
	FROM AC_Periodic_Billing_Detail
    WHERE AC_Customers_ID = @CustomerID AND
          Post = 1 AND
          MONTH(Transaction_Date) = @Month AND
          YEAR(Transaction_Date) = @Year AND
          Amount = @Amount AND
          Slu_AW_Active_ID = 1



RETURN @Test











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Filter_Customer_CostPlus_Categories
--Purpose       :Filters Customers to set Cost+Plus Categories globally
--Date          :2007/07/29
--Authors       :TB
--MODS:         :
--2004.4.5      :16/05/09 - Reworked to FETCH Customers with NO SALES
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Filter_Customer_CostPlus_Categories
    (
        @TermsID tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT c.AW_User_Companies_ID AS [CompanyID],
           c.AC_Customers_ID AS [CustomerID],
           MAX(ISNULL(c.Surname, '') + ' ' +
               '(' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' +
               '(' + ISNULL(c.Customer_Number, '') + ')') AS [Customer],

           ISNULL(SUM(d.Quantity), 0) AS [Qty],
           ISNULL(SUM(d.Original_Price * d.Quantity), 0) AS [Gross Sales],
           ISNULL(SUM(d.Discount_Amount) + SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [Discount],
           ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [Net Sales],

           ISNULL(CASE WHEN SUM(d.Original_Price * d.Quantity) <> 0
                THEN (SUM(d.Discount_Amount) + SUM((d.Unit_Price - d.Original_Price) * d.Quantity)) / SUM(d.Original_Price * d.Quantity) * 100
                ELSE 0.00
           END, 0) AS [Disc %],

           ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],

           ISNULL(CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0
                THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100
                ELSE 0.00
           END, 0) AS [GP %],
           c.Lup_AC_Markup_Categories_ID AS [Markup Category]

    FROM AC_Customers c
        LEFT JOIN AS_Transactions h
            ON c.AC_Customers_ID = h.AC_Customers_ID
        LEFT JOIN AS_Transaction_Details d
            ON h.AS_Transactions_ID = d.AS_Transactions_ID
    WHERE c.AW_User_Companies_ID = @CompanyID AND
          c.Slu_AW_Credit_Terms_ID = @TermsID
    GROUP BY c.AW_User_Companies_ID, c.AC_Customers_ID, c.Lup_AC_Markup_Categories_ID
    ORDER BY [Customer]




-------------------------------------------------------------------------------
-- PREVIOUS PROCEDURE
-------------------------------------------------------------------------------
--     DECLARE @StartDate AS datetime,
--             @EndDate AS datetime
-- 
-- 
--     SET @EndDate = getdate()
--     SET @StartDate = DATEADD(month, -6, @EndDate)


--     SELECT c.AW_User_Companies_ID AS [CompanyID],
--            c.AC_Customers_ID AS [CustomerID],
--            MAX(ISNULL(c.Surname, '') + ' ' +
-- --               ISNULL(c.Firstnames, '') +
--                '(' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' +
--                '(' + ISNULL(c.Customer_Number, '') + ')') AS [Customer],
-- 
--            SUM(d.Quantity) AS [Qty],
--            SUM(d.Original_Price * d.Quantity) AS [Gross Sales],
--            SUM(d.Discount_Amount) + SUM((d.Unit_Price - d.Original_Price) * d.Quantity) AS [Discount],
--            SUM(d.Extended_Amount - d.Tax_Amount) AS [Net Sales],
-- 
--            CASE WHEN SUM(d.Original_Price * d.Quantity) <> 0
--                 THEN (SUM(d.Discount_Amount) + SUM((d.Unit_Price - d.Original_Price) * d.Quantity)) / SUM(d.Original_Price * d.Quantity) * 100
--                 ELSE 0.00
--            END AS [Disc %],
-- 
--            SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
-- 
--            CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0
--                 THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100
--                 ELSE 0.00
--            END AS [GP %],
--            c.Lup_AC_Markup_Categories_ID AS [Markup Category]
-- 
--     FROM AS_Transaction_Details d
--         INNER JOIN AS_Transactions h
--             ON h.AS_Transactions_ID = d.AS_Transactions_ID
--         LEFT JOIN AC_Customers c
--             ON c.AC_Customers_ID = h.AC_Customers_ID
--     WHERE h.AW_User_Companies_ID = @CompanyID AND
--           c.Slu_AW_Credit_Terms_ID = @TermsID AND
-- --           h.Transaction_Date >= @StartDate AND
-- --           h.Transaction_Date <= @EndDate AND
--          (h.Sys_AW_Transaction_Types_ID = 3 OR
--           h.Sys_AW_Transaction_Types_ID = 4)
--     GROUP BY c.AW_User_Companies_ID, c.AC_Customers_ID, c.Lup_AC_Markup_Categories_ID
--     ORDER BY [Customer]
-------------------------------------------------------------------------------











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AC_Filter_Customer_Discount_Categories
--Purpose       :Filters Cuatomers to set Discount Categories globally
--Date          :2006/10/07
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Filter_Customer_Discount_Categories
    (
        @TermsID tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

--     DECLARE @StartDate AS datetime,
--             @EndDate AS datetime
-- 
-- 
--     SET @EndDate = getdate()
--     SET @StartDate = DATEADD(month, -6, @EndDate)


    SELECT c.AW_User_Companies_ID AS [CompanyID],
           c.AC_Customers_ID AS [CustomerID],
           MAX(ISNULL(c.Surname, '') + ' ' +
--               ISNULL(c.Firstnames, '') +
               '(' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' +
               '(' + ISNULL(c.Customer_Number, '') + ')') AS [Customer],

           SUM(d.Quantity) AS [Qty],
           SUM(d.Original_Price * d.Quantity) AS [Gross Sales],
           SUM(d.Discount_Amount) + SUM((d.Unit_Price - d.Original_Price) * d.Quantity) AS [Discount],
           SUM(d.Extended_Amount - d.Tax_Amount) AS [Net Sales],

           CASE WHEN SUM(d.Original_Price * d.Quantity) <> 0
                THEN (SUM(d.Discount_Amount) + SUM((d.Unit_Price - d.Original_Price) * d.Quantity)) / SUM(d.Original_Price * d.Quantity) * 100
                ELSE 0.00
           END AS [Disc %],

           SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],

           CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0
                THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100
                ELSE 0.00
           END AS [GP %],
           c.Lup_AC_Discount_Categories_ID AS [Discount Category]

    FROM AS_Transaction_Details d
        INNER JOIN AS_Transactions h
            ON h.AS_Transactions_ID = d.AS_Transactions_ID
        LEFT JOIN AC_Customers c
            ON c.AC_Customers_ID = h.AC_Customers_ID
    WHERE h.AW_User_Companies_ID = @CompanyID AND
          c.Slu_AW_Credit_Terms_ID = @TermsID AND
--           h.Transaction_Date >= @StartDate AND
--           h.Transaction_Date <= @EndDate AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4)
    GROUP BY c.AW_User_Companies_ID, c.AC_Customers_ID, c.Lup_AC_Discount_Categories_ID
    ORDER BY [Customer]











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   :sp_AC_Get_Claim_Code
--Purpose       :Get the Code for a Claim Clode ID
--Date          :2004/03/09
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Claim_Code
    (
        @CompanyID int,
        @ClaimCodeID smallint,
        @ClaimCode varchar(3) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @ClaimCode = LEFT(ISNULL(Code, ''), 3)
    FROM Lup_AP_Claim_Codes
    WHERE Lup_AP_Claim_Codes_ID = @ClaimCodeID



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description	:sp_AC_Get_CustomerID
--Purpose       :Gets AC_Customers_ID from Customer Number
--              :
--Date			:2003/07/01
--Authors		:TB
--Version		:1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_CustomerID
	(
		@CustomerNo varchar(10),
        @CompanyID int,
        @CustomerID int OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @CustomerID = AC_Customers_ID
    FROM AC_Customers
    WHERE Customer_Number = @CustomerNo AND
          AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Customer_Account_Balance
--Purpose       :Retrieve the latest Customer Account Balance
--              :
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Get_Customer_Account_Balance
    (
    	@CompanyID int,
        @CustomerID int,
    	@Balance money OUTPUT
    )

AS

SET NOCOUNT ON

   SELECT @Balance =  ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
   FROM AS_Transactions
   WHERE AW_User_Companies_ID = @CompanyID AND
         AC_Customers_ID = @CustomerID AND
         ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
         (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
          Sys_AW_Transaction_Types_ID = 4 OR   --Refund
          Sys_AW_Transaction_Types_ID = 5 OR   --Journal
          Sys_AW_Transaction_Types_ID = 7 OR   --Payment
          Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
          Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
          Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
          Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AC_Get_Customer_Account_Overrides
--Purpose       :Gets Customer Account Ovverride settings from @CustomerID
--Date			:2011/06/29
--Authors		:TB
--Version		:
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Get_Customer_Account_Overrides
	(
        @CustomerID int,
        @OverrideLimitID tinyint OUTPUT,
        @OverrideOverdueID tinyint OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @OverrideLimitID = AW_YesNo_Override_Credit_Limit,
           @OverrideOverdueID = AW_YesNo_Override_Overdue
    FROM AC_Customers
    WHERE AC_Customers_ID = @CustomerID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description	:sp_AC_Get_Customer_Account_Status
--Purpose       :Gets Customer Status for one Customer
--Date			:2011/08/23
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Customer_Account_Status
	(
        @CompanyID int,
        @CustomerID int,
        @AccountStatus varchar(30) OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @AccountStatus = ISNULL(s.Description, '')
    FROM AC_Customers c
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
    WHERE c.AW_User_Companies_ID = @CompanyID AND
          c.AC_Customers_ID = @CustomerID
          


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AC_Get_Customer_Credit_Limit
--Purpose       :Gets Customer Credit Limit for one Customer
--Date			:2007/05/10
--Authors		:TB
--MODS          :
--2004.3.7      :01/08/07 - Replaced incorrect Customer_Number with AC_Customers_ID
--              :           in WHERE clause
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Customer_Credit_Limit
	(
        @CompanyID int,
        @CustomerID int,
        @CreditLimit money OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @CreditLimit = ISNULL(Credit_Limit, 0)
    FROM AC_Customers
    WHERE AW_User_Companies_ID = @CompanyID AND
          AC_Customers_ID = @CustomerID
          


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Customer_Email_Address
--Date          :2011/05/07
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             Procedure sp_AC_Get_Customer_Email_Addresses
    (
        @CustomerID int,
        @AccountsEmail varchar(100) OUTPUT,
        @HomeEmail varchar(40) OUTPUT,
        @WorkEmail varchar(40) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @AccountsEmail = ISNULL(Orders_URL, ''),
           @HomeEmail = ISNULL(Home_Email, ''),
           @WorkEmail = ISNULL(Work_Email, '')
    FROM AC_Customers
	WHERE AC_Customers_ID = @CustomerID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AC_Get_Customer_Overdue_Amount
--Purpose       :Gets Overdue amount for ONE Customer
--Date          :2005/03/05
--Authors       :TB
--MODS          :06/03/05 - Added @Now
--2004.3.4      :13/02/07 - Simplified Overdue amount fetch in UI by move
--              :            selecting last 7 Period Procedures here
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Customer_Overdue_Amount
    (
        @CustomerID int,
        @CompanyID int,
        @Overdue money OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @Midnight datetime,
            @Now datetime,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime


    SET @Now = getdate()
    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Now), 0, 1)))
    SET @Overdue = 0


    --2004.3.4
    EXEC sp_AW_Period_Procedures_Select
            @Now,
            @D1 OUTPUT,
            @D2 OUTPUT,
            @D3 OUTPUT,
            @D4 OUTPUT,
            @D5 OUTPUT,
            @D6 OUTPUT,
            @D7 OUTPUT,
            1,
            @CompanyID


  	SELECT @Overdue = ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (a.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 @CustomerID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)
	FROM AC_Customers a
        LEFT JOIN Slu_AW_Credit_Terms b
            ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
	WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.AC_Customers_ID = @CustomerID




SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AC_Get_Customer_Tax_Code
--Purpose       :Gets Customer Tax Code from @CustomerID
--Date			:2011/05/06
--Authors		:TB
--Version		:
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Customer_Tax_Code
	(
        @CustomerID int,
        @TaxCodeID tinyint OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @TaxCodeID = Sys_AW_Tax_Codes_ID
    FROM AC_Customers
    WHERE AC_Customers_ID = @CustomerID


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AC_Get_Delivery_Details
--Purpose       :Fetch the Delivery Address, Contact, Tel No, E-mail address
--Parameters    :OUTPUT
--Date          :2008/06/13
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AC_Get_Delivery_Details
	(
        @CustomerID int,
        @Delivery1 varchar(40) OUTPUT,
        @Delivery2 varchar(40) OUTPUT,
        @Delivery3 varchar(30) OUTPUT,
        @PostCode varchar(10) OUTPUT,
        @ContactName varchar(30) OUTPUT,
        @WorkTelNo varchar(16) OUTPUT,
        @ContactEmail varchar(40) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT  @Delivery1 = ISNULL(Delivery_Address, ''),
            @Delivery2 = ISNULL(Delivery_Suburb, ''),
            @Delivery3 = ISNULL(Delivery_City, ''),
            @PostCode = ISNULL(Delivery_Post_Code, ''),
            @ContactName = ISNULL(Contact_Name, ''),
            @WorkTelNo = ISNULL(Work_Tel_No, ''),
            @ContactEmail = ISNULL(Home_Email, '')
    FROM AC_Customers
    WHERE AC_Customers_ID = @CustomerID


        
SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Discount_Category
--Purpose       :
--Functionality :Tables: Lup_AC_Discount_Categories
--Parameters    : 
--Date          :2002/02/08
--Authors       :TB
--MODS          :
--2004.4.0      :28/07/07 - Added ORDER BY [Description]
--              :28/07/07 - Reworked using [User], [Active] ID's to allow ListBindGrid
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Discount_Category
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON


	SELECT Lup_AC_Discount_Categories_ID AS [ID],
           [Description] AS [Discount Category],
           Date_Captured AS [Date],
           [User_ID] AS [User],
           Slu_AW_Active_ID AS [Active]
	FROM Lup_AC_Discount_Categories
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]


-- 	SELECT a.Lup_AC_Discount_Categories_ID AS [ID],
--            a.[Description] AS [Discount Category],
--            a.Date_Captured AS [Date],
--            CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
--                     THEN ISNULL(b.Surname,'')
--                 WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
--                     THEN ISNULL(b.Surname,'')
--                 ELSE ISNULL(b.Surname,'') + ', ' + 
--                      LTRIM(ISNULL(b.FirstName,''))
--                 END AS [User],
--            c.Description AS [Active]
-- 	FROM Lup_AC_Discount_Categories a
-- 		INNER JOIN AW_users b
--             ON a.User_ID = b.AW_Users_ID
--         INNER JOIN dbo.Slu_AW_Active c
--             ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
-- 	WHERE AW_User_Companies_ID = @Company_ID
--     ORDER BY a.[Description]







SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Discount_Category_Per_Group
--Purpose       :Returns the Commission Categories for the selected Group
--Functionality :Tables: AS_Discount_Categories_Groups, Lup_AC_Discount_Categories
--Parameters    :
--Date          :2002/02/09
--Authors       :TB
--Version       :1.0.0
--              :03/10/03 - Changed alias [Comm %] to [Disc %]
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Discount_Category_Per_Group
    (
    	@GroupID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

-- 	SELECT a.AS_Commission_Categories_Groups_ID AS [ID],
--     	   a.Lup_AP_Commission_Groups_ID AS [FK ID],
--     	   b.[Description] AS [Commission Category],
--     	   a.Commission_Percentage AS [Comm %],    --[Percentage],
--     	   a.Date_Captured AS [Date],              --[Date Captured],
--     	   a.[User_ID] AS [User ID],
--     	   a.Slu_AW_Active_ID AS [Active]
-- 	FROM AS_Commission_Categories_Groups a
--         INNER JOIN Lup_AS_Commission_Categories b 
-- 	        ON a.Lup_AS_Commission_Categories_ID = b.Lup_AS_Commission_Categories_ID
-- 	WHERE a.Lup_AP_Commission_Groups_ID = @GroupID AND
--           a.AW_User_Companies_ID = @Company_ID

	SELECT a.AS_Discount_Categories_Groups_ID AS [ID],
    	   a.Lup_AP_Discount_Groups_ID AS [FK ID],
    	   b.[Description] AS [Discount Category],
    	   a.Discount_Percentage AS [Disc %],    --[Percentage],
    	   a.Date_Captured AS [Date],              --[Date Captured],
            CASE WHEN c.Surname IS NULL and c.FirstName IS NULL
                     THEN ISNULL(c.Surname,'')
                 WHEN c.Surname IS NOT NULL and c.FirstName IS NULL
                     THEN ISNULL(c.Surname,'')
                 ELSE ISNULL(c.Surname,'') + ', ' + 
                      LTRIM(ISNULL(c.FirstName,''))
                 END AS [User],
            d.Description AS [Active]
	FROM AS_Discount_Categories_Groups a
        INNER JOIN Lup_AC_Discount_Categories b 
	        ON a.Lup_AC_Discount_Categories_ID = b.Lup_AC_Discount_Categories_ID
		INNER JOIN AW_users c
            ON a.User_ID = c.AW_Users_ID
        INNER JOIN dbo.Slu_AW_Active d
            ON a.Slu_AW_Active_ID = d.Slu_AW_Active_ID
	WHERE a.Lup_AP_Discount_Groups_ID = @GroupID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF



--Description   :sp_AS_Get_Discount_Category_Per_Group
--Purpose       :Returns the discount categories for the selected 
--Functionality :
--Parameters    :@GroupID
--Date          : 2001/03/15
--Authors       :charl	
--Version       :1.0.0

-- ALTER      PROCEDURE sp_AC_Get_Discount_Category_Per_Group
-- (
-- 	@GroupID int,
-- 	@Company_ID int
-- )
-- AS
-- 	SELECT DCG.AS_Discount_Categories_Groups_ID AS [ID],
-- 		DCG.Lup_AP_Discount_Groups_ID AS [FK ID],
-- 		LupDC.[Description] AS [Discount Category],
-- 		DCG.Discount_Percentage AS [Percentage],
-- 		DCG.Date_Captured AS [Date Captured],
-- 		DCG.[User_ID] AS [User ID],
-- 		DCG.AW_User_Companies_ID AS [Company],
-- 		DCG.Slu_AW_Active_ID AS [Active]
-- 	FROM AS_Discount_Categories_Groups DCG INNER JOIN
-- 	Lup_AC_Discount_Categories LupDC ON LupDC.Lup_AC_Discount_Categories_ID =
-- 	DCG.Lup_AC_Discount_Categories_ID
-- 	WHERE DCG.Lup_AP_Discount_Groups_ID = @GroupID AND
-- 		DCG.AW_User_Companies_ID = @Company_ID













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













---------------------------------------------------------------------------------
--Description   :sp_AC_Get_Fail_Reason_Code
--Purpose       :Get the Code for a Fail Reason ID
--Date          :2004/03/03
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Fail_Reason_Code
    (
        @CompanyID int,
        @FailReasonID smallint,
        @FailCode varchar(7) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @FailCode = LEFT(ISNULL(Code, ''), 7)
    FROM Lup_AP_Fail_Reasons
    WHERE Lup_AP_Fail_Reasons_ID = @FailReasonID



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








--------------------------------------------------------------------------------
--Description   :sp_AC_Get_Group_Per_Discount_Category
--Purpose       :Returns the Discount Groups for a Discount Category
--Date          :2002/02/08
--Authors       :TB
--MODS          :
--2004.4.0      :28/07/07 - Repositioned [FK ID] to 2nd field
--              :28/07/07 - Renamed [User ID] to [User]
--------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Group_Per_Discount_Category
    (
    	@CategoryID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


	SELECT a.AS_Discount_Categories_Groups_ID AS [ID],
           a.Lup_AC_Discount_Categories_ID AS [FK ID],
           b.[Description] AS [Discount Group],
           a.Discount_Percentage AS [Disc %],
           a.Date_Captured AS [Date],
           a.[User_ID] AS [User],
           a.Slu_AW_Active_ID AS [Active]
	FROM AS_Discount_Categories_Groups a
        INNER JOIN Lup_AP_Discount_Groups b
            ON b.Lup_AP_Discount_Groups_ID = a.Lup_AP_Discount_Groups_ID
	WHERE a.Lup_AC_Discount_Categories_ID = @CategoryID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--------------------------------------------------------------------------------
--Description   :sp_AC_Get_Group_Per_Markup_Category
--Purpose       :Returns the Cost+Plus Groups for a Cost+Plus Category
--Date          :2007/07/23
--Authors       :TB
--MODS          :
--2004.4.0      :28/07/07 - Repositioned [FK ID] to 2nd field
--              :28/07/07 - Renamed [User ID] to [User]
--------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Get_Group_Per_Markup_Category
    (
    	@CategoryID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


	SELECT a.AS_Markup_Categories_Groups_ID AS [ID],
           a.Lup_AC_Markup_Categories_ID AS [FK ID],
           b.[Description] AS [Markup Group],
           a.Markup_Percentage AS [Markup %],
           a.Date_Captured AS [Date],
           a.[User_ID] AS [User],
           a.Slu_AW_Active_ID AS [Active]
	FROM AS_Markup_Categories_Groups a
        INNER JOIN Lup_AP_Markup_Groups b
            ON b.Lup_AP_Markup_Groups_ID = a.Lup_AP_Markup_Groups_ID
	WHERE a.Lup_AC_Markup_Categories_ID = @CategoryID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Invoice_Terms_Due
--Purpose       :Select Customer Account Ageing and Overdue Invoice Totals
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :26/01/04 - Added @TotalDays and @TranCNT to calculate Days Overdue
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Invoice_Terms_Due
	(
        @Choice tinyint,
        @Date datetime,
        @CompanyID int,
        @CustomerID int,
        @DaysTerms int,
        @Amount money OUTPUT,
        @TotalDays int OUTPUT,
        @TranCNT int OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE
        @Midnight datetime

-- SET @Choice = 2
-- SET @Date = '2003/10/10 12:19:00'
-- SET @CompanyID = 1
-- SET @CustomerID = 4
-- SET @DaysTerms = 21


    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Date), 0, 1)))
    SET @Amount = 0

--> CUSTOMER On Invoice Terms amount DUE
    IF @Choice = 1
    	BEGIN

    		SELECT @Amount = ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
        	FROM AS_Transactions
        	WHERE AC_Customers_ID = @CustomerID AND
                  AW_User_Companies_ID = @CompanyID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR        --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                --> If Transaction EXACTLY @DaysTerms OLD
                  DATEDIFF(d, @Midnight, Transaction_Date + @DaysTerms) = 0

    	END

    ELSE
--> CUSTOMER On Invoice Terms amount OVERDUE
    IF @Choice = 2
    	BEGIN

    		SELECT @Amount = ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0),
                   @TotalDays = ISNULL(SUM(DATEDIFF(d, @Midnight, Transaction_Date + @DaysTerms)), 0),
                   @TranCNT = ISNULL(COUNT(Sys_AW_Transaction_Types_ID), 0)
        	FROM AS_Transactions
        	WHERE AC_Customers_ID = @CustomerID AND
                  AW_User_Companies_ID = @CompanyID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR        --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR        --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR       --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                --> If Transaction OLDER THAN @DaysTerms
                  DATEDIFF(d, @Midnight, Transaction_Date + @DaysTerms) < 0

    	END


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Last_Period_Procedure_Date
--Purpose       :Get the date of the LAST Month-End done
--Date          :2004/01/23
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Last_Period_Procedure_Date
	(
		@CompanyID int,
        @LastPeriodProcedureDate datetime OUTPUT,
        @LastPeriodProcedureMonthID tinyint OUTPUT,
        @LastPeriodProcedureYearID int OUTPUT
	)

AS

SET NOCOUNT ON


	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date,
                 @LastPeriodProcedureMonthID = [Month],
                 @LastPeriodProcedureYearID = [Year]
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          AW_User_Companies_ID = @CompanyID
	ORDER BY Month_End_Date DESC












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Markup_Category
--Purpose       :
--Functionality :Tables: Lup_AC_Markup_Categories
--Parameters    : 
--Date          :2007/07/23
--Authors       :TB
--MODS          :
--2004.4.0      :28/07/07 - Added ORDER BY [Description]
--              :28/07/07 - Reworked using [User], [Active] ID's to allow ListBindGrid
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Markup_Category
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON


	SELECT Lup_AC_Markup_Categories_ID AS [ID],
           [Description] AS [Markup Category],
           Date_Captured AS [Date],
           [User_ID] AS [User],
           Slu_AW_Active_ID AS [Active]
	FROM Lup_AC_Markup_Categories
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]


-- 	SELECT a.Lup_AC_Markup_Categories_ID AS [ID],
--            a.[Description] AS [Markup Category],
--            a.Date_Captured AS [Date],
--             CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
--                      THEN ISNULL(b.Surname,'')
--                  WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
--                      THEN ISNULL(b.Surname,'')
--                  ELSE ISNULL(b.Surname,'') + ', ' + 
--                       LTRIM(ISNULL(b.FirstName,''))
--                  END AS [User],
--             c.Description AS [Active]
-- 	FROM Lup_AC_Markup_Categories a
-- 		INNER JOIN AW_users b
--             ON a.User_ID = b.AW_Users_ID
--         INNER JOIN dbo.Slu_AW_Active c
--             ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
-- 	WHERE AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Markup_Category_Per_Group
--Purpose       :Returns the Markup Categories for the selected Group
--Functionality :Tables: AS_Markup_Categories_Groups, Lup_AC_Markup_Categories
--Parameters    :
--Date          :2007/07/23
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Get_Markup_Category_Per_Group
    (
    	@GroupID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT a.AS_Markup_Categories_Groups_ID AS [ID],
    	   a.Lup_AP_Markup_Groups_ID AS [FK ID],
    	   b.[Description] AS [Markup Category],
    	   a.Markup_Percentage AS [Markup %],
    	   a.Date_Captured AS [Date],
            CASE WHEN c.Surname IS NULL and c.FirstName IS NULL
                     THEN ISNULL(c.Surname,'')
                 WHEN c.Surname IS NOT NULL and c.FirstName IS NULL
                     THEN ISNULL(c.Surname,'')
                 ELSE ISNULL(c.Surname,'') + ', ' + 
                      LTRIM(ISNULL(c.FirstName,''))
                 END AS [User],
            d.Description AS [Active]
	FROM AS_Markup_Categories_Groups a
        INNER JOIN Lup_AC_Markup_Categories b 
	        ON a.Lup_AC_Markup_Categories_ID = b.Lup_AC_Markup_Categories_ID
		INNER JOIN AW_users c
            ON a.User_ID = c.AW_Users_ID
        INNER JOIN dbo.Slu_AW_Active d
            ON a.Slu_AW_Active_ID = d.Slu_AW_Active_ID
	WHERE a.Lup_AP_Markup_Groups_ID = @GroupID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















----------------------------------------------------------------------------
--Description   :sp_AC_Get_Periodic_Billing_Descriptions
--Purpose       :Get Customer, Tran Type, GL Account,Tax Method descriptions
--Date          :2011/01/23
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Periodic_Billing_Descriptions
    (
        @CompanyID int,
        @CustomerID int,
        @TranTypeID tinyint,
        @GLAccountID int,
        @TaxMethodID tinyint,
        @Customer varchar(200) OUTPUT,
        @TranType varchar(20) OUTPUT,
        @GLAccount varchar(50) OUTPUT,
        @TaxMethod varchar(10) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Customer = ISNULL(Surname, '') +
                       ISNULL(', ' + Firstnames, '') +
                       ISNULL(', ' + Street_Address, '') +
                       ISNULL(', ' + Suburb, '') +
                       ISNULL(', ' + City, '')
    FROM AC_Customers
    WHERE AW_User_Companies_ID = @CompanyID AND
          AC_Customers_ID = @CustomerID


    SELECT @TranType = [Description]
    FROM Sys_AW_Transaction_Types
    WHERE Sys_AW_Transaction_Types_ID = @TranTypeID


    SELECT @GLAccount = Description
    FROM AB_Accounts
    WHERE AW_User_Companies_ID = @CompanyID AND
          AB_Accounts_ID = @GLAccountID


    SELECT @TaxMethod = Description
    FROM Sys_AW_Tax_Methods
    WHERE Sys_AW_Tax_Methods_ID = @TaxMethodID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















----------------------------------------------------------------------------
--Description   :sp_AC_Get_Periodic_Billing_Split_Descriptions
--Purpose       :Get Product and Tax Method descriptions
--Date          :2011/01/23
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Get_Periodic_Billing_Split_Descriptions
    (
        @CompanyID int,
        @ProductID int,
        @TaxMethodID tinyint,
        @Product varchar(50) OUTPUT,
        @TaxMethod varchar(10) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @Product = Description
    FROM AP_Products
    WHERE AW_User_Companies_ID = @CompanyID AND
          AP_Products_ID = @ProductID


    SELECT @TaxMethod = Description
    FROM Sys_AW_Tax_Methods
    WHERE Sys_AW_Tax_Methods_ID = @TaxMethodID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AC_Get_Settlement_Discount_Perc
--Purpose       :Gets the Settlement Discount % for one customer
--Date			:2005/02/03
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Settlement_Discount_Perc
	(
        @CompanyID int,
		@CustomerID int,
        @SettDisc decimal(7,2) OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @SettDisc = ISNULL(Default_Settlement_Discount, 0)
    FROM AC_Customers
    WHERE AC_Customers_ID = @CustomerID AND
          AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AC_Get_Statement_Terms_Due
--Purpose       :Select Customer Account Ageing Totals
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :25/06/03 - Removed @CompanyID to fn_AC_Customer_Ageing_Non_Grouped
--              :           to enable multi-company processing - superfluous
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Get_Statement_Terms_Due
	(
        @Date datetime,
        @CompanyID int,
        @CustomerID int,
        @DaysTerms int
    )

AS

SET NOCOUNT ON

    DECLARE
        @Midnight datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime


-- SET @Choice = 2
-- SET @Date = '2003/10/10 12:19:00'
-- SET @CompanyID = 1
-- SET @CustomerID = 4
-- SET @DaysTerms = 21


    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Date), 0, 1)))


    EXEC sp_AW_Period_Procedures_Select
                             @Midnight,
                             @D1 OUTPUT,
                             @D2 OUTPUT,
                             @D3 OUTPUT,
                             @D4 OUTPUT,
                             @D5 OUTPUT,
                             @D6 OUTPUT,
                             @D7 OUTPUT,
                             1,
                             @CompanyID

	SELECT
		CustomerID,
		SUM(Payment) AS [Payment],
		SUM(Amount) AS [Amount],
		SUM([Current]) AS [Current],
		SUM([30 Days]) AS [30 Days],
		SUM([60 Days]) AS [60 Days],
		SUM([90 Days]) AS [90 Days],
		SUM([120 Days]) AS [120 Days],
		SUM([150 Days]) AS [150 Days],
		SUM([180+ Days]) AS [180+ Days]
		FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
--        ( @CompanyID, @CustomerID, @Midnight, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
        ( @CustomerID, @Midnight, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
	GROUP BY CustomerID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















---------------------------------------------------------------------------------
--Description   :sp_AC_Get_Trade_Style
--Purpose       :Get the Local Host connection Node_Name
--Date          :2005/02/05
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Get_Trade_Style
    (
        @CompanyID int,
        @TradeName varchar(50) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TradeName = ISNULL(Company_Trading_Name, '')
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AC_Insert_CBilling_Temp
--Functionality :INSERT daily UNSUBMITTED Centralised Sales transactions
--Parameters    :
--Date          :2005/09/29
--Authors       :TB
--MODS          :03/10/05 - Removed superfluous @ProviderID from WHERE filter
--              :           to enable setting DEFAULT provider in UI
--2004.2.8      :03/05/06 - Added input parameters to EXCLUDE Sales Cost Prices
--              :           and Truck and Tractor SALES data from submission
--2004.3.2      :22/09/06 - Added TRUNCATE all table varchar(50) fields to LEFT(48)
--              :01/11/06 - Added EXCLUDE Lubrication SALES data from submission
--2004.3.4      :21/02/07 - Replaced @chkTruckSales tinyint input parameter with
--              :           @ExclusionsFilter varchar(250) and append to query
--              :24/03/07 - Removed all customer details from submission file
--              :           EXCEPT if FLEET company
--2004.3.5      :16/05/07 - Added FILTER in WHERE clause to EXCLUDE INTER-BRANCH SALES
--              :           to other Customer Group FRANCHISEES in the Bridgestone Retail
--              :           stable by inserting 'bsretail' in the Head_Office field
--              :           of the BRANCH in the Customer Catalog
--2004.3.7      :15/08/07 - Added leading and trailing quotes to Product/Manuf code
--2004.4.7      :18/09/09 - Added Merchant No in 'special_instr'  and replaced 'branch_name'
--              :           with Trading Name as per Denise van Gent new specs
--R.L	2015-03-12	:Added Inclusion List
-------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AC_Insert_CBilling_Temp]
    (
        @chkSalesCost tinyint,
        @chkExcludeInterBranch tinyint,
        @ExclusionsFilter varchar(8000),
        @InclusionFilter varchar(8000),
        @StartDayEndDate datetime,
        @EndDayEndDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql				varchar(8000),
            @RetCode			tinyint,
            @No_Days			int,
            @Temp_No_Days		Varchar(20)

    SET @RetCode = 0
    SET @No_Days = 14

    SELECT TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCBillingDays'
          
	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
          
    Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
    
    --Select @StartDayEndDate

    SET @sql = ' INSERT AS_Transactions_CBilling_Temp '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + 'AS_Transactions_ID, '
    SET @sql = @sql + 'Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + 'cat_code, '
    SET @sql = @sql + 'drs_acc, '
    SET @sql = @sql + 'trs_ref, '
    SET @sql = @sql + 'trs_date, '
    SET @sql = @sql + 'qty, '
    SET @sql = @sql + 'amount, '
    SET @sql = @sql + 'gls_acc, '
    SET @sql = @sql + 'narr, '
    SET @sql = @sql + 'stock_group, '
    SET @sql = @sql + 'drs_apply, '
    SET @sql = @sql + 'sys_code, '
    SET @sql = @sql + 'updated, '
    SET @sql = @sql + 'interfaced, '
    SET @sql = @sql + 'drs_age_month, '
    SET @sql = @sql + 'stock_code, '
    SET @sql = @sql + 'area, '
    SET @sql = @sql + 'drs_alpha, '
    SET @sql = @sql + 'branch, '
    SET @sql = @sql + 'vat_amount, '
    SET @sql = @sql + 'cost_amount, '
    SET @sql = @sql + 'rep_comm, '
    SET @sql = @sql + 'process_type, '
    SET @sql = @sql + 'rep_code, '
    SET @sql = @sql + 'acct_type, '
    SET @sql = @sql + 'disc_amnt, '
    SET @sql = @sql + 'std_sell_price, '
    SET @sql = @sql + 'drs_trs_code, '
    SET @sql = @sql + 'trs_type, '
    SET @sql = @sql + 'acc_month, '
    SET @sql = @sql + 'acc_year, '
    SET @sql = @sql + 'con_acct_no, '
    SET @sql = @sql + 'zz_int01, '
    SET @sql = @sql + 'cntno, '
    SET @sql = @sql + 'line_disc1, '
    SET @sql = @sql + 'line_disc2, '
    SET @sql = @sql + 'stock_sell1, '
    SET @sql = @sql + 'no_of_deals, '
    SET @sql = @sql + 'zz_date01, '
    SET @sql = @sql + 'zz_date02, '
    SET @sql = @sql + 'zz_date03, '
    SET @sql = @sql + 'special_instr, '
    SET @sql = @sql + 'deals_flag, '
    SET @sql = @sql + 'deals_number, '
    SET @sql = @sql + 'vat_exempt_member, '
    SET @sql = @sql + 'cmonth, '
    SET @sql = @sql + 'cyear, '
    SET @sql = @sql + 'rep_call_status, '
    SET @sql = @sql + 'drsdiv_code, '
    SET @sql = @sql + 'crs_acc, '
    SET @sql = @sql + 'creation_date, '
    SET @sql = @sql + 'creation_time, '
    SET @sql = @sql + 'creation_userid, '
    SET @sql = @sql + 'creation_proc, '
    SET @sql = @sql + 'item_number, '
    SET @sql = @sql + 'rep_code2, '
    SET @sql = @sql + 'qty2, '
    SET @sql = @sql + 'deposit_amount, '
    SET @sql = @sql + 'job_number, '
    SET @sql = @sql + 'line_disc_amnt, '
    SET @sql = @sql + 'carhire_cntno, '
    SET @sql = @sql + 'currency, '
    SET @sql = @sql + 'exch_rate, '
    SET @sql = @sql + 'cyear_month, '
    SET @sql = @sql + 'zz_date04, '
    SET @sql = @sql + 'zz_date05, '
    SET @sql = @sql + 'zz_int02, '
    SET @sql = @sql + 'zz_int03, '
    SET @sql = @sql + 'zz_int04, '
    SET @sql = @sql + 'zz_int05, '
    SET @sql = @sql + 'zz_dec01, '
    SET @sql = @sql + 'zz_dec02, '
    SET @sql = @sql + 'zz_dec03, '
    SET @sql = @sql + 'zz_dec04, '
    SET @sql = @sql + 'zz_dec05, '
    SET @sql = @sql + 'zz_log01, '
    SET @sql = @sql + 'zz_log02, '
    SET @sql = @sql + 'zz_log03, '
    SET @sql = @sql + 'zz_log04, '
    SET @sql = @sql + 'zz_log05, '
    SET @sql = @sql + 'zz_log06, '
    SET @sql = @sql + 'zz_log07, '
    SET @sql = @sql + 'zz_char01, '
    SET @sql = @sql + 'zz_char02, '
    SET @sql = @sql + 'zz_char03, '
    SET @sql = @sql + 'zz_char04, '
    SET @sql = @sql + 'zz_char05, '
    SET @sql = @sql + 'key_glstrs, '
    SET @sql = @sql + 'key_history, '
    SET @sql = @sql + 'dumped, '
    SET @sql = @sql + 'company_name, '
    SET @sql = @sql + 'branch_name, '
    SET @sql = @sql + 'drs_name, '
    SET @sql = @sql + 'crs_name, '
    SET @sql = @sql + 'prd_grp_descr, '
    SET @sql = @sql + 'stk_descry, '
    SET @sql = @sql + 'status_ind, '
    SET @sql = @sql + 'customer_ref, '
    SET @sql = @sql + 'comments1, '
    SET @sql = @sql + 'comments2, '
    SET @sql = @sql + 'comments3, '
    SET @sql = @sql + 'comments4, '
    SET @sql = @sql + 'comments5, '
    SET @sql = @sql + 'comments6, '
    SET @sql = @sql + 'comments7, '
    SET @sql = @sql + 'comments8, '
    SET @sql = @sql + 'database_id, '
    SET @sql = @sql + 'system_id, '
    SET @sql = @sql + 'vat_reg_no, '
    SET @sql = @sql + 'email, '
    SET @sql = @sql + 'customer_cell_number, '
    SET @sql = @sql + 'customer_email_address, '
    SET @sql = @sql + 'Date_Captured, '
    SET @sql = @sql + 'User_ID, '
    SET @sql = @sql + 'AW_User_Companies_ID, '
    SET @sql = @sql + 'Slu_AW_Active_ID '
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + ' t.AS_Transactions_ID, '
    SET @sql = @sql + ' cb.Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + ' CASE WHEN t.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + ' THEN ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' WHEN t.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ''CR'' + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' END, '                                                        --cat_code
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --trs_ref
    SET @sql = @sql + ' t.Transaction_Date, '                                         --trs_date
    SET @sql = @sql + ' d.Quantity, '                                                 --qty
    SET @sql = @sql + ' ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), '     --amount,
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '      --narr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '     --stock_group
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --drs_apply
    SET @sql = @sql + ' ''"'' + ''SPI'' + ''"'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' 1, '                                                          --drs_age_month

--     SET @sql = @sql + ' CASE WHEN p.Manufacturer_Code IS NULL OR RTRIM(LTRIM(p.Manufacturer_Code)) = ''"'' + ''''   '
--     SET @sql = @sql + ' THEN p.Product_Code '
--     SET @sql = @sql + ' ELSE p.Manufacturer_Code '
--     SET @sql = @sql + ' END, '                                                        --stock_code
    SET @sql = @sql + ' CASE WHEN ISNULL(p.Manufacturer_Code, '''') = '''' '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(p.Product_Code, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ISNULL(p.Manufacturer_Code, '''') + ''"'' '
    SET @sql = @sql + ' END, '                                                        --stock_code

    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '            --drs_alpha
    SET @sql = @sql + ' ''"'' + ISNULL(uc.Network_Identity_Number, '''') + ''"'', '   --branch
    SET @sql = @sql + ' d.Tax_Amount, '                                               --vat_amount
    
    --> Product Cost Price data = 0
    IF @chkSalesCost = 0
    BEGIN
        SET @sql = @sql + ' 0, '
    END
    ELSE
    BEGIN    
        SET @sql = @sql + ' ROUND(ISNULL(d.Unit_Cost, 0) * ISNULL(d.Quantity, 0), 2), '    --cost_amount,
    END
    
    SET @sql = @sql + ' 0, '                                                         --rep_comm
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --process_type
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'','
    SET @sql = @sql + ' d.Discount_Amount, '                                         --disc_amnt
    SET @sql = @sql + ' d.Original_Price, '                                          --std_sell_price
    SET @sql = @sql + ' ''"'' + ''100'' + ''"'', '                                   --drs_trs_code
    SET @sql = @sql + ' 1, '                                                         --trs_type
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --acc_month,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --acc_year
    
    --     SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '           --on_acct_no
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(c.Customer_Number, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' 1, '                                                         --zz_int01
    SET @sql = @sql + ' 1, '                                                         --cntno
    SET @sql = @sql + ' CASE WHEN (d.Unit_Price * d.Quantity) <> 0 '
    
    --     SET @sql = @sql + ' THEN CONVERT(money, ABS(ROUND( (((d.Discount_Amount) / (d.Unit_Price * d.Quantity)) * 100), 2)) ) '
    SET @sql = @sql + ' THEN ABS(ROUND(CONVERT(money, ((d.Discount_Amount / (d.Unit_Price * d.Quantity)) * 100)), 2)) '
    
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END, '                                                       --line_disc1
    SET @sql = @sql + ' 0, '                                                         --line_disc2
    SET @sql = @sql + ' 0, '                                                         --stock_sell1
    SET @sql = @sql + ' 0, '                                                         --no_of_deals
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date01
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date02
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date03


--    SET @sql = @sql + ' ''"'' + ''"'', '                                             --special_instr
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Old_Customer_Number, ''''), 10) + ''"'', '        --special_instr


    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_flag
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_number
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --cmonth,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --cyear
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --drsdiv_code,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --crs_acc,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --creation_date,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_time,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_userid,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_proc,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --item_number,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code2,
    SET @sql = @sql + '  0 , '                                                       --qty2,
    SET @sql = @sql + '  0 , '                                                       --deposit_amount,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --job_number,
    SET @sql = @sql + '  0 , '                                                       --line_disc_amnt,
    SET @sql = @sql + '  0 , '                                                       --carhire_cntno,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --currency,
    SET @sql = @sql + '  0 , '                                                       --exch_rate,
    SET @sql = @sql + '  0 , '                                                       --cyear_month,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date04,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date05,
    SET @sql = @sql + '  0 , '                                                       --zz_int02,
    SET @sql = @sql + '  0 , '                                                       --zz_int03,
    SET @sql = @sql + '  0 , '                                                       --zz_int04,
    SET @sql = @sql + '  0 , '                                                       --zz_int05,
    SET @sql = @sql + '  0 , '                                                       --zz_dec01,
    SET @sql = @sql + '  0 , '                                                       --zz_dec02,
    SET @sql = @sql + '  0 , '                                                       --zz_dec03,
    SET @sql = @sql + '  0 , '                                                       --zz_dec04,
    SET @sql = @sql + '  0 , '                                                       --zz_dec05,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char01,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char02,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char03,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char04,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char05,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_glstrs,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_history,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --company_name


--    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --branch_name
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Trading_Name, ''''), 48) + ''"'', '             --branch_name

   
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --drs_name,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + ''"'', '                                                       --crs_name,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '              --prd_grp_descr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '               --stk_descry,
    SET @sql = @sql + ' ''"'' + ''NE'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Registration_No, ''''), 48) + ''"'', '          --customer_ref,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --comments1,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'', '          --comments2,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'', '           --comments3,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'', '             --comments4,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Authorization_No, ''''), 48) + ''"'', '         --comments5,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Odometer_Reading, ''''), 48) + ''"'', '         --comments6,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Engine_No, ''''), 48) + ''"'', '                --comments7,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Model_Year, '''') + ISNULL('' '' + cb.Make, '''') + ISNULL('' '' + cb.Model, ''''), 48) + ''"'', '          --comments8,
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Network_Identity_Number, ''''), 48) + ''"'', '  --system_id,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Tax_Number, ''''), 48) + ''"'', '                --vat_reg_no,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'', '                   --email,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Cell_No, ''''), 48) + ''"'', '                   --customer_cell_number,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'', '                --customer_email_address,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' t.Date_Captured, '
    SET @sql = @sql + ' t.User_ID, '
    SET @sql = @sql + ' t.AW_User_Companies_ID, '
    SET @sql = @sql + ' t.Slu_AW_Active_ID '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '    INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '    LEFT JOIN AS_Transactions_CBilling cb '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = cb.AS_Transactions_ID '
    SET @sql = @sql + '    INNER JOIN AP_Products p '
    SET @sql = @sql + ' ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
    SET @sql = @sql + '    INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '    INNER JOIN AW_User_Companies uc '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = uc.AW_User_Companies_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Groups pg '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    
    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '

    IF @chkExcludeInterBranch = 1
        BEGIN
            SET @sql = @sql + '       ISNULL(LOWER(RTRIM(LTRIM(c.Head_Office))), '''') <> ''bsretail'' AND '
        END

    SET @sql = @sql + '      (t.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '       t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '       t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

-- Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
-- Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  

    SET @sql = @sql + 'ORDER BY t.AS_Transactions_ID '

IF LEN(@sql) >= 8000
    BEGIN
        SET @RetCode = 1

        RETURN @RetCode
    END

EXEC (@sql)
--Select @sql
SET @RetCode = 2

RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



















--sp_AC_Insert_Enterprise_Customer_Ageing 'ADV2004', 'Autowiel Menlyn', '000-111', 'Inter-Company', 2345.66

-------------------------------------------------------------------------------
--Description   :sp_AC_Insert_Enterprise_Customer_Ageing
--Purpose       :INSERT Enterprise Customer Ageing
--Date          :2007/03/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                       PROCEDURE sp_AC_Insert_Enterprise_Customer_Ageing
	(
        @SourceDB varchar(100),
        @FilterDesc varchar(50),
        @Customer varchar(50),
        @CustNo varchar(20),
        @Balance money,
        @Current money,
        @Days30 money,
        @Days60 money,
        @Days90 money,
        @Days120 money,
        @Days150 money,
        @Days180 money
	)

AS

SET NOCOUNT ON

        INSERT AC_Enterprise_Customer_Ageing
            (
                SourceDB,
                Filter,
                Customer,
                CustNo,
                Balance,
                Days0,
                Days30,
                Days60,
                Days90,
                Days120,
                Days150,
                Days180
            )
        VALUES
            (
                @SourceDB,
                @FilterDesc,
                @Customer,
                @CustNo,
                @Balance,
                @Current,
                @Days30,
                @Days60,
                @Days90,
                @Days120,
                @Days150,
                @Days180
            )


SET NOCOUNT OFF	













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_AC_Insert_First_Customer
--Purpose       :Inserts an empty Customer into the Customer Catalog
--Date          :2006/03/29
--Authors       :TB
--MODS          :
--2004.5.3      :13/09/11 - Added set Default Country using @CountryID 
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Insert_First_Customer
    (
        @UserID int,
        @CompanyID int,
        @CountryID smallint
    )

AS

SET NOCOUNT ON


    INSERT AC_Customers
        (
            Surname,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Countries_ID
        )
    VALUES
        (
            'New Customer',
            @UserID,
            @CompanyID,
            @CountryID
        )


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_AC_Insert_First_Prospect
--Purpose       :Inserts an empty Prospect into the Prospects Catalog
--Date          :2006/03/29
--Authors       :TB
--MODS          :
--2004.5.3      :13/09/11 - Added set Default Country using @CountryID 
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Insert_First_Prospect
    (
        @UserID int,
        @CompanyID int,
        @CountryID smallint
    )

AS

SET NOCOUNT ON


    INSERT AC_Prospects
        (
            Surname,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Countries_ID
        )
    VALUES
        (
            'New Prospect',
            @UserID,
            @CompanyID,
            @CountryID
        )


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AC_Insert_Master_Controller
--Purpose       :INSERT a message via the messaging system
--              :also used on WEB
--Date			:2004/01/04
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Insert_Master_Controller
	(
		@CompanyID int,
        @ActorID int,
        @ActorTypeID int,
        @MessageID int,
        @Message varchar(500),
        @SeverityLevelID tinyint,
        @MessageTypeID smallint,
        @DeliveryMethodID tinyint,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)

    INSERT Log_AC_Master_Controller
        (
            Actor_ID,
            Sys_AT_Actor_Types_ID,
            AW_Messages_ID,
            Message,
            Sys_AC_Severity_Levels_ID,
            Sys_AC_Message_Types_ID,
            Sys_AW_Delivery_Methods_ID,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @ActorID,
            @ActorTypeID,
            @MessageID,
            @Message,
            @SeverityLevelID,
            @MessageTypeID,
            @DeliveryMethodID,
            getdate(),
            @UserID,
    		@CompanyID
        )


    SELECT @ReturnCode = scope_identity()

    RETURN @ReturnCode 


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description	:sp_AC_Insert_Message_Dispatch_Date
--Purpose       :INSERT the Dispatch_Date for a message in the Message Log
--              :
--Date			:2004/01/04
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Insert_Message_Dispatch_Date
	(
        @MessageID int,
        @DispatchDate datetime = NULL
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode tinyint

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)

    BEGIN
        UPDATE Log_AC_Messages
        SET Dispatch_Date = @DispatchDate
        WHERE Log_AC_Messages_ID = @MessageID

        SET @ReturnCode = 1       -- 1 = Successful (True)
    
        RETURN @ReturnCode

    END



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AC_Insert_Message_Log
--Purpose       :INSERT a Message Log via the messaging system
--              :
--Date			:2004/01/04
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Insert_Message_Log
	(
        @CustomersID int,
        @MessageDate datetime,
        @CRMID int,
        @ControllerID int,
        @Addressee varchar(50),
        @SendTo varchar(20),
        @Balance money,
        @Overdue money,
        @CreditTerms varchar(50),
        @TermsOfSale varchar(20),
        @DeliveryMethod	varchar(20),
        @Message varchar(200),
        @AddressList varchar(100),
        @Errors varchar(50),
        @Subject varchar(30),
        @MessageID int,
        @UserID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)

    INSERT Log_AC_Messages
        (
            AC_Customers_ID,
            Message_Date,
            User_CRM_ID,
            User_Controller_ID,
            Addressee,
            Send_To,
            Balance,
            Overdue,
            Credit_Terms,
            Terms_Of_Sale,
            Delivery_Method,
            Subject,
            AW_Messages_ID,
            Message,
            Address_List,
            Errors,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @CustomersID,
            @MessageDate,
            @CRMID,
            @ControllerID,
            @Addressee,
            @SendTo,
            @Balance,
            @Overdue,
            @CreditTerms,
            @TermsOfSale,
            @DeliveryMethod,
            @Subject,
            @MessageID,
            @Message,
            @AddressList,
            @Errors,
            getdate(),
            @UserID,
    		@CompanyID
        )

    SELECT @ReturnCode = scope_identity()

    RETURN @ReturnCode 


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_Insert_Period_Billing_Detail
--Purpose       :Inserts Periodic Billing History Detail
--Date          :2011/01/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Insert_Period_Billing_Detail
    (
        @PBHeaderID int,
        @Post bit,
        @TranDate datetime,
    	@CustomerID int,
        @TranTypeID tinyint,
        @RefNo varchar(20),
        @TaxMethodID tinyint,
        @Amount money,
        @Tax money,
        @Net money,
        @GLAccountID int,
        @Comment varchar(20),
        @Notes varchar(250),
        @Email varchar(100),
        @DatePosted datetime,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @DetailID int


    SET @DetailID = 0


	BEGIN TRANSACTION

    	BEGIN 
    		INSERT INTO AC_Periodic_Billing_Detail
                (
                    AC_Periodic_Billing_Header_ID,
                    Post,
                    Transaction_Date,
                    Ref_No,
                    AC_Customers_ID,
                    Sys_AW_Transaction_Types_ID,
                    Sys_AW_Tax_Methods_ID,
                    Amount,
                    Tax_Amount,
                    Net_Amount,
                    AB_Accounts_ID,
                    Comment,
                    Notes,
                    Email,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
    		VALUES
                (
                    @PBHeaderID,
                    @Post,
                    @TranDate,
                    @RefNo,
                    @CustomerID,
                    @TranTypeID,
                    @TaxMethodID,
                    @Amount,
                    @Tax,
                    @Net,
                    @GLAccountID,
                    @Comment,
                    @Notes,
                    @Email,
                    @DatePosted,
                    @UserID,
                    @CompanyID
                )
    		
            SELECT @DetailID = Scope_Identity() 
    	END			

	COMMIT TRAN



	
RETURN @DetailID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AC_Insert_Period_Billing_Detail_Splits
--Purpose       :Inserts Inserts Periodic Billing History Detail Splits
--Date          :2011/01/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Insert_Period_Billing_Detail_Splits
    (
        @PBHeaderID int,
        @PBDetailID int,
        @ProductID int,
        @Qty decimal(9,3),
        @UnitPrice money,
        @TaxMethodID tinyint,
        @Amount money,
        @Tax money,
        @Net money,
        @DatePosted datetime,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @SplitID int


    SET @SplitID = 0


	BEGIN TRANSACTION

    	BEGIN 
    		INSERT INTO AC_Periodic_Billing_Detail_Splits
                (
                    AC_Periodic_Billing_Header_ID,
                    AC_Periodic_Billing_Detail_ID,
                    AP_Products_ID,
                    Quantity,
                    Unit_Price,
                    Sys_AW_Tax_Methods_ID,
                    Amount,
                    Tax_Amount,
                    Net_Amount,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
    		VALUES
                (
                    @PBHeaderID,
                    @PBDetailID,
                    @ProductID,
                    @Qty,
                    @UnitPrice,
                    @TaxMethodID,
                    @Amount,
                    @Tax,
                    @Net,
                    @DatePosted,
                    @UserID,
                    @CompanyID
                )
    		
            SELECT @SplitID = Scope_Identity() 
    	END			

	COMMIT TRAN



	
RETURN @SplitID













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AC_Insert_Customer_PB_Header
--Purpose       :Inserts Period_Billing Header
--Date          :2011/01/19
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AC_Insert_Period_Billing_Header
    (
        @PostType varchar(50),
        @DatePosted datetime,
        @MonthsID tinyint,
        @YearsID smallint,
        @ImportFile varchar(50),
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @HeaderID int


    SET @HeaderID = 0
    SET @ImportFile = LEFT(@ImportFile, 50)


	INSERT INTO AC_Periodic_Billing_Header
        (
            Posting_Type,
            Date_Posted,
            Slu_AW_Months_ID,
            Slu_AW_Years_ID,
            Import_Filename,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
	VALUES 
        (
            @PostType,
            @DatePosted,
            @MonthsID,
            @YearsID,
            @ImportFile,
            @DatePosted,
        	@UserID,
            @CompanyID
        )

	SELECT @HeaderID = Scope_Identity() 



RETURN @HeaderID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AC_Insert_Prospect_Customer
--Purpose       :TRANSFER a Prospect to Customers and DELETE the Prospect
--Date			:2006/03/29
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Insert_Prospect_Customer
	(
		@ProspectID int,
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)


    INSERT AC_Customers
        (
            Surname,
            Firstnames,
            Initials,
            Slu_AW_Titles_ID,
            Contact_Name,
            Slu_AW_Languages_ID,
            IDReg_Number,
            Customer_Number,
            Old_Customer_Number,
            Post_Box,
            Post_Office,
            Post_Code,
            Street_Address,
            Suburb,
            City,
            Street_Post_Code,
            Delivery_Address,
            Delivery_Suburb,
            Delivery_City,
            Delivery_Post_Code,
            Head_Office,
            Lup_AC_Customer_Types_ID,
            Lup_AC_Customer_Groups_ID,
            Sys_AC_Account_Status_ID,
            AW_YesNo_Pre_Notify_ID,
            AW_YesNo_Post_Notify_ID,
            Lup_AC_Discount_Categories_ID,
            Credit_Limit,
            Slu_AW_Credit_Terms_ID,
            Sys_AC_Credit_Term_Types_ID,
            Sys_AC_Account_Types_ID,
            Credit_Insurers_Reference,
            Credit_Insurers_Limit,
            AW_YesNo_Charge_Interest_ID,
            Slu_AW_Controllers_ID,
            Lup_AS_Reps_ID,
            Lup_AC_Sales_Areas_ID,
            Slu_AW_Countries_ID,
            Cell_No,
            Home_Tel_No,
            Work_Tel_No,
            Fax_No,
            Web_Site_URL,
            Principal_Name,
            Principal_Firstname,
            Principal_Birthday,
            Principal_Contact_Method_ID,
            Principal_Cell_No,
            Orders_URL,
            Home_Email,
            Work_Email,
            Start_Date,
            Sys_AW_Tax_Codes_ID,
            Tax_Number,
            Notes,
            Account_Balance,
            Current_Balance,
            Days_30,
            Days_60,
            Days_90,
            Days_120,
            Days_150,
            Days_180,
            Sys_AW_Delivery_Methods_ID,
            Sys_AC_Use_Assets_ID,
            AW_YesNo_Send_Email_ID,
            Default_Settlement_Discount,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
        )
	SELECT
        Surname,
        Firstnames,
        Initials,
        Slu_AW_Titles_ID,
        Contact_Name,
        Slu_AW_Languages_ID,
        IDReg_Number,
        Customer_Number,
        Old_Customer_Number,
        Post_Box,
        Post_Office,
        Post_Code,
        Street_Address,
        Suburb,
        City,
        Street_Post_Code,
        Delivery_Address,
        Delivery_Suburb,
        Delivery_City,
        Delivery_Post_Code,
        Head_Office,
        Lup_AC_Customer_Types_ID,
        Lup_AC_Customer_Groups_ID,
        Sys_AC_Account_Status_ID,
        AW_YesNo_Pre_Notify_ID,
        AW_YesNo_Post_Notify_ID,
        Lup_AC_Discount_Categories_ID,
        Credit_Limit,
        Slu_AW_Credit_Terms_ID,
        Sys_AC_Credit_Term_Types_ID,
        Sys_AC_Account_Types_ID,
        Credit_Insurers_Reference,
        Credit_Insurers_Limit,
        AW_YesNo_Charge_Interest_ID,
        Slu_AW_Controllers_ID,
        Lup_AS_Reps_ID,
        Lup_AC_Sales_Areas_ID,
        Slu_AW_Countries_ID,
        Cell_No,
        Home_Tel_No,
        Work_Tel_No,
        Fax_No,
        Web_Site_URL,
        Principal_Name,
        Principal_Firstname,
        Principal_Birthday,
        Principal_Contact_Method_ID,
        Principal_Cell_No,
        Orders_URL,
        Home_Email,
        Work_Email,
        Start_Date,
        Sys_AW_Tax_Codes_ID,
        Tax_Number,
        Notes,
        Account_Balance,
        Current_Balance,
        Days_30,
        Days_60,
        Days_90,
        Days_120,
        Days_150,
        Days_180,
        Sys_AW_Delivery_Methods_ID,
        Sys_AC_Use_Assets_ID,
        AW_YesNo_Send_Email_ID,
        Default_Settlement_Discount,
        getdate(),
        @UserID,
        @CompanyID
	FROM AC_Prospects 
	WHERE AC_Prospects_ID = @ProspectID AND
	      AW_User_Companies_ID = @CompanyID



    SELECT @ReturnCode = scope_identity()

    --> DELETE the Prospect after transfer
    IF @ReturnCode > 0
        BEGIN
            DELETE
            FROM AC_Prospects
        	WHERE AC_Prospects_ID = @ProspectID AND
        	      AW_User_Companies_ID = @CompanyID
        END


RETURN @ReturnCode 



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AC_Insert_Prospect_Message_Log
--Purpose       :INSERT a message via the messaging system
--Date			:2006/03/29
--Authors		:TB
--MODS    		:
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Insert_Prospect_Message_Log
	(
		@CompanyID int,
        @ActorID int,
        @ActorTypeID int,
        @MessageID int,
        @Message varchar(500),
        @SeverityLevelID tinyint,
        @MessageTypeID smallint,
        @DeliveryMethodID tinyint,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)

    INSERT Log_AC_Prospect_Messages
        (
            Actor_ID,
            Sys_AT_Actor_Types_ID,
            AW_Messages_ID,
            Message,
            Sys_AC_Severity_Levels_ID,
            Sys_AC_Message_Types_ID,
            Sys_AW_Delivery_Methods_ID,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @ActorID,
            @ActorTypeID,
            @MessageID,
            @Message,
            @SeverityLevelID,
            @MessageTypeID,
            @DeliveryMethodID,
            getdate(),
            @UserID,
    		@CompanyID
        )


    SELECT @ReturnCode = scope_identity()

    RETURN @ReturnCode 


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AC_Reverse_Payment
--Purpose       :Reverses a Customer Payment
--Date          :2005/09/23
--Authors       :TB
--MODS          :30/11/05 - Removed REVERSING SIGN of Allocated Amount when Resetting
--              :           the SOURCE (ORIGINAL) transaction to its pre-payment state
--              :           and Add back the payment to the Customer's Account Balance
--2004.2.6      :18/01/06 - Fixed to DEDUCT @Allocated value in cursor to Reset the
--              :           SOURCE (ORIGINAL) transaction to its pre-payment state
--2004.3.5      :29/05/07 - Added @PaymentTypeID parameter to seperate POS (Type 7)
--              :           Payment Reversals because Amount for this type is POSITIVE
--              :           while others are NEGATIVE in AS_Transactions_Transactions
--              :29/05/07 - Moved UPDATE the Customer's Account Balance to END of
--              :           procedure using SUM(Transaction Totals)
--2004.3.8      :23/03/08 - Removed assign TranType(ABS(Amount)) when reversing payment
--              :           This code has POTENTIAL FOR ERROR as JOURNALS and PAYMENTS
--              :           can potentially be NEGATIVE OR POSITIVE
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AC_Reverse_Payment
    (
        @PaymentID int,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @CustomerID int,
            @SourceTranID int,
            @Allocated money,
            @TranNo varchar(19),
            @TranDate datetime,
    		@Amount money,
    		@Payment money,
    		@Discount money,
            @TotalAmount money,
    		@Date datetime,
    		@Comment varchar(20),
    		@DateCaptured DateTime,
    		@TranTypeID int,
            @SettTranID int,
            @SettCustID int,
            @SettTranNo varchar(19),
            @SettTranDate datetime,
            @SettDiscount money,
            @SettTotalAmount money,
            @SettPayment money,
            @SettAmount money,
            @SettTypeID int,
            @AccountBalance money,
            @ReturnCode int


    SET @ReturnCode = 0        -- 0 = FAIL, 1 = SUCCEED 
    SET @CustomerID = 0


    SELECT @CustomerID = AC_Customers_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @PaymentID


    IF @CustomerID = 0 OR @CustomerID IS NULL
        BEGIN
            RETURN @ReturnCode
        END


    -----------------------------------------------------------
    BEGIN TRAN Reverse_Payment
    -----------------------------------------------------------


        BEGIN

        -----------------------------------------------------------
        --> Define a CURSOR for Customer Payment Tran
        --           Uses DISTINCT to select only unique rows
        -----------------------------------------------------------
        	DECLARE Payment_Cursor CURSOR FOR
                (
                    SELECT DISTINCT
                                t.Sys_AW_Transaction_Types_ID,
                                st.Source_AS_Transactions_ID,
                                st.Amount
                    FROM AS_Transactions_Transactions st
                        LEFT JOIN AS_Transactions t
                            ON st.Destination_AS_Transactions_ID = t.AS_Transactions_ID
                    WHERE st.AW_User_Companies_ID = @CompanyID AND
                          st.Destination_AS_Transactions_ID = @PaymentID
                )
        
        	OPEN Payment_Cursor
        
            	FETCH NEXT FROM Payment_Cursor 
            	INTO
                    @TranTypeID,
                    @SourceTranID,
                    @Allocated
            	
            	WHILE @@FETCH_STATUS = 0
            	BEGIN

--                     -----------------------------------------------------------
--                     COMMENTED 2004.3.8
--                     -----------------------------------------------------------
--                     NB NB - This code has POTENTIAL FOR ERROR as JOURNALS and
--                             PAYMENTS can potentially be NEGATIVE OR POSITIVE
--                     -----------------------------------------------------------
--                     -----------------------------------------------------------
--                     SET @Allocated = ABS(@Allocated)
-- 
--                     -----------------------------------------------------------
--                     --Reset the ALLOCATED transaction to its pre-payment state
--                     -----------------------------------------------------------
--                     IF @TranTypeID = 7 OR @TranTypeID = 21 OR @TranTypeID = 22
--                         BEGIN
--                             UPDATE AS_Transactions
--                             SET Payment_Amount = Payment_Amount + @Allocated
--                             WHERE AS_Transactions_ID = @SourceTranID
--                         END
--                     ELSE
--                     IF @TranTypeID = 3 OR @TranTypeID = 4 OR @TranTypeID = 5 OR @TranTypeID = 15 OR @TranTypeID = 18
--                         BEGIN
--                             UPDATE AS_Transactions
--                             SET Payment_Amount = Payment_Amount - @Allocated
--                             WHERE AS_Transactions_ID = @SourceTranID
--                         END
--                     -----------------------------------------------------------

                        UPDATE AS_Transactions
                        SET Payment_Amount = Payment_Amount - @Allocated
                        WHERE AS_Transactions_ID = @SourceTranID
                    -----------------------------------------------------------


                	FETCH NEXT FROM Payment_Cursor 
                	INTO
                        @TranTypeID,
                        @SourceTranID,
                        @Allocated
        
            	END
        	
        	CLOSE Payment_Cursor
        
        	DEALLOCATE Payment_Cursor

            SET @TranTypeID = 0


            -----------------------------------------------------------
            --> INSERT a REVERSAL PAYMENT into AS_Transactions to be
            --  included in the next DAY-END to UPDATE Trade Debtors.
            --  The REVERSED PAYMENT will be inserted in Trade Debtors Payment Clearing
            --  and the CASH BOOK UNPAID CHEQUE must be journalised there
            -----------------------------------------------------------
            SELECT @CustomerID = AC_Customers_ID,
                   @TranNo = Transaction_Number,
                   @TranDate = Transaction_Date,
                   @Discount = Total_Discount_Amount,
                   @TotalAmount = Total_Amount * -1,
                   @Payment = Payment_Amount * -1,
                   @Amount = Amount * -1,
                   @TranTypeID = Sys_AW_Transaction_Types_ID
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @PaymentID


            SET @Comment = LEFT('REVERSAL of ' + ISNULL(@TranNo, ''), 20)
            SET @Date = getdate()


    		INSERT AS_Transactions 
    			(	
                    AC_Customers_ID,
                    Transaction_Number,
                    Total_Discount_Amount,	
                    Total_Amount,
                    Payment_Amount,
                    Amount, 
                    Transaction_Date,
                    Comment,								
                    Sys_AW_Transaction_Types_ID,
                    Lup_AS_Cashiers_ID,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
    			)
    		VALUES
    			(
                    @CustomerID,
                    @TranNo,
                    @Discount,
                    @Amount,              --Reverse the original Total_Amount
                    @Payment,
                    @Amount,              --Reverse the original Amount
                    @Date, 
                    @Comment,
                    @TranTypeID,
                    @UserID,
                    @Date,
                    @UserID, 
                    @CompanyID
    			)
		

            -----------------------------------------------------------
            --> CHECK if a SETTLEMENT DISCOUNT transaction was inserted
            -----------------------------------------------------------
            SELECT @SettTranID = AS_Transactions_ID,
                   @SettCustID = AC_Customers_ID,
                   @SettTranNo = Transaction_Number,
                   @SettTranDate = Transaction_Date,
                   @SettDiscount = Total_Discount_Amount,
                   @SettTotalAmount = Total_Amount * -1,
                   @SettPayment = Payment_Amount * -1,
                   @SettAmount = Amount * -1,
                   @SettTypeID = Sys_AW_Transaction_Types_ID
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @PaymentID + 1

            -----------------------------------------------------------
            --> If a SETTLEMENT DISCOUNT transaction exists, REVERSE it
            -----------------------------------------------------------
            IF @SettCustID = @CustomerID AND
               @SettTypeID = 18 AND
               @SettTranNo = CONVERT(varchar(19), (CONVERT(int, @TranNo) + 1)) AND
               @SettTranDate = @TranDate
                BEGIN
                    SET @Comment = LEFT('REVERSAL of ' + ISNULL(@SettTranNo, ''), 20)
                    SET @Date = getdate()
        
        
            		INSERT AS_Transactions 
            			(	
                            AC_Customers_ID,
                            Transaction_Number,
                            Total_Discount_Amount,	
                            Total_Amount,
                            Payment_Amount,
                            Amount, 
                            Transaction_Date,
                            Comment,								
                            Sys_AW_Transaction_Types_ID,
                            Lup_AS_Cashiers_ID,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID
            			)
            		VALUES
            			(
                            @SettCustID,
                            @SettTranNo,
                            @SettDiscount,
                            @SettTotalAmount,       --Reverse the original Total_Amount
                            @SettPayment,
                            @SettAmount,            --Reverse the original Amount
                            @Date, 
                            @Comment,
                            @SettTypeID,
                            @UserID,
                            @Date,
                            @UserID, 
                            @CompanyID
            			)

                END
            -----------------------------------------------------------


            -----------------------------------------------------------
            -- UPDATE the Customer's Account Balance
            -----------------------------------------------------------
            SELECT @AccountBalance = SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0))
            FROM AS_Transactions
            WHERE AC_Customers_ID = @CustomerID AND
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

        	UPDATE AC_Customers
            SET Account_Balance = @AccountBalance
            WHERE AC_Customers_ID = @CustomerID
            -----------------------------------------------------------


            -----------------------------------------------------------
            -- DELETE the PAYMENT ALLOCATIONS
            -----------------------------------------------------------
            DELETE
            FROM AS_Transactions_Transactions
            WHERE Destination_AS_Transactions_ID = @PaymentID AND
                  AW_User_Companies_ID = @CompanyID
    
    
            DELETE
            FROM AS_Transaction_Payments
            WHERE AS_Transactions_ID = @PaymentID AND
                  AW_User_Companies_ID = @CompanyID
    

            SET @ReturnCode = 1


        END


    -----------------------------------------------------------
    COMMIT TRAN Reverse_Payment
    -----------------------------------------------------------


    RETURN @ReturnCode



SET NOCOUNT OFF




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















--------------------------------------------------------------------------------
--Description   :sp_AC_Select_Billing_Customers_Extended
--Purpose       :Returns all Customer as a Lookup PLUS street address and
--              :Accounts E-Mail address (Orders_URL) for Periodic Billing
--Date          :2010/11/16
--Authors       :TB
--MODS          :
--------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Select_Billing_Customers_Extended
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT c.AC_Customers_ID AS [CustomerID],
    	   ISNULL(c.Surname, '') +
           ISNULL(', ' + c.Firstnames, '') +
           ISNULL(', ' + c.Street_Address, '') +
           ISNULL(', ' + c.Suburb, '') +
           ISNULL(', ' + c.City, '') AS [Customer],
           ISNULL(c.Orders_URL, '') AS [E-Mail],
           ISNULL(tc.Tax_Rate, 0) AS [CustTaxRate]
    FROM AC_Customers c
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
    WHERE c.AW_User_Companies_ID = @CompanyID AND
          c.Slu_AW_Active_ID = 1
    ORDER BY [Customer]


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_Select_CBilling_Lups
--Purpose       :Central Billing Look-ups
--Date          :2004/03/01
--Authors       :TB
--Version       :1.0.0
--MODS          :04/03/04 - Added Server, User and Password to Lup_AS_CBilling_Types
--              :09/03/04 - Added Claim Codes from Lup_AP_Claim_Codes
--              :27/09/05 - Added WHERE Active Lup_AS_CBilling_Providers validation
--              :27/09/05 - Changed SORT ORDER to default to Lup_AS_CBilling_Providers_ID
--              :07/03/06 - Added @CompanyID input parameter
--              :07/03/06 - Added CBilling Customers as LUP
--2004.4.5      :19/06/09 - Added [Folder] column to Lup_AS_CBilling_Providers
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AC_Select_CBilling_Lups
    (
        @Option tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON
    
        --Users
        IF @Option = 1
          	SELECT AW_Users_ID as [ID],
                   Surname + ISNULL(', ' + FirstName, '') AS [User]
            FROM AW_Users
            ORDER BY [User]
    
        --Fail Reasons
        ELSE
        IF @Option = 2
            SELECT Lup_AP_Fail_Reasons_ID as [ID],
                   [Description],
                   [Code]
            FROM Lup_AP_Fail_Reasons
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Lup_AP_Fail_Reasons_ID
    
        --Billing Providers
        ELSE
        IF @Option = 3
        	SELECT Lup_AS_CBilling_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_CBilling_Providers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [ID]

        --Transaction Types
        ELSE
        IF @Option = 4
            SELECT Sys_AW_Transaction_Types_ID as [ID],
                  [Description]
            FROM Sys_AW_Transaction_Types
            WHERE Sys_AW_Transaction_Types_ID = 3 or
                  Sys_AW_Transaction_Types_ID = 4

        --Claim Codes
        ELSE
        IF @Option = 5
            SELECT Lup_AP_Claim_Codes_ID as [ID],
                   [Description],
                   [Code]
            FROM Lup_AP_Claim_Codes
--            ORDER BY Lup_AP_Claim_Codes_ID


        --CBilling Customers as LUP
        ELSE
        IF @Option = 6
            SELECT AC_Customers_ID AS [ID],
            	   ISNULL(Surname, '') + ISNULL(', ' + Firstnames, '') AS [Customer]
            FROM AC_Customers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AC_Account_Types_ID = 4
            ORDER BY [Customer]



SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Select_CBilling_Submission
--Functionality :Select UNSUBMITTED Centralised Billing transactions
--Parameters    :
--Date          :2004/03/02
--Authors       :TB
--Version       :1.0.0.
--MODS          :09/03/04 - Added [Claim Code] from new Lup_AP_Claim_Codes_ID
--              :16/08/04 - Added Original_Number [Original No*] field - K Slabbert 5 AUG
--              :17/01/05 - Added Sys_AW_Transaction_Types_ID AS [TranTypeID]
--              :           to validate [Original No*] for refunds ONLY
--              :27/09/05 - Added append double asterisk(**) for SQ Central Sales
--              :29/09/05 - Removed superfluous @ProviderID from WHERE filter
--              :           to enable setting DEFAULT provider in UI
-------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AC_Select_CBilling_Submission
    (
        @ProviderID smallint,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     AS_Transactions_CBilling_ID AS [ID], '
    SET @sql = @sql + '     AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + '     Lup_AS_CBilling_Providers_ID AS [Provider*], '
    SET @sql = @sql + '     Customer_Number AS [Customer No*], '
    SET @sql = @sql + '     Network_Identity_Number AS [Our No*], '
    SET @sql = @sql + '     Transaction_Number AS [Number*], '
    SET @sql = @sql + '     Original_Number AS [Original No*], '
    SET @sql = @sql + '     Manufacturer_Code AS [Manuf Code*], '
    SET @sql = @sql + '     Quantity AS [Qty*], '
    SET @sql = @sql + '     Discount_Amount AS [Discount*], '
    SET @sql = @sql + '     Tax_Amount AS [Tax*], '
    SET @sql = @sql + '     Extended_Amount AS [Total*], '
    SET @sql = @sql + '     Lup_AP_Fail_Reasons_ID AS [Reason*], '
    SET @sql = @sql + '     Item_No AS [Item*], '
    SET @sql = @sql + '     Authorization_No AS [Auth No*], '
    SET @sql = @sql + '     Registration_No AS [Reg No*], '
    SET @sql = @sql + '     Odometer_Reading AS [Odometer*], '
    SET @sql = @sql + '     Sys_AW_Transaction_Types_ID AS [Type], '
    SET @sql = @sql + '     Transaction_Date AS [Date*], '
    SET @sql = @sql + '     Lup_AP_Claim_Codes_ID AS [Claim Code*], '
    SET @sql = @sql + '     Make AS [Make**], '
    SET @sql = @sql + '     Model AS [Model**], '
    SET @sql = @sql + '     Model_Year AS [Year**], '
    SET @sql = @sql + '     Client_ID_No AS [Customer ID No***], '
    SET @sql = @sql + '     Engine_No AS [EngineNo**], '
    SET @sql = @sql + '     Chassis_No AS [Chassis No**], '
    SET @sql = @sql + '     Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     [User_ID] AS [User], '
    SET @sql = @sql + '     Sys_AW_Transaction_Types_ID AS [TranTypeID] '

    SET @sql = @sql + ' FROM AS_Transactions_CBilling '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--    SET @sql = @sql + '       Lup_AS_CBilling_Providers_ID = ' + CONVERT(varchar(10), @ProviderID) + ' AND '
    SET @sql = @sql + '       Xmit_Date IS NULL '

    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '      AND Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '      AND Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY [Provider*], [Date*] ASC '


    EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AC_Select_CBilling_Temp
--Functionality :SELECT Centralised Sales transactions
--Parameters    :
--Date          :2005/10/03
--Authors       :TB
--MODS          :
--2004.5.8 RGL 2013-02-20 : Added distinct to select to remove duplicate
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Select_CBilling_Temp]
    (
        @CompanyID int
    )
AS

SET NOCOUNT ON

-- DECLARE @CompanyID int

-- SET @CompanyID = 1
    
    SELECT
		Distinct
        AS_Transactions_ID,
        Lup_AS_CBilling_Providers_ID,
        cat_code,
        drs_acc,
        trs_ref,
        trs_date,
        qty,
        amount,
        gls_acc,
        narr,
        stock_group,
        drs_apply,
        sys_code,
        updated,
        interfaced,
        drs_age_month,
        stock_code,
        area,
        drs_alpha,
        branch,
        vat_amount,
        cost_amount,
        rep_comm,
        process_type,
        rep_code,
        acct_type,
        disc_amnt,
        std_sell_price,
        drs_trs_code,
        trs_type,
        acc_month,
        acc_year,
        con_acct_no,
        zz_int01,
        cntno,
        line_disc1,
        line_disc2,
        stock_sell1,
        no_of_deals,
        zz_date01,
        zz_date02,
        zz_date03,
        special_instr,
        deals_flag,
        deals_number,
        vat_exempt_member,
        cmonth,
        cyear,
        rep_call_status,
        drsdiv_code,
        crs_acc,
        creation_date,
        creation_time,
        creation_userid,
        creation_proc,
        item_number,
        rep_code2,
        qty2,
        deposit_amount,
        job_number,
        line_disc_amnt,
        carhire_cntno,
        currency,
        exch_rate,
        cyear_month,
        zz_date04,
        zz_date05,
        zz_int02,
        zz_int03,
        zz_int04,
        zz_int05,
        zz_dec01,
        zz_dec02,
        zz_dec03,
        zz_dec04,
        zz_dec05,
        zz_log01,
        zz_log02,
        zz_log03,
        zz_log04,
        zz_log05,
        zz_log06,
        zz_log07,
        zz_char01,
        zz_char02,
        zz_char03,
        zz_char04,
        zz_char05,
        key_glstrs,
        key_history,
        dumped,
        company_name,
        branch_name,
        drs_name,
        crs_name,
        prd_grp_descr,
        stk_descry,
        status_ind,
        customer_ref,
        comments1,
        comments2,
        comments3,
        comments4,
        comments5,
        comments6,
        comments7,
        comments8,
        database_id,
        system_id,
        vat_reg_no,
        email,
        customer_cell_number,
        customer_email_address,
        Date_Captured,
        User_ID,
        AW_User_Companies_ID,
        Slu_AW_Active_ID
    FROM AS_Transactions_CBilling_Temp
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY AS_Transactions_ID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Select_CSales_Submission
--Functionality :Select UNSUBMITTED Centralised Sales (Billing) transactions
--Parameters    :
--Date          :2005/10/03
--Authors       :TB
--Version       :1.0.0.
--MODS          :09/03/04 - Added [Claim Code] from new Lup_AP_Claim_Codes_ID
--              :16/08/04 - Added Original_Number [Original No*] field - K Slabbert 5 AUG
--              :17/01/05 - Added Sys_AW_Transaction_Types_ID AS [TranTypeID]
--              :           to validate [Original No*] for refunds ONLY
--              :27/09/05 - Added append double asterisk(**) for SQ Central Sales
--              :29/09/05 - Removed superfluous @ProviderID from WHERE filter
--              :           to enable setting DEFAULT provider in UI
--              :03/10/05 - Removed superfluous @ChkDates, @StartDate and @EndDate
--              :           from WHERE filter to enable fetch ALL unsubmitted
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Select_CSales_Submission
    (
--        @ProviderID smallint,
--        @ChkDates int,
--        @StartDate datetime,
--        @EndDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     AS_Transactions_CBilling_ID AS [ID], '
    SET @sql = @sql + '     AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + '     Lup_AS_CBilling_Providers_ID AS [Provider*], '
    SET @sql = @sql + '     Customer_Number AS [Customer No*], '
    SET @sql = @sql + '     Network_Identity_Number AS [Our No*], '
    SET @sql = @sql + '     Transaction_Number AS [Number*], '
    SET @sql = @sql + '     Original_Number AS [Original No*], '
    SET @sql = @sql + '     Manufacturer_Code AS [Manuf Code*], '
    SET @sql = @sql + '     Quantity AS [Qty*], '
    SET @sql = @sql + '     Discount_Amount AS [Discount*], '
    SET @sql = @sql + '     Tax_Amount AS [Tax*], '
    SET @sql = @sql + '     Extended_Amount AS [Total*], '
    SET @sql = @sql + '     Lup_AP_Fail_Reasons_ID AS [Reason*], '
    SET @sql = @sql + '     Item_No AS [Item*], '
    SET @sql = @sql + '     Authorization_No AS [Auth No*], '
    SET @sql = @sql + '     Registration_No AS [Reg No*], '
    SET @sql = @sql + '     Odometer_Reading AS [Odometer*], '
    SET @sql = @sql + '     Sys_AW_Transaction_Types_ID AS [Type], '
    SET @sql = @sql + '     Transaction_Date AS [Date*], '
    SET @sql = @sql + '     Lup_AP_Claim_Codes_ID AS [Claim Code*], '
    SET @sql = @sql + '     Make AS [Make**], '
    SET @sql = @sql + '     Model AS [Model**], '
    SET @sql = @sql + '     Model_Year AS [Year**], '
    SET @sql = @sql + '     Client_ID_No AS [Customer ID No***], '
    SET @sql = @sql + '     Engine_No AS [EngineNo**], '
    SET @sql = @sql + '     Chassis_No AS [Chassis No**], '
    SET @sql = @sql + '     Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     [User_ID] AS [User], '
    SET @sql = @sql + '     Sys_AW_Transaction_Types_ID AS [TranTypeID] '

    SET @sql = @sql + ' FROM AS_Transactions_CBilling '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--    SET @sql = @sql + '       Lup_AS_CBilling_Providers_ID = ' + CONVERT(varchar(10), @ProviderID) + ' AND '
    SET @sql = @sql + '       Xmit_Date IS NULL '


--     IF @ChkDates = 1    --From/To Dates
--         BEGIN
--             SET @sql = @sql + '      AND Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
--             SET @sql = @sql + '      AND Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
--         END


    SET @sql = @sql + ' ORDER BY [Provider*], [Date*] ASC '


    EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AC_Select_Consignment_Customers
--Purpose       :Select all Customers that had or has had consignment stock
--Functionality :
--Parameters    :
--Date          :2015-05-20
--Authors       :RL
------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AC_Select_Consignment_Customers]
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Distinct c.AC_Customers_ID AS [ID],
		   ISNULL(Surname,'') + ISNULL(', ' + Firstnames,'') AS [Customer],
           ISNULL(Customer_Number, '') AS [Cust No],
           Sys_AC_Account_Types_ID AS [Account_Type]
	FROM AC_Customers c
		INNER JOIN AS_Transactions t
			ON c.AC_Customers_ID = t.AC_Customers_ID
		INNER JOIN AS_Transaction_Details d
			ON t.AS_Transactions_ID = d.AS_Transactions_ID
	WHERE c.AW_User_Companies_ID = @Company_ID
	AND t.Sys_AW_Transaction_Types_ID = 33
	AND d.Quantity 	- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
	ORDER BY [Customer] ASC

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Catalog
--Purpose       :Retrieves the customer catalog data
--Functionality :Select 
--Parameters    :
--Date          :2001/12/05
--Authors       :TB
--MODS          :03/01/04 - Added 9 fields including Controller, Pre/Post Notify
--              :           Delivery Method, and Principal for Credit Manager
--              :19/06/04 - Added new [Send Email] field
--              :05/07/04 - Added new [Customer_Group] field
--              :03/02/05 - Added new [SettleDisc] field
--2004.3.2      :11/10/06 - Added new [NetBilling] and [PurchaseOrder] fields
--2004.4.0      :24/07/07 - Added new [CostPlusBilling] field
--              :25/07/07 - Added new [CostPlusCategory] field
--2004.4.5      :13/06/09 - Added new [OverrideLimit] and [OverrideOverdue] field
--2004.5.2      :03/06/11 - Added new AW_YesNo_Attach_Tran_ID AS [Attach Docs]
--2004.4.9 RL   :2013-07-08 - Added AW_YesNo_Apply_Product_Levy
--RL	V6.0	:2014-04-21 - Added Automatically email documnets fields
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Select_Customer_Catalog]
    (
        @CustomerID int,
        @CompanyID int 
    )
AS

SET NOCOUNT ON

SELECT
        AC_Customers_ID AS [ID], 
        Surname AS [Name], 
        Firstnames AS [First Names], 
        Initials AS [Initials], 
        Slu_AW_Titles_ID AS Title, 
        Slu_AW_Languages_ID AS Language, 
        IDReg_Number AS [ID/Reg No], 
        Start_Date AS [Start Date], 
        Customer_Number AS [Customer No], 
        Old_Customer_Number AS [Old Customer No], 
        Head_Office AS [Head Office], 
        Lup_AC_Customer_Types_ID AS [Customer_Type], 
        Lup_AC_Customer_Groups_ID AS [Customer_Group], 
        Sys_AC_Use_Assets_ID AS [Use Assets],
        Sys_AW_Delivery_Methods_ID AS [Method],
        Sys_AW_Tax_Codes_ID AS [Tax Code], 
        Tax_Number AS [Tax Number],
        Notes, 
        Lup_AC_Discount_Categories_ID AS [Sales Discount], 
        Credit_Limit AS [Credit Limit], 
        Slu_AW_Credit_Terms_ID AS [Credit Terms], 
        Sys_AC_Credit_Term_Types_ID AS [Credit Term Types],
        Credit_Insurers_Reference AS [Credit Insurers Ref],
        Credit_Insurers_Limit AS [Credit Insurers Limit],
        AW_YesNo_Charge_Interest_ID AS [Charge Interest],
        Slu_AW_Controllers_ID AS [Controller], 
        AW_YesNo_Pre_Notify_ID AS [PreNotify], 
        AW_YesNo_Post_Notify_ID AS [PostNotify], 
        Lup_AS_Reps_ID AS Salesperson, 
        Lup_AC_Sales_Areas_ID AS [Sales Areas], 
        Contact_Name AS [Contact Name], 
        Sys_AC_Account_Types_ID AS [Account Types],
        Sys_AC_Account_Status_ID AS [Account Status],
        Slu_AW_Active_ID AS Active, 
        Post_Box AS [Post Box], 
        Post_Office AS [Post Office], 
        Post_Code AS [Post Code], 
        Street_Address AS [Street Address], 
        Suburb AS [Suburb], 
        City AS [City], 
        Street_Post_Code AS [Street Code], 
        Delivery_Address AS [Delivery Address], 
        Delivery_Suburb AS [Delivery Suburb], 
        Delivery_City AS [Delivery City], 
        Delivery_Post_Code AS [Delivery Post Code], 
        Slu_AW_Countries_ID AS [Country], 
        Home_Tel_No AS [Home Tel No], 
        Work_Tel_No AS [Work Tel No], 
        Cell_No AS [Cell No], 
        Fax_No AS [Fax No], 
        Principal_Name AS [Principal Name],
        Principal_Firstname AS [Principal Firstname],
        Principal_Birthday AS [Principal Birthday],
        Principal_Contact_Method_ID AS [PrincipalMethod],
        Principal_Cell_No AS [PrincipalCellNo],
        Web_Site_URL AS [Web Site URL], 
        Orders_URL AS [Order URL], 
        Home_Email AS [E-mail Home], 
        Work_Email AS [E-mail Work], 
        Account_Balance AS [Account Balance],
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company ID],
        AW_YesNo_Send_Email_ID AS [Send Email],
        AW_YesNo_Attach_Tran_ID AS [Attach Docs],
        Default_Settlement_Discount AS [SettleDisc],
        AW_YesNo_Net_Billing_ID AS [NetBilling], 
        AW_YesNo_Purchase_Order_ID AS [PurchaseOrder],
        AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling],
        Lup_AC_Markup_Categories_ID AS [CostPlusCategory],
        AW_YesNo_Override_Credit_Limit AS [OverrideLimit],
        AW_YesNo_Override_Overdue AS [OverrideOverdue],
        AW_YesNo_Apply_Product_Levy As [Apply_Product_Levy],
        AW_YesNo_Change_Doc_Details As [Change_Doc_Details],
	Slu_AC_Documents_ID_Invoice As [Invoice_Document],    
	Invoice_Printer As [Invoice_Printer],
	Invoice_Email As [Invoice_Email],
	AW_YesNo_Invoice_TCS As [Invoice_TCS],
	Slu_AC_Documents_ID_Quote As [Quote_Document],
	Quote_Printer As [Quote_Printer],
	Quote_Email As [Quote_Email],
	AW_YesNo_Quote_TCS As [Quote_TCS]        
FROM AC_Customers 
WHERE AC_Customers_ID = @CustomerID AND
      AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Document
--Purpose       :Retrieves the customer email document details
--Functionality :Select 
--Parameters    :
--Date          :2014/04/21
--Authors       :RL
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Select_Customer_Document]
    (
        @CustomerID int,
        @TransactionID int
    )
AS

SET NOCOUNT ON

	Declare @DocNo	Varchar(20)
	Declare @Comapny_Email	Varchar(80)

	Set @DocNo = ''
	Set @Comapny_Email = ''
	
	Select @DocNo = Transaction_Number
	From AS_Transactions
	Where AS_Transactions_ID = @TransactionID

	SELECT TOP 1 @Comapny_Email = ISNULL(E_Mail, '')
	FROM AW_User_Companies

	SELECT
        i.Document_Layout As [Invoice_Document_Layout],
		i.DLL_Name As [Invoice_DLL],
		i.DLL_Name + '.' + i.Class_Module As [Invoice_Class_Module],		
		Invoice_Printer As [Invoice_Printer],
		Invoice_Email As [Invoice_Email],
		AW_YesNo_Invoice_TCS As [Invoice_TCS],
		
        q.Document_Layout As [Quote_Document_Layout],
		q.DLL_Name As [Quote_DLL],
		q.DLL_Name + '.' + Q.Class_Module As [Quote_Class_Module],			
		Quote_Printer As [Quote_Printer],
		Quote_Email As [Quote_Email],
		AW_YesNo_Quote_TCS As [Quote_TCS],
		
		@DocNo As [DocNo],
		@Comapny_Email As [Comapny_Email]        
	FROM AC_Customers c
	LEFT OUTER JOIN Slu_AC_Documents i
		ON c.Slu_AC_Documents_ID_Invoice = i.Slu_AC_Documents_ID
	LEFT OUTER JOIN Slu_AC_Documents q
		ON c.Slu_AC_Documents_ID_Quote = q.Slu_AC_Documents_ID	
	WHERE AC_Customers_ID = @CustomerID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Edit_Transactions
--Purpose       :Selects Customer Transactions to Edit
--Date          :2004/04/07
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_Customer_Edit_Transactions
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime 
	)

AS

SET NOCOUNT ON

--> Specific Transaction Type
    IF @TransactionTypeID <> 0
        SELECT
            AS_Transactions_ID AS [TranID],
            AC_Customers_ID AS [CustomerID],
            Sys_AW_Transaction_Types_ID AS [Transaction Type],
            Transaction_Date AS [Date],
            Transaction_Number AS [Ref No],
            Amount AS [Amount],
            Total_Discount_Amount AS [Discount],
            Total_Tax_Amount AS [VAT],
            Total_Amount AS [Total],
            Payment_Amount AS [Payment],
            Comment AS [Comment],
            [User_ID] AS [User]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
              Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
             (DATEDIFF(d, Transaction_Date, @StartDate) <= 0 AND
              DATEDIFF(d, Transaction_Date, @EndDate) >= 0)
        ORDER BY Transaction_Date DESC

--> ALL Transaction Types
    ELSE
        SELECT
            AS_Transactions_ID AS [TranID],
            AC_Customers_ID AS [CustomerID],
            Sys_AW_Transaction_Types_ID AS [Transaction Type],
            Transaction_Date AS [Date],
            Transaction_Number AS [Ref No],
            Amount AS [Amount],
            Total_Discount_Amount AS [Discount],
            Total_Tax_Amount AS [VAT],
            Total_Amount AS [Total],
            Payment_Amount AS [Payment],
            Comment AS [Comment],
            [User_ID] AS [User]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
             (Sys_AW_Transaction_Types_ID = 3 OR
              Sys_AW_Transaction_Types_ID = 4 OR
              Sys_AW_Transaction_Types_ID = 5 OR
              Sys_AW_Transaction_Types_ID = 7 OR
              Sys_AW_Transaction_Types_ID = 15 OR
              Sys_AW_Transaction_Types_ID = 18 OR
              Sys_AW_Transaction_Types_ID = 21 OR
              Sys_AW_Transaction_Types_ID = 22) AND
             (DATEDIFF(d, Transaction_Date, @StartDate) <= 0 AND
              DATEDIFF(d, Transaction_Date, @EndDate) >= 0)
        ORDER BY Transaction_Date DESC

SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_History
--Purpose       : 
--Functionality : 
--REQUIRED in UI:CustomerID, UserID, CompanyID
--Date          :2003/03/30
--Authors       :TB
--Version       :1.0.0
--MODS          :17/05/03 - Commented all references to AW_Users JOIN which causes
--              :           a run-time error 'Insufficient key column information
--              :           for updating or refreshing' when updating rs in the UI.
--              :           This is caused by a confirmed ADO bug (Q246905)
--              :11/09/03 - Modified [Financing Costs] alias stated as [Statement Date]
--              :           in option 19 Income Statement
--              :27/10/03 - Added 4 new Bank Code columns to AC_History_Bankers
--              :15/07/04 - Changed ORDER BY from [Date_Changed] to [Date_Captured]
--              :           in @Option = 0 (Account Status) for update of lastest
--              :           setting to Account Status on Tab 0 of Customer Catalog
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_Customer_History
    (
        @Option tinyint,
    	@Company_ID int,
    	@Customer_ID int,
        @PrincipalID int
    )

AS

--EXEC sp_AC_Select_Customer_History 0, 2, 567, 0

SET NOCOUNT ON

----------------------------------------------------------------------
    IF @Option = 0
        SELECT
            a.AC_History_Status_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],         -- REQUIRED AS IS
            a.Sys_AC_Account_Status_ID AS [Account Status], 
            a.Status_Reason AS [Reason], 
            a.Date_Changed AS [Date Changed], 
            a.Date_Captured AS [Date Captured], 
--            b.UserName AS [User],
            a.[User_ID] AS [User],                   -- REQUIRED AS IS
            a.AW_User_Companies_ID AS [CompanyID],     -- REQUIRED AS IS 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Status a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 1
        SELECT
            a.AC_History_Credit_Limits_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            a.Slu_AW_Credit_Terms_ID AS [Credit Terms], 
            a.Sys_AC_Credit_Term_Types_ID AS [Terms of Sale], 
            a.New_Limit AS [New Limit], 
            a.Limit_Reason AS [Reason], 
            a.Date_Changed AS [Date Changed], 
            a.Date_Captured AS [Date Captured], 
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Credit_Limits a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
--        ORDER BY a.Date_Changed    -- AW_Messages #7 & #8 REQUIRE latest change in FIRST ROW
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 2
        SELECT
            a.AC_History_Info_Reports_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            a.Slu_AW_Info_Report_Types_ID AS [Report Type], 
            a.Report_Date AS [Report Date], 
            a.Date_Captured AS [Date Captured], 
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Info_Reports a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Report_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 3
        SELECT
            a.AC_History_Notarial_Bonds_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            a.Slu_AC_Bond_Types_ID AS [Bond Type],
            a.Bond_Holder AS [BondHolder],
            a.Bond_Amount AS [BondAmount],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
            a.Date_Registered AS [Date Registered],
            a.Collateral_Provider AS [Collateral],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Notarial_Bonds a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 4
        SELECT
            a.AC_History_Ratings_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            a.Slu_AC_Ratings_ID AS [Rating],
            a.Rating_Notes AS [Notes],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Ratings a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 5
        SELECT
            a.AC_History_KIScores_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            a.Slu_AC_KI_Scores_ID AS [KI Score],
            a.Notes AS [Notes],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_KIScores a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 6
        SELECT
            a.AC_History_ITCScores_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            a.Slu_AC_ITC_Scores_ID AS [ITC Score],
            a.Notes AS [Notes],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_ITCScores a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 7
        SELECT
            a.AC_History_Trade_References_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Slu_AC_Security_Types_ID AS [Security Type], 
            a.Date_of_Reference AS [Date of Reference], 
            a.Supplier_Name AS [Supplier Name], 
            a.Contact_Name AS [Contact Name], 
            a.Contact_Position AS [Contact Position], 
            a.Telephone_Number AS [Tel No], 
            a.Fax_Number AS [Fax No], 
            a.Period_Known AS [Period Known], 
            a.Average_per_Month AS [Ave per Month], 
            a.Reference_Comments AS [Comments], 
            a.Highest_Amount AS [Highest Amount], 
            a.Account_Limit AS [Account Limit], 
            a.Terms_Given AS [Terms Given], 
            a.Terms_Taken AS [Terms Taken], 
            a.Current_Balance AS [Current Balance], 
            a.Days_30 AS [30 Days], 
            a.Days_60 AS [60 Days], 
            a.Days_90 AS [90 Days], 
            a.Days_120 AS [120 Days], 
            a.Days_150 AS [150 Days], 
            a.Days_180 AS [180 Days], 
            a.Past_Due_Amount AS [Past Due Amount], 
            a.Limit_Of_Guarantee AS [Limit of Guarantee], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Trade_References a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_of_Reference DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 8
        SELECT
            a.AC_History_Default_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Slu_AC_Adverse_Reasons_ID AS [Adverse Reason], 
            a.Adverse_Source AS [Adverse Source], 
            a.Date_Reported AS [Date Reported], 
            a.Dispute_Amount AS [Dispute Amount], 
            a.Days_Overdue AS [Days Overdue], 
            a.Adverse_Comments AS [Comments], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Default a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Reported DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 9
        SELECT
            a.AC_History_Motion_Roll_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Slu_AW_Nature_Of_Action_ID AS [Nature Of Action], 
            a.Slu_AW_Lawsuit_Types_ID AS [Lawsuit Type], 
            a.Slu_AW_Courts_ID AS [Court], 
            a.Respondent_Name AS [Respondent], 
            a.Applicant AS [Applicant], 
            a.Application_Amount AS [Application Amount], 
            a.Case_Number AS [Case Number], 
            a.Item_Number AS [Item Number], 
            a.Hearing_Date AS [Hearing Date], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Motion_Roll a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Hearing_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 10
        SELECT
            a.AC_History_Judgements_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Slu_AW_Nature_Of_Action_ID AS [Nature Of Action], 
            a.Slu_AW_Courts_ID AS [Court], 
            a.Defendant_Name AS [Defendant], 
            a.Plaintiff_Name AS [Plaintiff], 
            a.Judgement_Amount AS [Judgement Amount], 
            a.Case_Number AS [Case Number], 
            a.Date_Of_Judgement AS [Judgement Date], 
            a.Default_Judgement AS [Default Judgement], 
            a.Date_Rescinded AS [Date Rescinded], 
            a.Rescindment_Reason AS [Rescindment Reason], 
            a.Date_Abandoned AS [Date Abandoned], 
            a.Abandonment_Reason AS [Abandonment Reason], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Judgements a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Of_Judgement DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 11
        SELECT
            a.AC_History_RD_Cheques_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Date_Reported AS [Date Reported], 
            a.Cheque_Amount AS [Cheque Amount], 
            a.Comments AS [Comments], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_RD_Cheques a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Reported DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 12
        SELECT
            a.AC_History_Principals_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Name, 
            a.ID_Number AS [ID Number], 
            a.Slu_AC_Principal_Types_ID AS [Principal Type], 
            a.Home_Tel_No AS [Home Tel], 
            a.Cell_No AS [Cell No], 
            a.E_Mail AS [E-mail Address], 
            a.Home_Address AS [Home Address], 
            a.Date_Appointed AS [Date Appointed], 
            a.Date_Terminated AS [Date Terminated], 
            a.Primary_Function AS [Primary Function], 
            a.Principal_Comments AS [Comments], 
            a.Status_Ind AS [Status Ind], 
            a.Status_Date AS [Status Date], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Principals a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Name DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 13
        SELECT
            a.AC_History_Principal_Properties_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.AC_History_Principals_ID AS [PrincipalID], 
            a.[Description] AS [Description], 
            a.Registered_Owner AS [Registered Owner], 
            a.Title_Deed_Number AS [Title Deed No], 
            a.Property_Size AS [Size], 
            a.Date_Purchased AS [Date Purchased], 
            a.Purchase_Price AS [Purchase Price], 
            a.Address1 AS [Address1], 
            a.Address2 AS [Address2], 
            a.Suburb AS [Suburb], 
            a.City AS [City], 
            a.Post_Code AS [Post Code], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Principal_Properties a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID AND
              a.AC_History_Principals_ID = @PrincipalID
        ORDER BY a.Date_Purchased DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 14
        SELECT
            a.AC_History_Shareholders_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Shareholder_Name AS [Name], 
            a.Interest_Percent AS [Interest %], 
            a.Number_Of_Shares AS [No Of Shares], 
            a.Slu_AC_Shareholding_Types_ID AS [Shareholding Type], 
            a.Members_Contribution AS [Members Contrib], 
            a.Par_Value_Of_Holding AS [Par Value], 
            a.Estimated_Valuation AS [Valuation], 
            a.Controlling_Shareholder AS [Controlling Shareholder], 
            a.Parent_Company AS [Parent Company], 
            a.Holding_Company AS [Holding Company], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Shareholders a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 15
        SELECT
            a.AC_History_Auditors_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Firm_Name AS [Firm Name], 
            a.Audit_Manager AS [Audit Manager], 
            a.Registration_Date AS [Reg Date], 
            a.Slu_AC_Profession_Types_ID AS [Profession Type], 
            a.Slu_AC_Auditor_Rankings_ID AS [Auditor Ranking], 
            a.Profession_Number AS [Profession No], 
            a.Profession_Date_Changed AS [Date Changed], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Auditors a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 16
        SELECT
            a.AC_History_Associates_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Associate_Name AS [Associate Name], 
            a.Slu_AC_Association_Types_ID AS [Association Type], 
            a.Shareholding_Percentage AS [Shareholding %], 
            a.Slu_AC_Shareholding_Types_ID AS [Shareholding Type], 
            a.Date_Acquired AS [Date Acquired], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Associates a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Acquired DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 17
        SELECT
            a.AC_History_Bankers_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Slu_AW_Banks_ID AS [Bank], 
            a.Bank_Branch AS [Branch], 
            a.Bank_Branch_Code AS [Branch Code], 
            a.Account_Name AS [Account Name], 
            a.Account_Number AS [Account Number], 
            a.Slu_AC_Bank_Codes_ID AS [Bank Code],
            a.Bank_Code_Amount AS [Code Amount], 
            a.Slu_AW_Credit_Terms_ID AS [Code Terms], 
            a.Banker_Comments AS [Code Comments], 
            a.Date_Opened AS [Date Opened], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Bankers a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Opened DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 18
        SELECT
            a.AC_History_Balance_Sheets_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Statement_Date AS [Statement Date], 
            a.Property_Plant_and_Equipment AS [Prop Plant Equip], 
            a.Investment_Property AS [Invest Prop], 
            a.Investments_and_Loans AS [Invest &_Loans], 
            a.Investments_and_Finance_Leases AS [Invest & Fin Leases], 
            a.Forward_Exchange_Contract_Asset AS [Fwd Exch Contract Asset], 
            a.Inventories AS [Inventories], 
            a.Trade_and_Other_Receivables AS [Trade & Other Receivables], 
            a.Prepayments AS [Prepayments], 
            a.Cash_and_Cash_Equivalents AS [Cash], 
            a.Issued_Capital AS [Issued Capital], 
            a.Reserves AS [Reserves], 
            a.Accumulated_Profit_Loss AS [Accum Profit/Loss], 
            a.Interest_Bearing_Borrowings AS [Int Bearing Borrowings], 
            a.Deferred_Taxation AS [Deferred Taxation], 
            a.Retirement_Benefit_Obligations AS [Retire Benefit Obligs], 
            a.Trade_and_Other_Payables AS [Trade & Other Payables], 
            a.Taxation AS [Taxation], 
            a.Dividend_Declared AS [Dividend Declared], 
            a.Bank_Overdraft AS [Bank Overdraft], 
            a.Overdraft_Facility AS [Overdraft Facility], 
            a.Current_portion_of_Interest_Bearing_Borrowings AS [Curr port of Int Bear Borrow], 
            a.Warranty_Provision AS [Warranty Provision], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Balance_Sheets a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Statement_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 19
        SELECT
            a.AC_History_Income_Statements_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Statement_Date AS [Statement Date], 
            a.Revenue AS [Revenue], 
            a.Cost_of_Sales AS [Cost of Sales], 
            a.Other_Income AS [Other Income], 
            a.Fleet_Rental AS [Fleet Rental], 
            a.Distribution_Expenses AS [Distrib Exp], 
            a.Auditors_Remuneration AS [Auditors Remun], 
            a.Depreciation AS [Depreciation], 
            a.Prepayments AS [Prepayments], 
            a.Profit_Loss_on_disposal_of_Assets AS [P/L on disposal of Assets], 
            a.Permanent_decline_in_value_of_Investment_Property AS [Permanent decline in value of Invest Prop], 
            a.Fees_for_Services AS [Fees for Services], 
            a.Rental_on_Operating_Leases AS [Rent on Operating Leases], 
            a.Forex_Gains_Losses AS [Forex Gains Losses], 
            a.Staff_Costs AS [Staff Costs], 
            a.Other_Long_Term_Employee_Benefits AS [Other Long Term Employee Benefits], 
            a.Directors_Emoluments AS [Directors Emoluments], 
            a.Other_Expenses AS [Other Expenses], 
            a.Financing_Costs AS [Financing Costs], 
            a.Financing_Costs_Capitalized AS [Fin Costs Capitalized], 
            a.Taxation AS [Taxation], 
            a.Extraordinary_Items AS [Extraordinary Items], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Income_Statements a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Statement_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 20
        SELECT
            a.AC_History_Bonds_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Bond_Account_Number AS [Bond Acct NNo], 
            a.Bond_Holder AS [Bond Holder], 
            a.Bond_Amount AS [Bond Amount], 
            a.Slu_AC_Bond_Types_ID AS [Bond Type], 
            a.Repayment_Period AS [Repay Period], 
            a.Repayment_Amount AS [Repay Amount], 
            a.Effective_date AS [Effective Date], 
            a.Date_Registered AS [Date Registered], 
            a.Collateral_Provider AS [Collateral Provider], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Bonds a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 21
        SELECT
            a.AC_History_Properties_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Slu_AC_Bond_Types_ID AS [Bond Type], 
            a.[Description] AS [Description], 
            a.Registered_Owner AS [Registered Owner], 
            a.Title_Deed_Number AS [Title Deed No], 
            a.Property_Size AS [Size], 
            a.Date_Purchased AS [Date Purchased], 
            a.Purchase_Price AS [Price], 
            a.Address1 AS [Address1], 
            a.Address2 AS [Address2], 
            a.Suburb AS [Suburb], 
            a.City AS [City], 
            a.Post_Code AS [Post Code], 
            a.Date_Captured AS [Date Captured],
--            b.UserName AS [User],
            a.[User_ID] AS [User],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Properties a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Purchased DESC
----------------------------------------------------------------------



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Lookups
--Purpose       :
--Functionality :
--Date          :2003/05/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Select_Customer_Lookups
    (
        @Option varchar(30) = '',
        @ID smallint = -1
    )
AS
    IF @Option = 'Title'
        SELECT Slu_AW_Titles_ID AS [ID], Description AS [Title]
        FROM Slu_AW_Titles
    ELSE
    IF @Option = 'Language'
        SELECT Slu_AW_Languages_ID AS [ID], Description AS [Language]
        FROM Slu_AW_Languages
    ELSE
    IF @Option = 'Type'
        SELECT Lup_AC_Customer_Types_ID AS [ID], Description AS [Type]
        FROM Lup_AC_Customer_Types
    ELSE
    IF @Option = 'Discount Category'
        SELECT Lup_AC_Discount_Categories_ID AS [ID], Description AS [Discount Category]
        FROM Lup_AC_Discount_Categories
    ELSE
    IF @Option ='Credit Terms'
        SELECT Slu_AW_Credit_Terms_ID AS [ID], Description AS [Credit Terms]
        FROM Slu_AW_Credit_Terms
    ELSE
    IF @Option = 'Charge Interest'
        SELECT Slu_AW_YesNo_ID AS [ID], Description AS [Charge Interest]
        FROM Slu_AW_YesNo
    ELSE
    IF @Option = 'Salesperson'
        SELECT Lup_AS_Reps_ID AS [ID], Description AS [Salesperson]
        FROM Lup_AS_Reps
    ELSE
    IF @Option = 'Sales Area'
        SELECT Lup_AC_Sales_Areas_ID AS [ID], Description AS [Sales Area]
        FROM Lup_AC_Sales_Areas
    ELSE
    IF @Option = 'Active'
        SELECT Slu_AW_Active_ID AS [ID], Description AS [Active]
        FROM Slu_AW_Active 
    ELSE
    IF @Option = 'Account Status'
        SELECT Sys_AC_Account_Status_ID AS [ID], Description AS [Account Status]
        FROM Sys_AC_Account_Status  
    ELSE
    IF @Option = 'Tax Code'
        SELECT Sys_AW_Tax_Codes_ID AS [ID], Description AS [Tax Code], Tax_Rate AS [Tax Rate]
        FROM Sys_AW_Tax_Codes 
    ELSE
    IF @Option = 'Country'
        SELECT Slu_AW_Countries_ID AS [ID], Description AS [Country]
        FROM Slu_AW_Countries
    ELSE
    IF @Option = 'Actor'
        SELECT Sys_AT_Actor_Types_ID as ID, Description AS [Actor]
        FROM Sys_AT_Actor_Types
    ELSE
    IF @Option = 'Status'
        SELECT SYS_AT_Status_ID as ID, Description AS [Status]
        FROM SYS_AT_Status
    ELSE 
    IF @Option = 'Notification'
        SELECT SYS_AT_Notifications_ID as ID, Description AS [Notification]
        FROM SYS_AT_Notifications
    ELSE
    IF @Option = 'User'
        SELECT AW_Users_ID as ID, UserName AS [User Name]
        FROM AW_Users







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/03/15
--Authors       :TB
--MODS          :24/07/02 - Added Sys_AW_Transactions_Types_ID's 21 and 22 to
--              :           @Choice=17 (Customer Catalog cboCustTrans)
--              :04/08/03 - Added Choice 18 & 19, Transaction Types - Quotes, 
--              :           Jobcards, Proformas and Users for Deactivate Transactions
--              :06/08/03 - Added Choice 20 Active for Deactivate Transactions
--              :09/08/03 - Added Choice 21 ALL Transaction Types - Sales Chronolgy
--              :20/12/03 - Added Choice 22 Use Assets in Customer Catalog
--              :04/01/04 - Added Choice 23 to 48 for Credit Manager
--              :05/07/04 - Added Choice 49 for Lup_AC_Customer_Groups
--              :05/01/05 - Added Choice 50 for Customers Payments History
--2004.2.7      :10/03/06 - Added Choice = 51 for Customer E-Mail addresses
--2004.3.7      :25/07/07 - Added Choice = 52 for Customer Cost+Plus Category
--2004.3.8      :02/12/07 - Added ORDER BY for Reps, Countries, Customer Type,
--              :           Sales Areas, and Customer Groups
--2004.3.9      :05/07/08 - Added new Select Sales Order TranType = 16 where required
--2004.4.3      :17/03/09 - Added Option = 53 for Statement Messages - Active only
--2004.4.7      :22/08/09 - Added new Select Stock Transfer TranType = 23 where required
--2004.5.0      :16/11/10 - Change alias in Choice 51 from [EMail] to [E-Mail] for Periodic Billing
--              :21/01/11 - Added Option = 54 for Periodic Billing
--V6.2	RL	2015-05-18	:Added Option 56 - Customer Consignment Stock Transaction Types
--V6.2	RL	2015-06-10	:Added Customer Consignment Transactions to options 17 and 21
--V6.4	RL	2018-03-27	:Added option 58 Added AS_Transactions_Address_Detail Email
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Select_Customer_Lups]
    (
       	@Choice int,
    	@CompanyID int
    )
AS

BEGIN
    IF @Choice = 1	--'Title'
        SELECT Slu_AW_Titles_ID AS [ID], [Description] 
        FROM Slu_AW_Titles
        ORDER BY [Description]
    ELSE

    IF @Choice = 2	--'Language'
      	SELECT Slu_AW_Languages_ID AS [ID],  [Description]  
        FROM Slu_AW_Languages
        ORDER BY [Description]
    ELSE

    IF @Choice = 3	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],  [Description]  	
        FROM Slu_AW_YesNo

    ELSE
    IF @Choice = 4	--'Sales Discount'
      	SELECT Lup_AC_Discount_Categories_ID AS [ID],  [Description] 
        FROM Lup_AC_Discount_Categories
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 5	--'Credit Terms'
      	SELECT Slu_AW_Credit_Terms_ID AS [ID],  [Description] 	
        FROM Slu_AW_Credit_Terms

    ELSE
    IF @Choice = 6	--'Terms Of Sale        'Credit Term Types'
      	SELECT Sys_AC_Credit_Term_Types_ID AS [ID], [Description] 
        FROM Sys_AC_Credit_Term_Types
        ORDER BY [Description]

    ELSE
    IF @Choice = 7	--'Account Types'
      	SELECT Sys_AC_Account_Types_ID AS [ID], [Description] 
        FROM Sys_AC_Account_Types
        ORDER BY [Description]

    ELSE
    IF @Choice = 8 	--'Reps  **'
      	SELECT Lup_AS_Reps_ID AS [ID], Description 
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 9	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID], Description 
        FROM Slu_AW_Active 
        ORDER BY [Description]

    ELSE
    IF @Choice = 10	--'Account Status'
      	SELECT Sys_AC_Account_Status_ID AS [ID], Description 
        FROM Sys_AC_Account_Status  
        ORDER BY [Description]

    ELSE
    IF @Choice = 11	--'Tax Code'
      	SELECT Sys_AW_Tax_Codes_ID AS [ID], Description, Tax_Rate AS [Tax Rate] 
        FROM Sys_AW_Tax_Codes 

    ELSE
    IF @Choice = 12	--'Countries **'
        SELECT Slu_AW_Countries_ID AS [ID], Description 
        FROM Slu_AW_Countries
        ORDER BY [Description]

    ELSE
    IF @Choice = 13	--'Actor2'    '(Customer Tasks)
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [Actor2]
        FROM AW_Users 
        WHERE AW_Users_ID > 1
        ORDER BY [Actor2]

    ELSE
    IF @Choice = 14	--'Customer Type **'
      	SELECT Lup_AC_Customer_Types_ID as [ID] , Description
        FROM Lup_AC_Customer_Types 
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 15 --Transaction Types
        SELECT Sys_AW_Transaction_Types_ID as [ID], Description
        FROM Sys_AW_Transaction_Types 
        WHERE Sys_AW_Transaction_Types_ID <= 4

    ELSE
    IF @Choice = 16 --'Sales Areas **'
      	SELECT Lup_AC_Sales_Areas_ID as [ID], Description
        FROM Lup_AC_Sales_Areas 
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 17 --Transaction Types - ALL
        SELECT Sys_AW_Transaction_Types_ID as [ID],
               [Description]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or 
              Sys_AW_Transaction_Types_ID = 3 or 
              Sys_AW_Transaction_Types_ID = 4 or 
              Sys_AW_Transaction_Types_ID = 5 or 
              Sys_AW_Transaction_Types_ID = 7 or 
              Sys_AW_Transaction_Types_ID = 13 or
              Sys_AW_Transaction_Types_ID = 15 or 
              Sys_AW_Transaction_Types_ID = 16 or 
        	  Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or 
        	  Sys_AW_Transaction_Types_ID = 22 or
              Sys_AW_Transaction_Types_ID = 23 or
              Sys_AW_Transaction_Types_ID = 33 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 34 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 35		--V6.2 Consignment Transactions
        ORDER BY Description

    ELSE
    IF @Choice = 18 --Transaction Types - Quotes, Jobs, Proformas and Sales Orders only
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or
              Sys_AW_Transaction_Types_ID = 13 or
              Sys_AW_Transaction_Types_ID = 16 or
              Sys_AW_Transaction_Types_ID = 23

    ELSE
    IF @Choice = 19	--'Users'
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [User]
        FROM AW_Users 
        ORDER BY [User]

    ELSE
    IF @Choice = 20	--'Active' for Deactivate Transactions
      	SELECT Slu_AW_Active_ID AS [ID],
               [Description] AS [Active] 
        FROM Slu_AW_Active 

    ELSE
    IF @Choice = 21 --Transaction Types - ALL (Manager Console - Sales Chronology)
        SELECT Sys_AW_Transaction_Types_ID as [ID],
               [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or 
              Sys_AW_Transaction_Types_ID = 3 or 
              Sys_AW_Transaction_Types_ID = 4 or 
              Sys_AW_Transaction_Types_ID = 5 or 
              Sys_AW_Transaction_Types_ID = 7 or
              Sys_AW_Transaction_Types_ID = 13 or 
              Sys_AW_Transaction_Types_ID = 15 or 
              Sys_AW_Transaction_Types_ID = 16 or 
        	  Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or 
        	  Sys_AW_Transaction_Types_ID = 22 or
              Sys_AW_Transaction_Types_ID = 23 or
              Sys_AW_Transaction_Types_ID = 33 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 34 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 35		--V6.2 Consignment Transactions

    ELSE
    IF @Choice = 22	--'Active' for Use Assets
      	SELECT Sys_AC_Use_Assets_ID AS [ID],
               [Description] AS [Description] 
        FROM Sys_AC_Use_Assets 

	ELSE 
	IF @Choice = 23    --Controllers
		SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [Description]
		FROM AW_Users
        WHERE IsController = 1
        ORDER BY [Description]

    ELSE
    IF @Choice = 24    --'Delivery Methods'
      	SELECT Sys_AW_Delivery_Methods_ID as [ID] , [Description]
        FROM Sys_AW_Delivery_Methods 

    ELSE
    IF @Choice = 25	--'Pricipal Contact Method'
      	SELECT Sys_AW_Delivery_Methods_ID as [ID] , [Description]
        FROM Sys_AW_Delivery_Methods 

    ELSE
    IF @Choice = 26	--'Business Types'
      	SELECT Slu_AC_Business_Types_ID AS [ID],  [Description] 
        FROM Slu_AC_Business_Types
        ORDER BY [Description]

    ELSE
    IF @Choice = 27 --Transaction Types - Financial ONLY
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 3 or
              Sys_AW_Transaction_Types_ID = 4 or
              Sys_AW_Transaction_Types_ID = 5 or
              Sys_AW_Transaction_Types_ID = 7 or
              Sys_AW_Transaction_Types_ID = 15 or
              Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 28	--'Security Types'
      	SELECT Slu_AC_Security_Types_ID as [ID] , [Description]
        FROM Slu_AC_Security_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 29	--'Information_Report Types'
      	SELECT Slu_AW_Info_Report_Types_ID as [ID] , [Description]
        FROM Slu_AW_Info_Report_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 30	--'Bond Types'
      	SELECT Slu_AC_Bond_Types_ID as [ID] , [Description]
        FROM Slu_AC_Bond_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 31	--'Customer Rating'
      	SELECT Slu_AC_Ratings_ID as [ID] , [Description]
        FROM Slu_AC_Ratings 
        ORDER BY [Description] DESC

    ELSE
    IF @Choice = 32	--'KI Scores'
      	SELECT Slu_AC_KI_Scores_ID as [ID] , [Description]
        FROM Slu_AC_KI_Scores 
        ORDER BY [Description]

    ELSE
    IF @Choice = 33	--'ITC Scores'
      	SELECT Slu_AC_ITC_Scores_ID as [ID] , [Description]
        FROM Slu_AC_ITC_Scores 
        ORDER BY [Description]

    ELSE
    IF @Choice = 34	--'Adverse Reasons'
      	SELECT Slu_AC_Adverse_Reasons_ID as [ID] , [Description]
        FROM Slu_AC_Adverse_Reasons 
        ORDER BY [Description]

    ELSE
    IF @Choice = 35	--'Nature Of Action'
      	SELECT Slu_AW_Nature_Of_Action_ID as [ID] , [Description]
        FROM Slu_AW_Nature_Of_Action 
        ORDER BY [Description]

    ELSE
    IF @Choice = 36	--'Lawsuit Type'
      	SELECT Slu_AW_Lawsuit_Types_ID as [ID] , [Description]
        FROM Slu_AW_Lawsuit_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 37	--'Court'
      	SELECT Slu_AW_Courts_ID as [ID] , [Description]
        FROM Slu_AW_Courts 
        ORDER BY [Description]

    ELSE
    IF @Choice = 38	--'Principal Type'
      	SELECT Slu_AC_Principal_Types_ID as [ID] , [Description]
        FROM Slu_AC_Principal_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 39	--'Shareholder Type'
      	SELECT Slu_AC_Shareholding_Types_ID as [ID] , [Description]
        FROM Slu_AC_Shareholding_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 40	--'Profession Type'
      	SELECT Slu_AC_Profession_Types_ID as [ID] , [Description]
        FROM Slu_AC_Profession_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 41	--'Auditor Ranking'
      	SELECT Slu_AC_Auditor_Rankings_ID as [ID] , [Description]
        FROM Slu_AC_Auditor_Rankings 
        ORDER BY [Description]

    ELSE
    IF @Choice = 42	--'Association Type'
      	SELECT Slu_AC_Association_Types_ID as [ID] , [Description]
        FROM Slu_AC_Association_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 43	--'Bank'
      	SELECT Slu_AW_Banks_ID as [ID] , [Description]
        FROM Slu_AW_Banks 
        ORDER BY [Description]

    ELSE
    IF @Choice = 44	--'SICC Codes'
		--RL V6.0 2014-10-22 Table does not exist
		--SELECT AW_SICC_Codes_ID as [ID] , [Description]
       -- FROM AW_SICC_Codes 
       -- ORDER BY [Description]

      	SELECT 1 as [ID] , '' As [Description]

    ELSE
    IF @Choice = 45	--'Users'
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [User]
        FROM AW_Users 
        ORDER BY [User]

    ELSE
    IF @Choice = 46	--'Severity Level'
      	SELECT Sys_AC_Severity_Levels_ID as [ID] , [Description]
        FROM Sys_AC_Severity_Levels 

    ELSE
    IF @Choice = 47	--'Bank Codes'
      	SELECT Slu_AC_Bank_Codes_ID as [ID] , [Description]
        FROM Slu_AC_Bank_Codes 

    ELSE
    IF @Choice = 48	--'Bank Code Terms'
      	SELECT Slu_AW_Credit_Terms_ID AS [ID],  [Description] 	
        FROM Slu_AW_Credit_Terms

    ELSE
    IF @Choice = 49	--'Customer Groups **'
      	SELECT Lup_AC_Customer_Groups_ID as [ID] , Description
        FROM Lup_AC_Customer_Groups 
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 50 --Payment Types
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 7 OR
              Sys_AW_Transaction_Types_ID = 21 OR
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 51 --Customer E-Mail addresses
        SELECT Orders_URL as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Orders_URL,'') <> ''

        UNION

        SELECT Home_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Home_Email,'') <> ''

        UNION

        SELECT Work_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Work_Email,'') <> ''

    ELSE
    IF @Choice = 52	--'Cost+Plus Category'
      	SELECT Lup_AC_Markup_Categories_ID AS [ID], [Description] 
        FROM Lup_AC_Markup_Categories
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 53 --'Statement Messages - Active only
        SELECT Slu_AC_Statement_Messages_ID AS [ID],
              ISNULL(Description, '') AS [Description],
              ISNULL(Message, '') AS [Message]
        FROM Slu_AC_Statement_Messages
        WHERE Slu_AW_Active_ID = 1
        ORDER BY [Description]

    ELSE
    IF @Choice = 54 --Transaction Types - Periodic Billing
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 3 or
              Sys_AW_Transaction_Types_ID = 4 or
              Sys_AW_Transaction_Types_ID = 5 or
              Sys_AW_Transaction_Types_ID = 21 or
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 55 --Email Document Layout
        SELECT Slu_AC_Documents_ID as [ID],
			   Document_Layout AS [Description] 
        FROM Slu_AC_Documents
        ORDER BY Slu_AC_Documents_ID

    ELSE
    IF @Choice = 56 --Customer COnsignment Stock Transactions Types
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 33 or
              Sys_AW_Transaction_Types_ID = 34 or
              Sys_AW_Transaction_Types_ID = 35
    ELSE
    IF @Choice = 57 --Customer COnsignment Stock Transactions Types
        SELECT Lup_AP_Product_Bins_ID as [ID],
              [Description] AS [ProductBin]
        FROM Lup_AP_Product_Bins
        ORDER BY [Description]
    ELSE
    IF @Choice = 58 --Customer E-Mail addresses including AS_Transactions_Address_Detail
    BEGIN
        SELECT Orders_URL as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Orders_URL,'') <> ''

        UNION

        SELECT Home_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Home_Email,'') <> ''

        UNION

        SELECT Work_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Work_Email,'') <> ''

		UNION
		
        SELECT Distinct Email as [E-Mail]
        FROM AS_Transactions_Address_Detail
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Email,'') <> ''
	END	
END  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Payments
--Purpose       :Selects the PAYMENT to display in Customer Payments --> History
--Date          :2005/02/05
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Select_Customer_Payments
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime 
	)

AS

SET NOCOUNT ON

--> Specific Payment Type
    IF @TransactionTypeID <> 0
        SELECT
            a.[ID],
            b.[Description] AS [Type],
            a.[Date],
            a.[No],
            a.Discount,
            a.Tax,
            a.Amount,
            a.Payment,
            a.Comment,
        	a.CashUp AS [Cash Up], 
        	a.DayEnd AS [Day End],
            u.UserName AS [User],
            a.TypeID
        FROM vw_AS_Transaction_Headers a
            INNER JOIN Sys_AW_Transaction_Types b
                ON a.TypeID = b.Sys_AW_Transaction_Types_ID
            LEFT JOIN AW_Users u
                ON a.UserID = u.AW_Users_ID
        WHERE a.CustomerID = @CustomerID AND
              a.TypeID = @TransactionTypeID AND
             (datediff(d, a.[Date], @StartDate ) <= 0 AND
              datediff(d, a.[Date], @EndDate) >= 0)
        ORDER BY a.[Date] DESC

--> ALL Payment Types
    ELSE
        SELECT
            a.[ID],
            b.[Description] AS [Type],
            a.[Date],
            a.[No],
            a.Discount,
            a.Tax,
            a.Amount,
            a.Payment,
            a.Comment,
        	a.CashUp AS [Cash Up], 
        	a.DayEnd AS [Day End],
            u.UserName AS [User],
            a.TypeID
        FROM vw_AS_Transaction_Headers a
            INNER JOIN Sys_AW_Transaction_Types b
                ON a.TypeID = b.Sys_AW_Transaction_Types_ID
            LEFT JOIN AW_Users u
                ON a.UserID = u.AW_Users_ID
        WHERE a.CustomerID = @CustomerID AND
             (a.TypeID = 7 OR
              a.TypeID = 21 OR
              a.TypeID = 22) AND
             (datediff(d, a.[Date], @StartDate ) <= 0 AND
              datediff(d, a.[Date], @EndDate) >= 0)
        ORDER BY a.[Date] DESC

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Product_Bins
--Purpose       : 
--Functionality : 
--REQUIRED in UI:CustomerID, UserID, CompanyID
--Date          :2016-07-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Select_Customer_Product_Bins]
    (
    	@Company_ID int,
    	@Customer_ID int
    )

AS

--EXEC sp_AC_Select_Customer_Product_Bins 0, 2, 567, 0

SET NOCOUNT ON

----------------------------------------------------------------------

        SELECT
            a.AC_Product_Bins_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],         -- REQUIRED AS IS
            a.Lup_AP_Product_Bins_ID AS [ProductBin], 
            a.Date_Captured AS [Date Captured], 
            a.[User_ID] AS [User],                   -- REQUIRED AS IS
            a.AW_User_Companies_ID AS [CompanyID],     -- REQUIRED AS IS 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_Product_Bins a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :Selects the transactions to display at Customer Catalog & POS
--Purpose       :
--Functionality :
--Parameters    : 
--Date          :2002/03/15
--Authors       :TB
--Version       :1
--Mods          :25/06/02 - Changed SORT ORDER of: @Choice = 1 
--              :           1. ORDER BY to a.[Date] DESC
--              :           2. SELECT column order and added CashUp, DayEnd, User
--              :23/07/02 - Added SELECT [ID] (AS_Transactions_ID),
--              :                        [TypeID] (Sys_AW_Transaction_Types_ID)
--                          from vw_AS_Transaction_Headers for POS Re-Print
--              :24/07/02 - Added Sys_AW_Transaction_Types_ID 21 & 22
--              :12/11/04 - Removed transaction type filters in ALL Transactions option
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AC_Select_Customer_Transactions
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime 
	)

AS

SET NOCOUNT ON

--> Specific Transactions
    IF @TransactionTypeID <> 0
        SELECT
            a.[ID],
            b.[Description] AS [Type],
            a.[Date],
            a.[No],
            a.Discount,
            a.Tax,
            a.Amount,
            a.Payment,
            a.Comment,
        	a.CashUp AS [Cash Up], 
        	a.DayEnd AS [Day End],
            u.UserName AS [User],
            a.TypeID
        FROM vw_AS_Transaction_Headers a
            INNER JOIN Sys_AW_Transaction_Types b
                ON a.TypeID = b.Sys_AW_Transaction_Types_ID
            LEFT JOIN AW_Users u
                ON a.UserID = u.AW_Users_ID
        WHERE a.CustomerID = @CustomerID AND
              a.TypeID = @TransactionTypeID AND
             (datediff(d, a.[Date], @StartDate ) <= 0 AND
              datediff(d, a.[Date], @EndDate) >= 0)
        ORDER BY a.[Date] DESC

--> ALL Transactions
    ELSE
        SELECT
            a.[ID],
            b.[Description] AS [Type],
            a.[Date],
            a.[No],
            a.Discount,
            a.Tax,
            a.Amount,
            a.Payment,
            a.Comment,
        	a.CashUp AS [Cash Up], 
        	a.DayEnd AS [Day End],
            u.UserName AS [User],
            a.TypeID
        FROM vw_AS_Transaction_Headers a
            INNER JOIN Sys_AW_Transaction_Types b
                ON a.TypeID = b.Sys_AW_Transaction_Types_ID
            LEFT JOIN AW_Users u
                ON a.UserID = u.AW_Users_ID
        WHERE a.CustomerID = @CustomerID AND
--              (a.TypeID = 3 OR
--               a.TypeID = 4 OR
--               a.TypeID = 5 OR
--               a.TypeID = 7 OR
--               a.TypeID = 15 OR
--               a.TypeID = 18 OR
--               a.TypeID = 21 OR
--               a.TypeID = 22) AND
             (datediff(d, a.[Date], @StartDate ) <= 0 AND
              datediff(d, a.[Date], @EndDate) >= 0)
        ORDER BY a.[Date] DESC

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customers_As_Lup
--Purpose       :Returns all Customer Accounts as a Lookup
--Date          :2003/11/11
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_Customers_As_Lup
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AC_Customers_ID AS [ID],
    	   ISNULL(Surname, '') + ISNULL(', ' + Firstnames, '') AS [Customer]
    FROM AC_Customers
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY [Customer]


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customers_As_Lup_Extended
--Purpose       :Returns all Customer Accounts as a Lookup PLUS street address
--Date          :2004/11/27
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AC_Select_Customers_As_Lup_Extended
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AC_Customers_ID AS [ID],
    	   ISNULL(Surname, '') +
           ISNULL(', ' + Firstnames, '') +
           ISNULL(', ' + Street_Address, '') +
           ISNULL(', ' + Suburb, '') +
           ISNULL(', ' + City, '') AS [Customer]
    FROM AC_Customers
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY [Customer]


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customers_For_PickList
--Purpose       :Select all Customers for the Customer Catalog Picklist
--Functionality :
--Parameters    :
--Date          :2002/04/27
--Authors       :TB
--MODS          :28/09/02 - Added comma after Surname
--              :27/07/03 - Switched [Customer] and [Cust No] column order
--2004.4.2      :30/10/08 - Added ISNULL validation to Customer_Number field
--              :30/10/08 - Changed ORDER BY from Surname, Firstnames to [Customer]
------------------------------------------------------------------------------

CREATE         Procedure sp_AC_Select_Customers_For_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AC_Customers_ID AS [ID],
		   ISNULL(Surname,'') + ISNULL(', ' + Firstnames,'') AS [Customer],
           ISNULL(Customer_Number, '') as [Cust No]
	FROM AC_Customers
	WHERE AW_User_Companies_ID = @Company_ID
	ORDER BY [Customer] ASC

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AC_Select_Email_Statement_Customers
--Purpose       :Returns all Customers in AC_Statements
--Functionality :
--Parameters    :
--Date          :2004/01/18
--Authors       :TB
--MODS          :19/06/04 - Changed Orders_URL to be the Accounts E-mail address 
--              :21/06/04 - Added [StatementID] field
--2004.3.4      :08/01/07 - Added Customer Surname and Firstname CASE statement
--2004.5.2      :03/06/11 - Added new AW_YesNo_Attach_Tran_ID AS [Attach Docs]
--V6.3	RL	2017-09-18 - Added option to ignore zero balance statements. 
--						 Month end are now pulled for all customers with transactions for a specific month
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Select_Email_Statement_Customers]
    (
        @PeriodProceduresID int,
		@ShowZeroBalance	int
    )

AS

SET NOCOUNT ON

	IF @ShowZeroBalance = 0
	BEGIN
        SELECT DISTINCT
            s.AC_Statements_ID AS [StatementID],
            c.AC_Customers_ID AS [CustomerID], 
            c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
            c.AW_YesNo_Attach_Tran_ID AS [Attach Docs],

            CASE WHEN c.Firstnames IS NULL
                THEN ISNULL(c.Surname, '')
                ELSE ISNULL(c.Surname, '') + ', ' + 
                     LTRIM(ISNULL(c.Firstnames, ''))
                END AS [Customer],

    		c.Customer_Number AS [Customer No],
            c.Orders_URL AS [E-Mail Address],
            c.Post_Box AS [Postal Address],
            c.Post_Office AS [Post Office],
            c.Post_Code AS [Post Code],
            s.Account_Balance AS [Balance]
        FROM AC_Statements s
            INNER JOIN AC_Statement_Details d
                ON s.AC_Statements_ID = d.AC_Statements_ID
            INNER JOIN AC_Customers c
                On s.AC_Customers_ID = c.AC_Customers_ID
        WHERE AW_Period_Procedures_ID = @PeriodProceduresID AND
              --ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			  s.Account_Balance <> 0
        ORDER BY [Customer]
	END
	ELSE
	BEGIN
        SELECT DISTINCT
            s.AC_Statements_ID AS [StatementID],
            c.AC_Customers_ID AS [CustomerID], 
            c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
            c.AW_YesNo_Attach_Tran_ID AS [Attach Docs],

            CASE WHEN c.Firstnames IS NULL
                THEN ISNULL(c.Surname, '')
                ELSE ISNULL(c.Surname, '') + ', ' + 
                     LTRIM(ISNULL(c.Firstnames, ''))
                END AS [Customer],

    		c.Customer_Number AS [Customer No],
            c.Orders_URL AS [E-Mail Address],
            c.Post_Box AS [Postal Address],
            c.Post_Office AS [Post Office],
            c.Post_Code AS [Post Code],
            s.Account_Balance AS [Balance]
        FROM AC_Statements s
            INNER JOIN AC_Statement_Details d
                ON s.AC_Statements_ID = d.AC_Statements_ID
            INNER JOIN AC_Customers c
                On s.AC_Customers_ID = c.AC_Customers_ID
        WHERE AW_Period_Procedures_ID = @PeriodProceduresID 
              --ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
        ORDER BY [Customer]
	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















--sp_AC_Select_Enterprise_Customer_Ageing 1
-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Enterprise_Customer_Ageing
--Purpose       :FILTER Enterprise Sales
--Date          :2007/03/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AC_Select_Enterprise_Customer_Ageing
	(
        @Sort tinyint
	)
   
AS

SET NOCOUNT ON

	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AC_Enterprise_Ageing_Temp '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Customer_Number] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [FullName] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AC_Select_FirstLast_Transaction_Date
--Purpose       :Select FIRST or LAST Customer Transaction Date
--Date          :2004/01/07
--Authors       :TB
--Version       :1.0.0
--MODS          :16/03/06 - Added set First date to Midnight last night and
--              :           Last date to Midnight tonight 
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_FirstLast_Transaction_Date
	(
    	@CompanyID int,
        @Option tinyint,
        @TranDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

--> Get the FIRST Customer Transaction Date
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Transaction_Date ASC

        --> Midnight yesterday
            SET @TranDate = CONVERT(datetime, DATEADD(dd, 0, ROUND(CONVERT(float, @TranDate), 0, 1)))

        END



    ELSE

--> Get the LAST Customer Transaction Date
    IF @Option = 1
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Transaction_Date DESC

        --> Midnight tonight
            SET @TranDate = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @TranDate), 0, 1)))
        END

SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Journal_Lups
--Purpose       :Gets a Customer List 
--Functionality :Used in Journal and Interest Journal
--Parameters    :
--Date          :2002/02/19
--Authors       :TB
--Version       :1.0.0
--Mods          :29/06/02 - Added 'InterestControl' as mlngDefaultGLAccountID
--              :20/07/02 - Added Customer Number to PickList rs (Customer Journals)
--              :20/07/02 - Replaces sp_AC_Customer_List_Select also used by POS
--              :01/05/05 - Added 'Credit Terms' used by Customer Interest Journals
--              :01/05/05 - Removed EXCLUSION of AB_Accounts_ID = 1 in 'Account'
--2004.5.1      :10/06/11 - Modified Option 'Account' to only select ACTIVE GL Accounts
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Select_Journal_Lups
    (
    	@CompanyID int,
    	@Option varchar(20) = ''
    )

AS

SET NOCOUNT ON

	IF @Option = 'Account'
		SELECT
            AB_Accounts_ID AS [ID],
            [Description] 
		FROM AB_Accounts
		WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
		ORDER BY [Description]

	ELSE
	IF @Option = 'Tax'
		SELECT
            Sys_AW_Tax_Codes_ID AS [ID],
            [Description],
            Tax_Rate AS [Tax] 
		FROM Sys_AW_Tax_Codes

    ELSE
    IF @Option = 'InterestControl'
        SELECT
            AB_Accounts_ID AS [ID]
        FROM AB_Control_Accounts
        WHERE Control_Number = 104

    ELSE
    IF @Option = 'Credit Terms'
      	SELECT
            Slu_AW_Credit_Terms_ID AS [ID],
            [Description],
            Terms_Value AS [TermsValue]
        FROM Slu_AW_Credit_Terms
        ORDER BY Slu_AW_Credit_Terms_ID

	ELSE        -- Picklist of Customers
		SELECT 
			c.AC_Customers_ID AS [ID],
    		ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, '') AS [Name],
    		ISNULL(c.Customer_Number, '') AS [No]
		FROM AC_Customers c
		WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Name]








SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Mail_Merge_Support_Customers
--Purpose       :Customer MAIL MERGE and SUPPORT PAYMENT TRACKER
--Date          :11 DEC 2007
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AC_Select_Mail_Merge_Support_Customers
    (
        @ProductID int,
        @Option tinyint,
        @Sort tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @DivideFeeBy tinyint,
            @Month int,
            @MonthlyFee money,
            @AnnualFee money,
            @Payable money,
            @PayableMonthly money



    SELECT @MonthlyFee = CONVERT(money, (1.14 * (dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()))))
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID


    SET @Month = MONTH(getdate()) + 1

    IF @Month > 12
        BEGIN
            SET @Month = 1
        END


    IF @Month < 7
        BEGIN
            SET @DivideFeeBy = 2
            SET @Payable = CONVERT(money, (6 * @MonthlyFee))
        END
    ELSE
        BEGIN
            SET @DivideFeeBy = 1
            SET @Payable = CONVERT(money, (12 * @MonthlyFee))
        END


    SET @AnnualFee = CONVERT(money, (12 * @MonthlyFee))
    SET @PayableMonthly = CONVERT(money, (@Month * @MonthlyFee))


    IF @Sort = 0
        BEGIN
            ----------------------------------------------------------------------
            -- Customer that have paid ANNUAL SUPPORT in FULL
            ----------------------------------------------------------------------
            IF @Option = 1
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, 0) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) = 0
                    ORDER BY c.Surname
                END
        
        
            ----------------------------------------------------------------------
            -- Customer that PAY MONTHLY ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 2
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, (@PayableMonthly + ISNULL(t.Payment_Amount, 0))) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          @PayableMonthly + ISNULL(t.Payment_Amount, 0) >= 0
                    ORDER BY c.Surname
                END
        
        
            ----------------------------------------------------------------------
            -- Customer that have NOT PAID ANY ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 3
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, @Payable) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          ISNULL(t.Payment_Amount, 0) = 0
                    ORDER BY c.Surname
                END


            ----------------------------------------------------------------------
            -- Customer OVERDUE on ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 4
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, (@Payable + t.Payment_Amount)) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          @Payable + t.Payment_Amount > 0
                    ORDER BY c.Surname
                END


            ----------------------------------------------------------------------
            -- Customer that have NOT BEEN INVOICED for ANY ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 5
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           CONVERT(money, 0) AS [Amount],
                           CONVERT(money, @Payable) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
--                           c.Date_Captured AS [Start Date]
                    FROM AC_Customers c
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE c.AC_Customers_ID NOT IN
                            (
                                SELECT DISTINCT t.AC_Customers_ID
                                FROM AS_Transactions t
                                    INNER JOIN AS_Transaction_Details d
                                        ON d.AS_Transactions_ID = t.AS_Transactions_ID
                                WHERE d.AP_Products_ID = @ProductID
                            ) AND
                          c.Slu_AW_Active_ID = 1 AND
--                          c.Lup_AC_Customer_Types_ID = 2 AND
                          c.Lup_AC_Customer_Groups_ID = 2
                    ORDER BY c.Surname
                END


            ----------------------------------------------------------------------
            -- Customer UP TO DATE on ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 6
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, (@Payable + t.Payment_Amount)) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        LEFT JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          @Payable + t.Payment_Amount <= 0
                    ORDER BY c.Surname
                END


            ----------------------------------------------------------------------
            -- Customer NOT OVERDUE on ANNUAL SUPPORT - E-mail Addresses
            ----------------------------------------------------------------------
            IF @Option = 7
                BEGIN
                    SELECT DISTINCT Work_Email AS [Email]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        LEFT JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          ABS(t.Payment_Amount) < @Payable
                END
        END
    ELSE
        BEGIN
            ----------------------------------------------------------------------
            -- Customer that have paid ANNUAL SUPPORT in FULL
            ----------------------------------------------------------------------
            IF @Option = 1
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, 0) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) = 0
                    ORDER BY [Customer]
                END
        
        
            ----------------------------------------------------------------------
            -- Customer that have PARTIALLY paid ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 2
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, (@PayableMonthly + ISNULL(t.Payment_Amount, 0))) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          @PayableMonthly + ISNULL(t.Payment_Amount, 0) >= 0
                    ORDER BY [Customer]
                END
        
        
            ----------------------------------------------------------------------
            -- Customer that have NOT PAID ANY ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 3
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, @Payable) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          ISNULL(t.Payment_Amount, 0) = 0
                    ORDER BY [Customer]
                END


            ----------------------------------------------------------------------
            -- Customer OVERDUE on ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 4
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, (@Payable + t.Payment_Amount)) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          @Payable + t.Payment_Amount > 0
                    ORDER BY [Customer]
                END


            ----------------------------------------------------------------------
            -- Customer that have NOT BEEN INVOICED for ANY ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 5
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           CONVERT(money, 0) AS [Amount],
                           CONVERT(money, @Payable) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
--                           c.Date_Captured AS [Start Date]
                    FROM AC_Customers c
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE c.AC_Customers_ID NOT IN
                            (
                                SELECT DISTINCT t.AC_Customers_ID
                                FROM AS_Transactions t
                                    INNER JOIN AS_Transaction_Details d
                                        ON d.AS_Transactions_ID = t.AS_Transactions_ID
                                WHERE d.AP_Products_ID = @ProductID
                            ) AND
                          c.Slu_AW_Active_ID = 1 AND
--                          c.Lup_AC_Customer_Types_ID = 2 AND
                          c.Lup_AC_Customer_Groups_ID = 2
                    ORDER BY [Customer]
                END


            ----------------------------------------------------------------------
            -- Customer NOT OVERDUE on ANNUAL SUPPORT
            ----------------------------------------------------------------------
            IF @Option = 6
                BEGIN
                    SELECT c.AC_Customers_ID AS [CustomerID], 
                           c.AW_YesNo_Send_Email_ID AS [Selected],
                           CASE WHEN c.Firstnames IS NULL
                                THEN ISNULL(c.Surname, '')
                                ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                                END AS [Customer],
                           c.Customer_Number AS [Number],
                           t.Total_Amount AS [Amount],
                           CONVERT(money, (@Payable + t.Payment_Amount)) AS [Overdue],
                           c.Fax_No AS [Fax Number],
                           c.Home_Email AS [Contact E-mail],
                           LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                                     THEN ISNULL(c.Principal_Name, '')
                                     ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                          RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                                END, 50) AS [Principal],
                           c.Contact_Name AS [Contact], 
                           c.Post_Box AS [Post Box],
                           c.Post_Office AS [Post Office],
                           c.Post_Code AS [Post Code],
                           c.Street_Address AS [Street Address], 
                           c.Suburb AS [Suburb],
                           c.City AS [City],
                           c.Street_Post_Code AS [Street Code]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        LEFT JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN Slu_AW_Titles tit
                            ON c.Slu_AW_Titles_ID = tit.Slu_AW_Titles_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          @Payable + t.Payment_Amount <= 0
                    ORDER BY [Customer]
                END


            ----------------------------------------------------------------------
            -- Customer NOT OVERDUE on ANNUAL SUPPORT - E-mail Addresses
            ----------------------------------------------------------------------
            IF @Option = 7
                BEGIN
                    SELECT DISTINCT Work_Email AS [Email]
                    FROM AS_Transactions t
                        INNER JOIN AS_Transaction_Details d
                            ON d.AS_Transactions_ID = t.AS_Transactions_ID
                        LEFT JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE d.AP_Products_ID = @ProductID AND
                          ABS(t.Payment_Amount) < @Payable
                END


        END

SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AC_Select_Master_Controller
--Purpose       :SELECT messages via the messaging system
--              :
--Date			:2004/01/05
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Select_Master_Controller
	(
		@CompanyID int,
        @ActorID int,
        @ActorTypeID int
	)

AS

SET NOCOUNT ON

    SELECT  a.Log_AC_Master_Controller_ID AS [ID],
            a.Date_Captured AS [Date Captured],
            a.Message AS [Message],
            c.[Description] AS [Severity],
            d.[Description] AS [Type],
            e.[Description] AS [Method],
            b.UserName AS [User]
    FROM Log_AC_Master_Controller a
        INNER JOIN AW_Users b
            ON a.[User_ID] = b.AW_Users_ID
        INNER JOIN Sys_AC_Severity_Levels c
            ON a.Sys_AC_Severity_Levels_ID = c.Sys_AC_Severity_Levels_ID
        INNER JOIN Sys_AC_Message_Types d
            ON a.Sys_AC_Message_Types_ID = d.Sys_AC_Message_Types_ID
        INNER JOIN Sys_AW_Delivery_Methods e
            ON a.Sys_AW_Delivery_Methods_ID = e.Sys_AW_Delivery_Methods_ID
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.Actor_ID = @ActorID AND
          a.Sys_AT_Actor_Types_ID = @ActorTypeID
    ORDER BY a.Date_Captured DESC


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




























-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Periodic_Billing_Detail
--Purpose       :Select Periodic Billing History Detail rows of a HeaderID
--Date          :21 JAN 2011
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Select_Periodic_Billing_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AC_Periodic_Billing_Detail_ID AS [ID],
           AC_Periodic_Billing_Header_ID AS [HeaderID],
           Post AS [Post],
           Transaction_Date AS [Date],
           Ref_No AS [Ref No],
           AC_Customers_ID AS [Customer],
           Sys_AW_Transaction_Types_ID AS [Transaction Type],
           Sys_AW_Tax_Methods_ID AS [Tax Method],
           Amount AS [Amount],
           Tax_Amount AS [Tax],
           Net_Amount AS [Net],
           AB_Accounts_ID AS [GL Account],
           Comment AS [Comment],
           Notes AS [Notes],
           Email AS [E-Mail]
    FROM AC_Periodic_Billing_Detail
    WHERE AC_Periodic_Billing_Header_ID = @HeaderID AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY AC_Periodic_Billing_Detail_ID




SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Periodic_Billing_Detail_Splits
--Purpose       :Select eriodic Billing HistoryDetail rows of a HeaderID
--Date          :21 JAN 2011
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Select_Periodic_Billing_Detail_Splits
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AC_Periodic_Billing_Detail_Splits_ID AS [ID],
           AC_Periodic_Billing_Detail_ID AS [DetailID],
           AP_Products_ID AS [Product],
           Quantity AS [Qty],
           Unit_Price AS [Unit Price],
           Sys_AW_Tax_Methods_ID AS [Method],
           Amount AS [Item Amount],
           Tax_Amount AS [Item Tax],
           Net_Amount AS [Item Net]
    FROM AC_Periodic_Billing_Detail_Splits
    WHERE AC_Periodic_Billing_Header_ID = @HeaderID AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY AC_Periodic_Billing_Detail_Splits_ID




SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Periodic_Billing_Header
--Purpose       :Select ONE Periodic Billinbg History Header row
--Date          :21 JAN 2011
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_Periodic_Billing_Header
	(
        @HeaderID int
	)

AS

SET NOCOUNT ON


    SELECT AC_Periodic_Billing_Header_ID AS [ID],
           Posting_Type AS [PostingType],
           Date_Posted AS [DatePosted],
           Slu_AW_Months_ID AS [MonthID],
           Slu_AW_Years_ID AS [YearID],
           Import_Filename AS [ImportFile],
           [User_ID] AS [UserID],
           Slu_AW_Active_ID AS [ActiveID]
    FROM AC_Periodic_Billing_Header
    WHERE AC_Periodic_Billing_Header_ID = @HeaderID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description   :sp_AC_Select_Prospect_Catalog
--Purpose       :Retrieves the Prospect catalog data
--Date          :2006/03/29
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Select_Prospect_Catalog
    (
        @ProspectID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        AC_Prospects_ID AS [ID], 
        Surname AS [Name], 
        Firstnames AS [First Names], 
        Initials AS [Initials], 
        Slu_AW_Titles_ID AS Title, 
        Slu_AW_Languages_ID AS Language, 
        IDReg_Number AS [ID/Reg No], 
        Start_Date AS [Start Date], 
        Customer_Number AS [Customer No], 
        Old_Customer_Number AS [Old Customer No], 
        Head_Office AS [Head Office], 
        Lup_AC_Customer_Types_ID AS [Customer_Type], 
        Lup_AC_Customer_Groups_ID AS [Customer_Group], 
        Sys_AC_Use_Assets_ID AS [Use Assets],
        Sys_AW_Delivery_Methods_ID AS [Method],
        Sys_AW_Tax_Codes_ID AS [Tax Code], 
        Tax_Number AS [Tax Number],
        Notes, 
        Lup_AC_Discount_Categories_ID AS [Sales Discount], 
        Credit_Limit AS [Credit Limit], 
        Slu_AW_Credit_Terms_ID AS [Credit Terms], 
        Sys_AC_Credit_Term_Types_ID AS [Credit Term Types],
        Credit_Insurers_Reference AS [Credit Insurers Ref],
        Credit_Insurers_Limit AS [Credit Insurers Limit],
        AW_YesNo_Charge_Interest_ID AS [Charge Interest],
        Slu_AW_Controllers_ID AS [Controller], 
        AW_YesNo_Pre_Notify_ID AS [PreNotify], 
        AW_YesNo_Post_Notify_ID AS [PostNotify], 
        Lup_AS_Reps_ID AS Salesperson, 
        Lup_AC_Sales_Areas_ID AS [Sales Areas], 
        Contact_Name AS [Contact Name], 
        Sys_AC_Account_Types_ID AS [Account Types],
        Sys_AC_Account_Status_ID AS [Account Status],
        Slu_AW_Active_ID AS Active, 
        Post_Box AS [Post Box], 
        Post_Office AS [Post Office], 
        Post_Code AS [Post Code], 
        Street_Address AS [Street Address], 
        Suburb AS [Suburb], 
        City AS [City], 
        Street_Post_Code AS [Street Code], 
        Delivery_Address AS [Delivery Address], 
        Delivery_Suburb AS [Delivery Suburb], 
        Delivery_City AS [Delivery City], 
        Delivery_Post_Code AS [Delivery Post Code], 
        Slu_AW_Countries_ID AS [Country], 
        Home_Tel_No AS [Home Tel No], 
        Work_Tel_No AS [Work Tel No], 
        Cell_No AS [Cell No], 
        Fax_No AS [Fax No], 
        Principal_Name AS [Principal Name],
        Principal_Firstname AS [Principal Firstname],
        Principal_Birthday AS [Principal Birthday],
        Principal_Contact_Method_ID AS [PrincipalMethod],
        Principal_Cell_No AS [PrincipalCellNo],
        Web_Site_URL AS [Web Site URL], 
        Orders_URL AS [Order URL], 
        Home_Email AS [E-mail Home], 
        Work_Email AS [E-mail Work], 
        Account_Balance AS [Account Balance],
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company ID],
        AW_YesNo_Send_Email_ID AS [Send Email],
        Default_Settlement_Discount AS [SettleDisc]
	FROM AC_Prospects 
	WHERE AC_Prospects_ID = @ProspectID AND
	      AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AC_Select_Prospect_Message_Log
--Purpose       :SELECT Prospect messages from Prospect Message Log
--Date			:2006/03/29
--Authors		:TB
--MODS    		:
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_Prospect_Message_Log
	(
		@CompanyID int,
        @ActorID int,
        @ActorTypeID int
	)

AS

SET NOCOUNT ON

    SELECT  a.Log_AC_Prospect_Messages_ID AS [ID],
            a.Date_Captured AS [Date Captured],
            a.Message AS [Message],
            c.[Description] AS [Severity],
            d.[Description] AS [Type],
            e.[Description] AS [Method],
            b.UserName AS [User]
    FROM Log_AC_Prospect_Messages a
        INNER JOIN AW_Users b
            ON a.[User_ID] = b.AW_Users_ID
        INNER JOIN Sys_AC_Severity_Levels c
            ON a.Sys_AC_Severity_Levels_ID = c.Sys_AC_Severity_Levels_ID
        INNER JOIN Sys_AC_Message_Types d
            ON a.Sys_AC_Message_Types_ID = d.Sys_AC_Message_Types_ID
        INNER JOIN Sys_AW_Delivery_Methods e
            ON a.Sys_AW_Delivery_Methods_ID = e.Sys_AW_Delivery_Methods_ID
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.Actor_ID = @ActorID AND
          a.Sys_AT_Actor_Types_ID = @ActorTypeID
    ORDER BY a.Date_Captured DESC


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :sp_AC_Select_Prospects_For_PickList
--Purpose       :Select all Prospects for the Prospect Catalog Picklist
--Date          :2006/03/29
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE        Procedure sp_AC_Select_Prospects_For_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AC_Prospects_ID AS [ID],
		   ISNULL(Surname,'') + ISNULL(', ' + Firstnames,'') AS [Customer],
           Customer_Number as [Cust No]
	FROM AC_Prospects
	WHERE AW_User_Companies_ID = @Company_ID
	ORDER BY Surname, Firstnames ASC

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Statement_Transactions
--Purpose       :Select all transactions for one Customer StatementID
--Date          :02 JUL 2011
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AC_Select_Statement_Transactions
    (
        @CustomerID int,
        @StatementID int
    )

AS

SET NOCOUNT ON

    --> Make DOUBLE sure that the tran owner can ONLY be this @CustomerID
    SELECT d.AS_Transactions_ID AS [TranID],
           d.Transaction_Number AS [TranNo], 
           d.Sys_AW_Transaction_Types_ID AS [TypeID],
           RIGHT(tt.Type_Code, 3) AS [TranType]
    FROM AC_Statement_Details d
        INNER JOIN AC_Statements h
            ON d.AC_Statements_ID = h.AC_Statements_ID
        INNER JOIN AS_Transactions t
            ON d.AS_Transactions_ID = t.AS_Transactions_ID
        INNER JOIN Sys_AW_Transaction_Types tt
            ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    WHERE h.AC_Customers_ID = @CustomerID AND
          t.AC_Customers_ID = @CustomerID AND
          d.AC_Statements_ID = @StatementID
    ORDER BY [TranNo]


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Top_Customer_ID
--Purpose       :Select FIRST ot LAST Customer ID
--Functionality :
--Date          :2002/09/05
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Select_Top_Customer_ID
	(
    	@CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AC_Customers_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AC_Customers_ID
            FROM AC_Customers
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AC_Customers_ID
        END

    ELSE

--> Get the LAST AC_Customers_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AC_Customers_ID
            FROM AC_Customers
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AC_Customers_ID DESC
        END

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Top_Prospect_ID
--Purpose       :Select FIRST ot LAST Prospect ID
--Date          :2006/03/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Select_Top_Prospect_ID
	(
    	@CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AC_Prospects_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AC_Prospects_ID
            FROM AC_Prospects
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AC_Prospects_ID
        END

    ELSE

--> Get the LAST AC_Prospects_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AC_Prospects_ID
            FROM AC_Prospects
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AC_Prospects_ID DESC
        END

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















----------------------------------------------------------------------------
--Description   :sp_AC_Set_Periodic_Billing_Batch
--Purpose       :De-activate a posted Periodic Billing batch
--Date          :2011/01/21
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Set_Periodic_Billing_Batch
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int


    SET @RetCode = 0


    BEGIN
        UPDATE AC_Periodic_Billing_Header
        SET Slu_AW_Active_ID = 5
        WHERE AC_Periodic_Billing_Header_ID = @HeaderID AND
              AW_User_Companies_ID = @CompanyID

        SET @RetCode = 1
    END


    BEGIN
        UPDATE AC_Periodic_Billing_Detail
        SET Slu_AW_Active_ID = 5
        WHERE AC_Periodic_Billing_Detail_ID = @HeaderID AND
              AW_User_Companies_ID = @CompanyID
        SET @RetCode = 2
    END



RETURN @RetCode










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




























-------------------------------------------------------------------------------
--Description   :sp_AC_Shape_Periodic_Billing_Detail
--Purpose       :Selects Periodic Billing Post History Detail Shaped
--Date          :21 JAN 2011
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AC_Shape_Periodic_Billing_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT d.AC_Periodic_Billing_Detail_ID AS [ID],
           d.AC_Periodic_Billing_Header_ID AS [HeaderID],
           d.Post AS [Post],
           d.Transaction_Date AS [Date],
           d.Ref_No AS [Ref No],
    	   ISNULL(c.Surname, '') +
           ISNULL(', ' + c.Firstnames, '') +
           ISNULL(', ' + c.Street_Address, '') +
           ISNULL(', ' + c.Suburb, '') +
           ISNULL(', ' + c.City, '') AS [Customer],
           d.AC_Customers_ID AS [CustomerID],
           tt.[Description] AS [Transaction Type],
           d.Sys_AW_Transaction_Types_ID AS [TranTypeID],
           tm.[Description] AS [Tax Method],
           d.Amount AS [Amount],
           d.Tax_Amount AS [Tax],
           d.Net_Amount AS [Net],
           gl.[Description] AS [GL Account],
           d.AB_Accounts_ID AS [GLAccountID],
           d.Comment AS [Comment],
           d.Notes AS [Notes],
           d.Email AS [E-Mail]
    FROM AC_Periodic_Billing_Detail d
        LEFT JOIN AC_Customers c
            ON d.AC_Customers_ID = c.AC_Customers_ID
        LEFT JOIN AB_Accounts gl
            ON d.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN Sys_AW_Transaction_Types tt
            ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        INNER JOIN Sys_AW_Tax_Methods tm
            ON d.Sys_AW_Tax_Methods_ID = tm.Sys_AW_Tax_Methods_ID
    WHERE d.AC_Periodic_Billing_Header_ID = @HeaderID AND
          d.AW_User_Companies_ID = @CompanyID
    ORDER BY [ID]

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AC_Shape_Periodic_Billing_Detail_Splits
--Purpose       :Selects Periodic Billing Post History Detail Splits Shaped
--Date          :21 JAN 2011
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Shape_Periodic_Billing_Detail_Splits
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT ds.AC_Periodic_Billing_Detail_Splits_ID AS [ID],
           ds.AC_Periodic_Billing_Detail_ID AS [DetailID],
           p.[Description] AS [Product],
           ds.Quantity AS [Qty],
           ds.Unit_Price AS [Unit Price],
           tm.[Description] AS [Method],
           ds.Amount AS [Item Amount],
           ds.Tax_Amount AS [Item Tax],
           ds.Net_Amount AS [Item Net]
    FROM AC_Periodic_Billing_Detail_Splits ds
        INNER JOIN AP_Products p
            ON ds.AP_Products_ID = p.AP_Products_ID
        INNER JOIN Sys_AW_Tax_Methods tm
            ON ds.Sys_AW_Tax_Methods_ID = tm.Sys_AW_Tax_Methods_ID
    WHERE ds.AC_Periodic_Billing_Header_ID = @HeaderID AND
          ds.AW_User_Companies_ID = @CompanyID
    ORDER BY [AC_Periodic_Billing_Detail_Splits_ID]












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AC_Shape_Periodic_Billing_Header
--Purpose       :Selects Cask Book IBS Post History Header Shaped
--Date          :27 FEB 2010
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Shape_Periodic_Billing_Header
	(
        @MonthID tinyint,
        @YearID smallint,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT h.AC_Periodic_Billing_Header_ID AS [ID],
           h.Posting_Type AS [Posting Type],
           h.Date_Posted AS [Date Posted],
           m.[Description] AS [Month],
           y.[Description] AS [Year],
           h.Import_Filename AS [Import File],
           ISNULL(u.FirstName + ' ', '') + ISNULL(u.Surname, '') AS [User],
           a.[Description] AS [Active],
           h.Slu_AW_Active_ID AS [ActiveID]
    FROM AC_Periodic_Billing_Header h
        INNER JOIN Slu_AW_Months m
            ON h.Slu_AW_Months_ID = m.Slu_AW_Months_ID
        INNER JOIN Slu_AW_Years y
            ON h.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        LEFT JOIN AW_Users u
            ON h.[User_ID] = u.AW_Users_ID
        LEFT JOIN Slu_AW_Active a
            ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID
    WHERE h.AW_User_Companies_ID = @CompanyID AND
          h.Slu_AW_Months_ID = @MonthID AND
          h.Slu_AW_Years_ID = @YearID
    ORDER BY h.Date_Posted DESC
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :Selects the transactions to display at POS
--Purpose       :
--Functionality :
--Parameters    : 
--Date          :2002/03/15
--Authors       :TB
--Version       :1
-------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AC_Transaction_Headers_Select
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime 
	)

AS

SET NOCOUNT ON

    SELECT        -- TOP 1000
        [No],
        Amount,
        Payment,
        Discount,
        Tax,
        [Date],
        Expiry
    FROM vw_AS_Transaction_Headers
    WHERE
        CustomerID = @CustomerID AND
        TypeID = @TransactionTypeID AND
        datediff(d, Date, @StartDate ) <= 0 AND
        datediff(d, Date, @EndDate) >= 0

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AC_Transfer_Transaction_To_Customer
--Purpose       :Transfers ONE Customer Transaction to another Customer
--Date          :2008/10/29
--Authors       :TB
--MODS 
--RL	V5.6	:2013-11-27 Moved invoice address details to new customer
--RL	V6.0	:2014-04-10 Fix address detail move
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Transfer_Transaction_To_Customer]
    (
        @OldCustomerID int,
        @NewCustomerID int,
        @TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @Total money,
            @Payment money,
            @Owing money,
            @TranTypeID tinyint,
            @ReturnValue int,
            @AS_Transactions_Address_ID int,
            @AS_Transactions_Address_Detail_ID int,
			@Date_Captured	datetime, 
			@User_ID	int, 
			@AW_User_Companies_ID int,
			@AW_YesNo_Delivery_Address int,
			@chkPOSPrintTradeName int

    SET @ReturnValue = 0
    SET @AS_Transactions_Address_ID = 0
	SET @AS_Transactions_Address_Detail_ID = 0
	SET @AW_YesNo_Delivery_Address = 0
	SET @chkPOSPrintTradeName = 0

    SELECT @Total = ISNULL(Total_Amount, 0),
           @Payment = ISNULL(Payment_Amount, 0),
           @TranTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TransactionID

    SET @Owing = @Total + @Payment

	UPDATE AS_Transactions
    SET AC_Customers_ID = @NewCustomerID
	WHERE AS_Transactions_ID = @TransactionID

     IF (@TranTypeID = 3 OR       --Invoice
          @TranTypeID = 4 OR      --Refund
          @TranTypeID = 5 OR      --Journal
          @TranTypeID = 7 OR      --Payment
          @TranTypeID = 15 OR     --Interest Journal
          @TranTypeID = 18 OR     --Settlement Discount
          @TranTypeID = 21 OR     --Back Office Payment
          @TranTypeID = 22)       --EFT Payment
        BEGIN
            UPDATE AC_Customers
            SET Account_Balance = Account_Balance - @Owing
            WHERE AC_Customers_ID = @OldCustomerID

            UPDATE AC_Customers
            SET Account_Balance = Account_Balance + @Owing
            WHERE AC_Customers_ID = @NewCustomerID
        END

	--Transfer Invoice details
	SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID,
			@AS_Transactions_Address_ID = AS_Transactions_Address_ID,
			@Date_Captured = Date_Captured,
			@User_ID = [User_ID],
			@AW_User_Companies_ID = AW_User_Companies_ID
	FROM AS_Transactions_Address
	WHERE AS_Transactions_ID = @TransactionID
	
	IF @AS_Transactions_Address_Detail_ID <> 0
	BEGIN	
		
		SELECT @chkPOSPrintTradeName = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkPOSPrintTradeName'
		AND Control_Index = 0
		
		IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions_Address
			WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
			AND AS_Transactions_Address_ID <> @AS_Transactions_Address_ID
		)
		BEGIN
			IF EXISTS
			(
				SELECT 1
				FROM AC_Customers
				WHERE AC_Customers_ID = @NewCustomerID
				AND ISNULL(LTRIM(RTRIM(Delivery_Address)),'') <> ''
				AND ISNULL(LTRIM(RTRIM(Delivery_Suburb)),'') <> ''
				AND ISNULL(LTRIM(RTRIM(Delivery_City)),'') <> ''
				AND ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),'') <> ''
			)
			BEGIN
				SET @AW_YesNo_Delivery_Address = 1
			END
			
			IF EXISTS
			(
				SELECT 1
				FROM Sys_AW_Options
				WHERE Control_Name = 'optPOSPrintAddress'
				AND Control_Index = 1
				AND Control_Value = 'True'
			)
			BEGIN --Street Address
				INSERT INTO AS_Transactions_Address_Detail
				(
					AC_Customers_ID, 
					Inv_Address1, 
					Inv_Address2, 
					Inv_City, 
					Inv_Code, 
					Delivery_Address, 
					Delivery_Suburb, 
					Delivery_City, 
					Delivery_Post_Code, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Customer_Name, 
					Tax_Number, 
					AW_YesNo_Delivery_Address, 
					AW_YesNo_Invoice
				)
				SELECT 
					AC_Customers_ID, 
					ISNULL(LTRIM(RTRIM(Street_Address)),''), 
					ISNULL(LTRIM(RTRIM(Suburb)),''), 
					ISNULL(LTRIM(RTRIM(City)),''), 
					ISNULL(LTRIM(RTRIM(Street_Post_Code)),''),
					ISNULL(LTRIM(RTRIM(Delivery_Address)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Suburb)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_City)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),''), 
					@Date_Captured, 
					@User_ID,
					@AW_User_Companies_ID,
					CASE WHEN @chkPOSPrintTradeName = 1
					THEN
						CASE WHEN ISNULL(Initials,'') = ''
						THEN
							CASE WHEN ISNULL(Firstnames,'') = ''
							THEN LTRIM(RTRIM(Surname))
								ELSE LTRIM(RTRIM(Surname)) + ' / ' + LTRIM(RTRIM(Firstnames))
							END
						ELSE
							CASE WHEN ISNULL(Firstnames,'') = '' 
							THEN LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) 
								ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) + ' / ' + LTRIM(RTRIM(Firstnames))
							END
						END
					ELSE
						CASE WHEN ISNULL(Initials,'') = ''
						THEN LTRIM(RTRIM(Surname))
							ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))
						END
					END,					
					ISNULL(LTRIM(RTRIM(Tax_Number)),''), 
					@AW_YesNo_Delivery_Address, 
					1
				FROM AC_Customers
				WHERE AC_Customers_ID = @NewCustomerID
				
				SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
				
				UPDATE AS_Transactions_Address
				SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
				WHERE AS_Transactions_ID = @TransactionID
			END
			ELSE
			BEGIN --POSTAL Address
				INSERT INTO AS_Transactions_Address_Detail
				(
					AC_Customers_ID, 
					Inv_Address1, 
					Inv_Address2, 
					Inv_City, 
					Inv_Code, 
					Delivery_Address, 
					Delivery_Suburb, 
					Delivery_City, 
					Delivery_Post_Code, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Customer_Name, 
					Tax_Number, 
					AW_YesNo_Delivery_Address, 
					AW_YesNo_Invoice
				)
				SELECT 
					AC_Customers_ID, 
					ISNULL(LTRIM(RTRIM(Post_Box)),''), 
					ISNULL(LTRIM(RTRIM(Post_Office)),''), 
					ISNULL(LTRIM(RTRIM(City)),''), 
					ISNULL(LTRIM(RTRIM(Post_Code)),''),
					ISNULL(LTRIM(RTRIM(Delivery_Address)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Suburb)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_City)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),''), 
					@Date_Captured, 
					@User_ID,
					@AW_User_Companies_ID, 
					CASE @chkPOSPrintTradeName
					WHEN 1 THEN					 
						ISNULL(Surname,'') + ' / ' + ISNULL(Firstnames,'') 
					ELSE
						ISNULL(Surname,'') 					
					END,
					ISNULL(LTRIM(RTRIM(Tax_Number)),''), 
					@AW_YesNo_Delivery_Address, 
					1
				FROM AC_Customers
				WHERE AC_Customers_ID = @NewCustomerID	
				
				SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()				
				
				UPDATE AS_Transactions_Address
				SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
				WHERE AS_Transactions_ID = @TransactionID
			END	
		END
		ELSE
		BEGIN
			UPDATE AS_Transactions_Address_Detail
			SET AC_Customers_ID = @NewCustomerID
			WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
		END
		
	END

    SET @ReturnValue = 1

    RETURN @ReturnValue

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















---------------------------------------------------------------------------------
--Description   :sp_AC_Update_CBilling_Submission
--Purpose       :Update CBilling submission
--Date          :2004/03/04
--Authors       :TB
--Version       :1.0.0
--MODS          :04/10/05 - Added Xmit_Date and Xmit_File filter in WHERE clause
---------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Update_CBilling_Submission
    (
        @CBillingID int,
        @XmitDate datetime,
        @XmitFile varchar(20)
    )

AS

SET NOCOUNT ON


    UPDATE AS_Transactions_CBilling
    SET Xmit_Date = @XmitDate,
        Xmit_File = @XmitFile
    WHERE AS_Transactions_CBilling_ID = @CBillingID AND
          Xmit_Date IS NULL AND
          LTRIM(RTRIM(Xmit_File)) = ''



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















---------------------------------------------------------------------------------
--Description   :sp_AC_Update_CSales_Submission
--Purpose       :Update CSales submission
--Date          :2004/03/04
--Authors       :TB
--Version       :1.0.0
--MODS          :04/10/05 - Removed superflous @CBillingID input parameter
--              :24/02/06 - Increased @XmitFile fieldsize to varchar(100)
---------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Update_CSales_Submission
    (
--        @CBillingID int,
        @XmitDate datetime,
        @XmitFile varchar(100)
    )

AS

SET NOCOUNT ON


    UPDATE AS_Transactions_CBilling
    SET Xmit_Date = @XmitDate,
        Xmit_File = @XmitFile
    WHERE Xmit_Date IS NULL AND
          LTRIM(RTRIM(Xmit_File)) = ''



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AC_Update_Customer_CostPlus_Categories
--Purpose       :
--Date          :2007/07/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Update_Customer_CostPlus_Categories
	(
        @CustomerID int,
        @Category int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AC_Customers_ID
            FROM AC_Customers
            WHERE AC_Customers_ID = @CustomerID

        )
        BEGIN
            UPDATE AC_Customers
            SET Lup_AC_Markup_Categories_ID = @Category
            WHERE AC_Customers_ID = @CustomerID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AC_Update_Customer_Discount_Categories
--Purpose       :
--Date          :2006/10/07
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Update_Customer_Discount_Categories
	(
        @CustomerID int,
        @Category int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AC_Customers_ID
            FROM AC_Customers
            WHERE AC_Customers_ID = @CustomerID

        )
        BEGIN
            UPDATE AC_Customers
            SET Lup_AC_Discount_Categories_ID = @Category
            WHERE AC_Customers_ID = @CustomerID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AC_Update_Customer_Notes
--Purpose       :Update the Notes
--Date          :2008/07/17
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AC_Update_Customer_Notes
	(
        @CustomerID int,
        @Notes varchar(500)
    )

AS

SET NOCOUNT ON

    UPDATE AC_Customers
    SET Notes = @Notes
    WHERE AC_Customers_ID = @CustomerID


        
SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AC_Update_Delivery_Details
--Purpose       :Updare the Delivery Address, Contact, Tel No, E-mail address
--Parameters    :OUTPUT
--Date          :2008/06/14
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Update_Delivery_Details
	(
        @CustomerID int,
        @Delivery1 varchar(40),
        @Delivery2 varchar(40),
        @Delivery3 varchar(30),
        @PostCode varchar(10),
        @ContactName varchar(30),
        @WorkTelNo varchar(16),
        @ContactEmail varchar(40)
    )

AS

SET NOCOUNT ON

    UPDATE AC_Customers
    SET Delivery_Address = @Delivery1,
        Delivery_Suburb = @Delivery2,
        Delivery_City = @Delivery3,
        Delivery_Post_Code = @PostCode,
        Contact_Name = @ContactName,
        Work_Tel_No = @WorkTelNo,
        Home_Email = @ContactEmail
    WHERE AC_Customers_ID = @CustomerID


        
SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














----------------------------------------------------------------------------
--Description   :sp_AC_Update_Status_From_History
--Purpose       :Updates Customer Catalog after ADD/UPDATE Account Status History
--Date          :2004/07/15
--Authors       :TB
--Version       :1.0
--MODS          :06/09/04 - Replaced Sys_AC_Account_Types_ID with
--              :           Sys_AC_Account_Status_ID !!!
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Update_Status_From_History
    (
        @CustomerID int,
        @AccountStatusID tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

	UPDATE AC_Customers
    SET Sys_AC_Account_Status_ID = @AccountStatusID
	WHERE AC_Customers_ID = @CustomerID AND
	      AW_User_Companies_ID = @CompanyID

    SET @ReturnValue = 1

    RETURN @ReturnValue

SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















----------------------------------------------------------------------------
--Description   :sp_AC_Update_Terms_From_History
--Purpose       :Updates Customer Catalog after ADD/UPDATE Credit Terms History
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AC_Update_Terms_From_History
    (
        @CustomerID int,
        @CreditTermsID tinyint,
        @TermsOfSaleID int,
        @NewLimit money,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

	UPDATE AC_Customers
    SET Slu_AW_Credit_Terms_ID = @CreditTermsID,
        Sys_AC_Credit_Term_Types_ID = @TermsOfSaleID,
        Credit_Limit = @NewLimit
	WHERE AC_Customers_ID = @CustomerID AND
	      AW_User_Companies_ID = @CompanyID

    SET @ReturnValue = 1

    RETURN @ReturnValue

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AC_Verify_Period_Interest_Charged
--Purpose       :Check if a CUSTOMER Period Procedure has already been done
--              :
--Parameters    :
--Date          :2002/06/26
--Authors       :TB
--Version       :1.0.0
--MODS          :02/11/02 - Modified validation criteria to find a interest charge
--              :           in the CURRENT ACCOUNTING PERIOD
--              :03/02/03 - Modified WHERE for any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AC_Verify_Period_Interest_Charged
	(
        @MonthID int,
        @YearID int,
        @CompanyID int,
        @GLTranID int OUTPUT,
        @GLTranDate DateTime OUTPUT,
        @LastPeriodProcedureDate DateTime OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @AccountingPeriodDate datetime,
            @EndPeriod varchar(6)

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @GLTranID = NULL
    SET @GLTranDate = NULL

--> Check if a Interest already charged for THIS PERIOD since LAST PERIOD PROCEDURE
    SELECT TOP 1 @GLTranID = AB_GL_Transactions_ID,
                 @GLTranDate = AB_Transaction_Date
    FROM AB_GL_Transactions
    WHERE Sys_AB_Transaction_Types_ID = 23 AND    --Accounts Receivable - Interest
          dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @EndPeriod


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









------------------------------------------------------------------------------
--Description   :sp_AC_Verify_Period_Procedure
--Purpose       :Check if a CUSTOMER Period Procedure has already been done
--              :
--Parameters    :
--Date          :2002/03/24
--Authors       :TB
--Version       :1.0.0
--MODS          :02/11/02 - Added validate using @CompanyID
--              :02/11/02 - Added @ProcedureType after including GL Period Procedure
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AC_Verify_Period_Procedure
	(
        @ProcedureType int,
        @MonthID int,
        @YearID int,
        @CompanyID int,
        @ProcedureID int OUTPUT,
        @ProcedureDate DateTime OUTPUT
	)

AS

SET NOCOUNT ON

    SET @ProcedureID = NULL
    SET @ProcedureDate = NULL

--> Check if a Month-End procedure for this PERIOD already exists
	SELECT @ProcedureID = AW_Period_Procedures_ID,
           @ProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE AW_User_Companies_ID = @CompanyID AND
         [Month] = @MonthID AND
         [Year] = @YearID AND
          Sys_AW_Period_Procedure_Types_ID = @ProcedureType

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AF_Casing_Credit_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (Casing Credit Refund)
--              :1. UPDATES AS_Transactions: Total_Cost
--              :2. UPDATES On_Hand and Average Cost for all JOB Products 
--              :3. INSERTS Non-GL Stock Adjustments for all JOB Products
--              :NB NB - NO GL ENTRIES ARE REQUIRED BECAUSE EXTERNAL PROCEDURES
--              :        (Day-End) WRITE ALL REQUIRED GL ENTRIES AUTOMATICALLY
--Functionality :AS_Transactions types with Detail only: 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/05/10
--Authors       :TB
--MODS          :
--2004.5.2      :04/07/11 - Added an additional Adjustment (Type 1 Qty) to deduct the stock
--              :           that was added by the Customer Refund for Credit Credit
--              :06/07/11 - Reworked and checked ALL calculations and DB updates
--              :10/07/11 - Added GL Postings to audit trail inventory movement
--              :           especially important in SPLIT CONTINOUS INVENTORY
--              :13/07/11 - Replaced @JobTicketID with @JobNo in @Note text
--2004.5.5      :17/10/11 - Fixed UPDATE Header Tran Total_Cost section that set the Total_Cost =
--              :           the COST OF THE CURRENT PRODUCT being inserted !! (No MULTIPLES CREDITS)
--              :           and DID NOT ADD EACH PRODUCT COST to the Total_Cost of the Doc Header 
--V6.2 RL	2016-06-26	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Casing_Credit_Insert]
    (
		@DocumentID int,
		@JobTicketID int,
        @CasingProductID int,
        @StockProductID int,
		@Qty decimal(9,3),
		@CasingCredit money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobNo int,
        @Make int,
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @AdjustmentsID int,
    		@OriginalPrice money,
            @SmallMake varchar(6),
            @RepairProductID int,
            @OtherProductID int,
            @RetreadCost money,
            @RepairCost money,
            @OtherCost money,
            @FactoryCosts money,
            @TotalCost money,
            @PurchasesControlGLID int,
            @InventoryControlGLID int,
            @CasingCode varchar(20),
            @RepairCode varchar(20),
            @OtherCode varchar(20),
            @StockCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @Prev_LastCostTotal money,
            @Prev_AvgCostTotal money,
            @New_Last_Cost money,
            @New_Average_Cost money,
        	@New_On_Hand decimal(9,3),
            @New_LastCostTotal money,
            @New_AvgCostTotal money,
            @AdjustmentType tinyint,
            @User_Name varchar(40),
            @Note varchar(70),
            @GRVID int,
            @InvoiceNo varchar(20),
            @RefundNo varchar(19),
            @NoCI tinyint,
            @NormalCI tinyint,
            @SplitCI tinyint,
            @CasingTypeDesc varchar(50),
            @RepairTypeDesc varchar(50),
            @OtherTypeDesc varchar(50),
            @StockTypeDesc varchar(50),
            @CasingGLDesc varchar(50),
            @RepairGLDesc varchar(50),
            @OtherGLDesc varchar(50),
            @StockGLDesc varchar(50),
            @GLCasingID int,
            @GLRepairID int,
            @GLOtherID int,
            @GLStockID int,
            @Narration varchar(50),
            @TempRef varchar(20),
            @InsertGLTran bit,
            @TempCost money,
            @TempCasingCredit money,
            @MonthID tinyint,
            @YearID int,
            @OppositeQty decimal(9,3)


    SELECT @RefundNo = ISNULL(Transaction_Number, '')
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @DocumentID


    SELECT @SmallMake = LEFT(ISNULL(Old_Code, ''), 6)
    FROM Lup_AP_Product_Manufacturers
    WHERE Lup_AP_Product_Manufacturers_ID = @Make


    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
--     UPDATE AS_Transactions
--     SET Total_Cost = -@CasingCredit
--     WHERE AS_Transactions_ID = @DocumentID

    -- NEW 2004.5.5 - Fixed to enable MULTIPLE CREDITS on ONE REFUND
    SET @TempCasingCredit = ABS(@CasingCredit) * -1

    UPDATE AS_Transactions
    SET Total_Cost = ISNULL(Total_Cost, 0) + @TempCasingCredit
    WHERE AS_Transactions_ID = @DocumentID
    ---------------------------------------------------------------------------


	SELECT @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
	FROM AP_Products
	WHERE AP_Products_ID = @CasingProductID


---------------------------------------------------------------------------
--> Do the CUSTOMER REFUND
---------------------------------------------------------------------------
	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@CasingProductID,
			-@Qty,
			@CasingCredit,
			@CasingCredit,
			@OriginalPrice,
			-@Tax,
			-@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)


    --> Add Refund Qty to Product On_Hand
    IF @CasingProductID > 0
        BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty
            WHERE AP_Products_ID = @CasingProductID
        END
        
	--Update Bin Qty
	IF @Qty <> 0
	BEGIN
		EXEC sp_AP_Products_Bins_Update_Insert 
			@CasingProductID,	--@ProductID int,
			1,					--@ProductBinID int,
    		@Qty,				--@Qty decimal(9,3)
    		'F CASCRED',		--@Source varchar(10),
    		0,					--@Batch_No
    		@UserID,			--@UserID int,
    		@CompanyID			--@CompanyID int
	END	
        
---------------------------------------------------------------------------


---------------------------------------------------------------------------
--> Do the STOCK ADJUSTMENTS
---------------------------------------------------------------------------

	SELECT @User_Name = LEFT(ISNULL(FirstName, ''), 20)
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --> Get the Job Ticket info - CHECK if ANY LOCKS on the record !!
    SELECT @RepairProductID =ISNULL(AP_Repair_Products_ID, 0),
           @OtherProductID = ISNULL(AP_Other_Products_ID, 0),
           @RetreadCost = ISNULL(Retread_Cost, 0),
           @RepairCost = ISNULL(Repair_Cost, 0),
           @OtherCost = ISNULL(Other_Cost, 0),
           @GRVID =  ISNULL(AO_GRV_ID, 0),
           @InvoiceNo = ISNULL(Invoice_No, '')
    FROM AF_Job_Tickets
    WHERE AF_Job_Tickets_ID = @JobTicketID

    SET @FactoryCosts = @RetreadCost + @RepairCost + @OtherCost
    SET @TotalCost = @FactoryCosts + @CasingCredit

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0


    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF @CasingProductID > 0
        BEGIN
            ---------------------------------------------------------------------------
            --> Get the CASING (Retread) Product stuff
            ---------------------------------------------------------------------------
        	SELECT @CasingCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
                   @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
                   @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
        		   @Prev_On_Hand = ISNULL(On_Hand, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @CasingProductID

            ---------------------------------------------------------------------------
            --> Calculate AVERAGE COST (lifted from Stock Returns)
            ---------------------------------------------------------------------------
            SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
            SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

            SET @New_LastCostTotal = @Prev_LastCostTotal - @RetreadCost
            SET @New_AvgCostTotal = @Prev_AvgCostTotal - @RetreadCost

            SET @New_On_Hand = @Prev_On_Hand - @Qty

            IF @New_On_Hand <> 0
                BEGIN
                    -- Calculate NEW Average_Cost
                    SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
                END
            ELSE
                BEGIN
                    -- Retain OLD Average_Cost
                    SET @New_Average_Cost = @Prev_Average_Cost
                END

            ---------------------------------------------------------------------------
            --> ADJUST Factory GRV Stock of CASING PRODUCT
            ---------------------------------------------------------------------------
        	UPDATE AP_Products 
        	SET Average_Cost = @New_Average_Cost,
                On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @CasingProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@CasingProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 6
            SET @Note = 'Casing Credit GRVFAC Adjustment ' + @InvoiceNo + '(' + CONVERT(varchar(10), @GRVID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 


        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @CasingProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        			@Prev_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
            ---------------------------------------------------------------------------

            ---------------------------------------------------------------------------
            --> ADJUST Customer Refund Stock of CASING PRODUCT
            ---------------------------------------------------------------------------
            ---------------------------------------------------------------------------
            --> Prepare values for Qty Adjustment (costs must remain same as above)
            ---------------------------------------------------------------------------
            SET @Prev_On_Hand = @New_On_Hand
            SET @New_On_Hand = @Prev_On_Hand - @Qty

        	UPDATE AP_Products 
        	SET On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @CasingProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@CasingProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 1
            SET @Note = 'Casing Credit REFUND Adjustment ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 

        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @CasingProductID,
                    @AdjustmentType,
        			@CasingCredit,
                    @CasingCredit,
        			@Prev_On_Hand ,
        			@CasingCredit,
                    @CasingCredit,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
            ---------------------------------------------------------------------------

        END
    ---------------------------------------------------------------------------

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0

    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF @RepairProductID > 0
        BEGIN
            ---------------------------------------------------------------------------
            --> Get the REPAIR Product stuff
            ---------------------------------------------------------------------------
        	SELECT @RepairCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
                   @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
                   @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
        		   @Prev_On_Hand = ISNULL(On_Hand, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @RepairProductID

            ---------------------------------------------------------------------------
            --> Calculate AVERAGE COST (lifted from Stock Returns)
            ---------------------------------------------------------------------------
            SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
            SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

            SET @New_LastCostTotal = @Prev_LastCostTotal - @RepairCost
            SET @New_AvgCostTotal = @Prev_AvgCostTotal - @RepairCost

            SET @New_On_Hand = @Prev_On_Hand - @Qty

            IF @New_On_Hand <> 0
                BEGIN
                    -- Calculate NEW Average_Cost
                    SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
                END
            ELSE
                BEGIN
                    -- Retain OLD Average_Cost
                    SET @New_Average_Cost = @Prev_Average_Cost
                END

            ---------------------------------------------------------------------------
            --> ADJUST Stock of REPAIR PRODUCT
            ---------------------------------------------------------------------------
        	UPDATE AP_Products 
        	SET Average_Cost = @New_Average_Cost,
                On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @RepairProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@RepairProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 6
            SET @Note = 'Casing Credit REFUND Adjustment ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 


        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @RepairProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        			@Prev_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
        END
    ---------------------------------------------------------------------------

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0

    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF @OtherProductID > 0
        BEGIN
            ---------------------------------------------------------------------------
            --> Get the OTHER Product stuff
            ---------------------------------------------------------------------------
        	SELECT @OtherCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
                   @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
                   @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
        		   @Prev_On_Hand = ISNULL(On_Hand, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @OtherProductID

            ---------------------------------------------------------------------------
            --> Calculate AVERAGE COST (lifted from Stock Returns)
            ---------------------------------------------------------------------------
            SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
            SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

            SET @New_LastCostTotal = @Prev_LastCostTotal - @OtherCost
            SET @New_AvgCostTotal = @Prev_AvgCostTotal - @OtherCost

            SET @New_On_Hand = @Prev_On_Hand - @Qty

            IF @New_On_Hand <> 0
                BEGIN
                    -- Calculate NEW Average_Cost
                    SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
                END
            ELSE
                BEGIN
                    -- Retain OLD Average_Cost
                    SET @New_Average_Cost = @Prev_Average_Cost
                END

            ---------------------------------------------------------------------------
            --> ADJUST Stock of OTHER PRODUCT
            ---------------------------------------------------------------------------
        	UPDATE AP_Products 
        	SET Average_Cost = @New_Average_Cost,
                On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @OtherProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@OtherProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 6
            SET @Note = 'Casing Credit REFUND Adjustment ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 

        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @OtherProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        			@Prev_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
        END
    ---------------------------------------------------------------------------


    ---------------------------------------------------------------------------
    --> Do the STOCK Product ADJUSTMENT
    ---------------------------------------------------------------------------

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0

    ---------------------------------------------------------------------------
    --> Get the STOCK Product stuff
    ---------------------------------------------------------------------------
    SELECT @StockCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
           @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
           @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
		   @Prev_On_Hand = ISNULL(On_Hand, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @StockProductID

    ---------------------------------------------------------------------------
    --> Calculate AVERAGE COST (lifted from Stock Returns)
    ---------------------------------------------------------------------------
    SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
    SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

    SET @New_LastCostTotal = @Prev_LastCostTotal + @TotalCost
    SET @New_AvgCostTotal = @Prev_AvgCostTotal + @TotalCost

    SET @New_On_Hand = @Prev_On_Hand + @Qty
    SET @New_Last_Cost = @TotalCost

    IF @New_On_Hand <> 0
        BEGIN
            -- Calculate NEW Average_Cost
            SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
        END
    ELSE
        BEGIN
            -- Retain OLD Average_Cost
            SET @New_Average_Cost = @Prev_Average_Cost
        END

    ---------------------------------------------------------------------------
    --> ADJUST Stock of STOCK PRODUCT
    ---------------------------------------------------------------------------
	UPDATE AP_Products 
	SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Average_Cost,
        On_Hand = On_Hand + @Qty  
	WHERE AP_Products_ID = @StockProductID

	--Update Bin Qty
	IF @Qty <> 0
	BEGIN
		--Roadmaster Incorrect sign
		--SET @OppositeQty = @Qty * -1
		EXEC sp_AP_Products_Bins_Update_Insert 
			@StockProductID,	--@ProductID int,
			1,					--@ProductBinID int,
			@Qty,				--@Qty decimal(9,3)
			'F CASCRED',		--@Source varchar(10),
			0,					--@Batch_No
			@UserID,			--@UserID int,
			@CompanyID			--@CompanyID int
	END	

    SET @AdjustmentType = 6
    SET @Note = 'Casing Credit TRF to STOCK Adjustment C/N ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
    SET @Note = LEFT(@Note, 70) 
    SET @AdjustmentsID = 0


	INSERT INTO AP_Inventory_Adjustments
        (
			AP_Products_ID,
            Sys_AP_Adjustment_Types_ID,
			Previous_Last_Cost,
            Previous_Average_Cost,
			Previous_On_Hand,
			New_Last_Cost,
            New_Average_Cost,
			New_On_Hand,
			Note,
			Date_Captured,
			[User_ID],
			AW_User_Companies_ID,
        	Lup_AP_Product_Bins_ID
        )
	VALUES
        (
            @StockProductID,
            @AdjustmentType,
			@Prev_Last_Cost,
            @Prev_Average_Cost,
			@Prev_On_Hand ,
			@New_Last_Cost,
            @New_Average_Cost,
			@New_On_Hand,
			@Note,
			getdate(),
			@UserID,
			@CompanyID,
        	1 --Defaulted to 1
        )

    SELECT @AdjustmentsID = SCOPE_IDENTITY() 
    ---------------------------------------------------------------------------


    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    -- NOW DO INVENTORY ACCOUNT TRF GL Transactions
    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------


    ---------------------------------------------------------------------------
    -- TRF from SOURCE INVENTORY account and put to TARGET INVENTORY account
    ---------------------------------------------------------------------------

    --    DR:    STOCK PRODUCT     -->    @FactoryCosts
    --    CR:    CASING PRODUCT    -->    @RetreadCost
    --    CR:    REPAIR PRODUCT    -->    @RepairCost
    --    CR:    OTHER PRODUCT     -->    @OtherCost
    ----------------------------------------------------------------
    -- If @SplitCI the Day-End handles the REFUND like this:
    --        Debits    Casing Refund to    INVENTORY - Casings
    --        Credits   Casing Refund to    C.O.S. - Casings 
    ----------------------------------------------------------------
    -- We must transfer the inventory like this:
    --    DR:    STOCK PRODUCT     -->    @CasingCredit
    --    CR:    CASING PRODUCT    -->    @CasingCredit
 
    --    Day-End will handle the REFUND (@CasingCredit) GL Transactions
    ---------------------------------------------------------------------------

    ---------------------------------------------------------------------
    --> Get NORMAL Continuous Inventory STOCK RECEIPTS parameter setting
    ---------------------------------------------------------------------
    SET @NormalCI = '0'

    SELECT @NormalCI = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = 'CheckBox' AND
          Control_Name = 'chkGRVtoInventoryCOS' AND
          Control_Index = 0 AND
          AW_User_Companies_ID = @CompanyID

    ---------------------------------------------------------------------
    --> Get SPLIT Continuous Inventory STOCK RECEIPTS parameter setting
    ---------------------------------------------------------------------
    SET @SplitCI = '0'

    SELECT @SplitCI = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = 'CheckBox' AND
          Control_Name = 'chkUseProductPurchasesGL' AND
          Control_Index = 0 AND
          AW_User_Companies_ID = @CompanyID


    ---------------------------------------------------------------------
    --> Get NO Continuous Inventory is used then use PURCHASES CONTROl
    ---------------------------------------------------------------------
    SET @NoCI = 0

    IF @NormalCI = 0 AND @SplitCI = 0
        BEGIN
            SET @NoCI = 1
        END

    ---------------------------------------------------------------------
    --> Get the PURCHASES CONTROL if NO Continuous Inventory
    ---------------------------------------------------------------------
    SELECT @PurchasesControlGLID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 301        --Purchases Control

    ---------------------------------------------------------------------
    --> Get the INVENTORY CONTROL if NOT Split Continuous Inventory
    ---------------------------------------------------------------------
    SELECT @InventoryControlGLID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 601        --Inventory Control
    ---------------------------------------------------------------------

    SELECT @MonthID = ISNULL(Slu_AW_Months_ID, 1),
           @YearID = ISNULL(Slu_AW_Years_ID, 1)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    SET @TempCost = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @Narration = 'Casing Credit Inventory TRF Job No ' + CONVERT(varchar(10), @JobNo)
    SET @Narration = LEFT(@Narration, 50)


    ---------------------------------------------------------------------
    --> INSERT GL INVENTORY TRF Tran for CASING PRODUCT here
    ---------------------------------------------------------------------

    --> Create GL TRANSACTIONS for SPLIT Inventory
    IF @SplitCI = 1
        BEGIN
            --> Get the CASING PRODUCT TYPE and SET GL Description
            IF @CasingProductID > 0
                BEGIN
                    SET @CasingTypeDesc = ''

        			SELECT @CasingTypeDesc = ISNULL(t.Description, '')
        			FROM AP_Products p
                        LEFT JOIN Lup_AP_Product_Types t
                            ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
        			WHERE p.AP_Products_ID = @CasingProductID

                    SET @CasingGLDesc = LEFT('INVENTORY - ' + @CasingTypeDesc, 50)
                END

            --> Get the REPAIR PRODUCT TYPE and SET GL Description
            IF @RepairProductID > 0
                BEGIN
                    SET @RepairTypeDesc = ''

        			SELECT @RepairTypeDesc = ISNULL(t.Description, '')
        			FROM AP_Products p
                        LEFT JOIN Lup_AP_Product_Types t
                            ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
        			WHERE p.AP_Products_ID = @RepairProductID

                    SET @RepairGLDesc = LEFT('INVENTORY - ' + @RepairTypeDesc, 50)
                END

            --> Get the OTHER PRODUCT TYPE and SET GL Description
            IF @OtherProductID > 0
                BEGIN
                    SET @OtherTypeDesc = ''

        			SELECT @OtherTypeDesc = ISNULL(t.Description, '')
        			FROM AP_Products p
                        LEFT JOIN Lup_AP_Product_Types t
                            ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
        			WHERE p.AP_Products_ID = @OtherProductID

                    SET @OtherGLDesc = LEFT('INVENTORY - ' + @OtherTypeDesc, 50)
                END

            --> Get the STOCK PRODUCT TYPE and SET GL Description
            IF @StockProductID > 0
                BEGIN
                    SET @StockTypeDesc = ''

        			SELECT @StockTypeDesc = ISNULL(t.Description, '')
        			FROM AP_Products p
                        LEFT JOIN Lup_AP_Product_Types t
                            ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
        			WHERE p.AP_Products_ID = @StockProductID

                    SET @StockGLDesc = LEFT('INVENTORY - ' + @StockTypeDesc, 50)
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Casing Product
            ---------------------------------------------------------------------
            IF @CasingProductID > 0
                BEGIN
                    SET @GLCasingID = 0

                    SELECT TOP 1 @GLCasingID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @CasingGLDesc AND
                          Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                          Slu_AW_Active_ID = 1

                    IF @GLCasingID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLCasingID = sp_AB_Insert_System_GL_Account
                                                    @CasingGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Repair Product
            ---------------------------------------------------------------------
            IF @RepairProductID > 0
                BEGIN
                    SET @GLRepairID = 0

                    SELECT TOP 1 @GLRepairID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @RepairGLDesc AND
                          Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                          Slu_AW_Active_ID = 1

                    IF @GLRepairID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLRepairID = sp_AB_Insert_System_GL_Account
                                                    @RepairGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Other Product
            ---------------------------------------------------------------------
            IF @OtherProductID > 0
                BEGIN
                    SET @GLOtherID = 0

                    SELECT TOP 1 @GLOtherID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @OtherGLDesc AND
                          Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                          Slu_AW_Active_ID = 1

                    IF @GLOtherID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLOtherID = sp_AB_Insert_System_GL_Account
                                                    @OtherGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Other Product
            ---------------------------------------------------------------------
            IF @StockProductID > 0
                BEGIN
                    SET @GLStockID = 0

                    SELECT TOP 1 @GLStockID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @StockGLDesc AND
                          Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                          Slu_AW_Active_ID = 1

                    IF @GLStockID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLStockID = sp_AB_Insert_System_GL_Account
                                                    @StockGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END
            ---------------------------------------------------------------------

            SET @TempCost = @RetreadCost * -1

            IF @CasingProductID > 0
                BEGIN
                    SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLCasingID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END

            SET @TempCost = @RepairCost * -1

            IF @RepairProductID > 0
                BEGIN
                    SET @TempRef = @RepairCode + '(' + CONVERT(varchar(10), @RepairProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLRepairID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END

            SET @TempCost = @OtherCost * -1

            IF @OtherProductID > 0
                BEGIN
                    SET @TempRef = @OtherCode + '(' + CONVERT(varchar(10), @OtherProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLOtherID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END

            IF @StockProductID > 0
                BEGIN
                    SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLStockID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @FactoryCosts,
                            @UserID,
                            @CompanyID
                END


            ----------------------------------------------------------------
            -- If @SplitCI the Day-End handles the REFUND like this:
            --        Debits    Casing Refund to    INVENTORY - Casings
            --        Credits   Casing Refund to    C.O.S. - Casings 
            ----------------------------------------------------------------
            -- We must transfer the inventory like this:
            --    DR:    STOCK PRODUCT     -->    @CasingCredit
            --    CR:    CASING PRODUCT    -->    @CasingCredit
            ----------------------------------------------------------------

            SET @Narration = 'Casing Refund Day-End Inventory TRF Job No ' + CONVERT(varchar(10), @JobNo)
            SET @Narration = LEFT(@Narration, 50)

            SET @TempCost = @CasingCredit * -1

            IF @CasingProductID > 0
                BEGIN
                    SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLCasingID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END


            IF @StockProductID > 0
                BEGIN
                    SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLStockID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @CasingCredit,
                            @UserID,
                            @CompanyID
                END


        END        --IF @SplitCI = 1
        ------------------------------------------------------------------------------

    --> Create GL TRANSACTION for Purchases Control 301 - IN and OUT
    ELSE
    IF @NoCI = 1
        BEGIN
            SET @TempCost = @FactoryCosts * -1

            SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @PurchasesControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @TempCost,
                    @UserID,
                    @CompanyID


            SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @PurchasesControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @FactoryCosts,
                    @UserID,
                    @CompanyID
        END
        ------------------------------------------------------------------------------

    --> DEFAULT - Create GL TRANSACTION for Inventory Control 601 - IN and OUT
    ELSE        --> @NormalCI = 1 - NORMAL CONTINUOUS INVENTORY
        BEGIN
            SET @TempCost = @FactoryCosts * -1

            SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @InventoryControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @TempCost,
                    @UserID,
                    @CompanyID


            SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @InventoryControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @FactoryCosts,
                    @UserID,
                    @CompanyID
        END    
        ------------------------------------------------------------------------------

RETURN @AdjustmentsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AF_Delete_Job_Ticket
--Purpose       :Deletes a selected Job Ticket ONLY IF IT HAS NOT BEEN GRV'D
--Date          :2011/06/10
--Authors       :TB
--MODS          : 
--RL	V6.0	2014-10-16 :Added Delete audit trail on Job Tickets & Waybills
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Delete_Job_Ticket]
    (
        @TicketID int,
        @UserID int
    )
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int
    Declare @AF_Waybills_ID		Int
    Declare @AF_Waybills_Count	Int

	Set @AF_Waybills_ID = 0
	Set @AF_Waybills_Count = 0
	
	Select @AF_Waybills_ID = ISNULL(AF_Waybills_ID,-1)
	From AF_Job_Tickets
	Where AF_Job_Tickets_ID = @TicketID

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AF_Job_Tickets_ID
            FROM AF_Job_Tickets
            WHERE AF_Job_Tickets_ID = @TicketID AND
                  AO_GRV_ID IS NULL
        )
        BEGIN
			Insert Into AF_Job_Tickets_Deleted
			(
				AF_Job_Tickets_ID,
				Post,
				Job_No,
				Job_Date,
				AC_Customers_ID,
				Order_No,
				AP_Products_ID,
				Lup_AP_Product_Manufacturers_ID,
				Serial_No,
				Lup_AF_Instructions_ID,
				Job_User_ID,
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Waybill_User_ID,
				AO_GRV_ID,
				GRV_Date,
				Invoice_No,
				Retread_Cost,
				Repair_Cost,
				Other_Cost,
				AP_Repair_Products_ID,
				AP_Other_Products_ID,
				Lup_AP_Fail_Reasons_ID,
				GRV_User_ID,
				AS_Transactions_ID,
				Billing_Date,
				Billing_No,
				Retread_Price,
				Repair_Price,
				Other_Price,
				Amount,
				Tax,
				Total,
				Comment,
				Billing_User_ID,
				AP_Inventory_Adjustments_ID,
				Adjustment_Date,
				AP_Stock_Products_ID,
				Casing_Credit,
				Stock_Cost,
				Adjustment_User_ID,
				Date_Captured,
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				Action_Date,
				Action_User_ID
			)        
			Select         
				AF_Job_Tickets_ID,
				Post,
				Job_No,
				Job_Date,
				AC_Customers_ID,
				Order_No,
				AP_Products_ID,
				Lup_AP_Product_Manufacturers_ID,
				Serial_No,
				Lup_AF_Instructions_ID,
				Job_User_ID,
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Waybill_User_ID,
				AO_GRV_ID,
				GRV_Date,
				Invoice_No,
				Retread_Cost,
				Repair_Cost,
				Other_Cost,
				AP_Repair_Products_ID,
				AP_Other_Products_ID,
				Lup_AP_Fail_Reasons_ID,
				GRV_User_ID,
				AS_Transactions_ID,
				Billing_Date,
				Billing_No,
				Retread_Price,
				Repair_Price,
				Other_Price,
				Amount,
				Tax,
				Total,
				Comment,
				Billing_User_ID,
				AP_Inventory_Adjustments_ID,
				Adjustment_Date,
				AP_Stock_Products_ID,
				Casing_Credit,
				Stock_Cost,
				Adjustment_User_ID,
				Date_Captured,
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				GETDATE(),
				@UserID
			From AF_Job_Tickets
            Where AF_Job_Tickets_ID = @TicketID
			        
            DELETE AF_Job_Tickets
            WHERE AF_Job_Tickets_ID = @TicketID

			Select @AF_Waybills_Count = COUNT(*)
			From AF_Job_Tickets
			Where ISNULL(AF_Waybills_ID,0) = @AF_Waybills_ID

			If @AF_Waybills_Count = 0
			Begin
				Exec sp_AF_Delete_Waybill @AF_Waybills_ID, @UserID
			End
			
            SET @ReturnValue = 1
        END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AF_Delete_Waybill
--Purpose       :Deletes a selected Waybill
--Date          :2011/05/05
--Authors       :TB
--MODS          :
--RL	V6.0	2014-10-16 :Added Delete audit trail on Waybills
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Delete_Waybill]
    (
        @WaybillID int,
        @UserID int
    )
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AF_Waybills_ID
            FROM AF_Waybills
            WHERE AF_Waybills_ID = @WaybillID
        )
        BEGIN
			Insert Into AF_Waybills_Deleted
			(
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Date_Captured,
				[User_ID],
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				Action_Date,
				Action_User_ID
			)
			Select 
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Date_Captured,
				[User_ID],
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				GETDATE(),
				@UserID
			From AF_Waybills
            Where AF_Waybills_ID = @WaybillID			
			
            DELETE AF_Waybills
            WHERE AF_Waybills_ID = @WaybillID

            SET @ReturnValue = 1
        END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AF_Generic_IF_EXISTS
--Purpose       :Generic VALIDATE IF VALUE IN ROW EXISTS
--Date          :2011/05/07
--Authors       :TB
--MODS          :
--2004.5.2      :09/07/11 - Added Option 3 Transaction Type = 9 validation
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Generic_IF_EXISTS
    (
        @Option tinyint,
        @FieldValue varchar(1000),
        @ActorID int,
        @CompanyID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

    IF @Option = 1
        BEGIN
            SELECT @Exists = dbo.fn_AF_Exists_Factory_JobNo(@FieldValue, @CompanyID)
        END

    ELSE
    IF @Option = 2
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Supplier_Invoice(@FieldValue, @ActorID, @CompanyID)
        END

    ELSE
    IF @Option = 3
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Supplier_Refund(@FieldValue, @ActorID, @CompanyID)
        END










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description	:sp_AF_Get_Job_Adjustment_ID
--Purpose       :Gets the ADJUSTMENT number of a Job Ticket ID (Job No)
--Date			:2011/08/28
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Get_Job_Adjustment_ID
	(
        @JobTicketID int,
        @AdjustmentID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @AdjustmentID = 0

	SELECT TOP 1 @AdjustmentID = ISNULL(AP_Inventory_Adjustments_ID, 0)
	FROM AF_Job_Tickets
	WHERE AF_Job_Tickets_ID = @JobTicketID


RETURN @AdjustmentID

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description	:sp_AF_Get_Job_Invoice_ID
--Purpose       :Gets the INVOICE number of a Job Ticket ID (Job No)
--Date			:2011/08/24
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Get_Job_Invoice_ID
	(
        @JobTicketID int,
        @BillingID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @BillingID = 0

	SELECT TOP 1 @BillingID = ISNULL(AS_Transactions_ID, 0)
	FROM AF_Job_Tickets
	WHERE AF_Job_Tickets_ID = @JobTicketID


RETURN @BillingID
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description	:sp_AF_Get_Last_Job_No
--Purpose       :Gets the last Job Ticket number
--Date			:2011/04/24
--Authors		:TB
--MODS          :
--2004.5.5      :06/10/11 - Modified to get Job Number of LAST record inserted 
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Get_Last_Job_No
	(
        @CompanyID int,
        @JobNo int OUTPUT
	)

AS

SET NOCOUNT ON

	SELECT TOP 1 @JobNo = ISNULL(Job_No, 0)
	FROM AF_Job_Tickets
	WHERE AW_User_Companies_ID = @CompanyID
--    ORDER BY Job_No DESC
    ORDER BY AF_Job_Tickets_ID DESC


RETURN @JobNo













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description	:sp_AF_Get_Last_Waybill_No
--Purpose       :Gets the last Waybill number
--Date			:2011/04/26
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Get_Last_Waybill_No
	(
        @CompanyID int,
        @WaybillNo int OUTPUT
	)

AS

SET NOCOUNT ON

	SELECT TOP 1 @WaybillNo = ISNULL(AF_Waybills_ID, 0)
	FROM AF_Waybills
	WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY ISNULL(AF_Waybills_ID, 0) DESC


RETURN @WaybillNo














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :sp_AF_Get_Product_Cost
--Purpose       :Get Product Cost using Primary Costing Method
--Date          :2011/10/17
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Get_Product_Cost
    (
        @CostMethod tinyint,
    	@ProductID int,
        @CostPrice money OUTPUT
    )

AS

SET NOCOUNT ON


    SET @CostPrice = 0


    IF @CostMethod = 0        --Average
        BEGIN
            SELECT @CostPrice = ISNULL(Average_Cost, 0)
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 1        --Last
        BEGIN
            SELECT @CostPrice = ISNULL(Last_Cost, 0)
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 2        --Standard
        BEGIN
            SELECT @CostPrice = ISNULL(Standard_Cost, 0)
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE        --Average
        BEGIN
            SELECT @CostPrice = ISNULL(Average_Cost, 0)
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END



RETURN @CostPrice













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AF_Get_Product_Unit_Price
--Purpose       :Get Product Unit Price for Factory Customer Billing
--Functionality :Applies POS BILLING rules for Cost+Plus, Contract, Discount, Normal
--              :Applies Profit Protector on PRODUCT COST WE PASS IN
--Date          :2011/05/06
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Get_Product_Unit_Price
    (
        @CompanyID int,
        @CustomerID int,
    	@ProductID int,
        @CostPrice money,
        @CostPlusEnabled tinyint,
        @UnitPrice money OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @RetailPrice money,
            @ContractPrice money,
            @MinGPPerc decimal(9, 3),
            @ApplyMinGPPerc tinyint,
            @IsCostPlusCustomer tinyint,
            @IsCostPlusProduct tinyint,
            @CostPlusGroupID smallint,
            @CostPlusCategoryID  smallint,
            @DiscGroupID smallint,
            @DiscCategoryID smallint,
            @DiscPerc decimal(9, 3),
            @DiscAmount money,
            @Today datetime,
            @GPAmount money,
            @GPPerc decimal(9, 3)


    SET @UnitPrice = 0


    --> Get the PRODUCT stuff
	SELECT @RetailPrice = ROUND(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()), 2),
           @MinGPPerc = ISNULL(Max_Discount_Perc, 0),
           @ApplyMinGPPerc = Slu_AW_YesNo_Max_Discount_Perc,
           @CostPlusGroupID = Lup_AP_Markup_Groups_ID,
           @IsCostPlusProduct = Slu_AW_YesNo_Cost_Plus_Item,
           @DiscGroupID = Lup_AP_Discount_Groups_ID
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID


    --> Get the CUSTOMER stuff
    SELECT @IsCostPlusCustomer = AW_YesNo_CostPlus_Billing_ID,
           @CostPlusCategoryID = Lup_AC_Markup_Categories_ID,
           @DiscCategoryID = Lup_AC_Discount_Categories_ID
    FROM AC_Customers
    WHERE AC_Customers_ID = @CustomerID


    --------------------------------------------------------------------
    --> COST+PLUS Billing
    --------------------------------------------------------------------
    IF @CostPlusEnabled = 1
        BEGIN
            --> Perhaps there is a COST+PLUS Price
            IF @IsCostPlusCustomer = 1
                BEGIN
                    IF @IsCostPlusProduct = 1
                        BEGIN
                            SELECT @UnitPrice = ROUND(@CostPrice + (ROUND((@CostPrice * (ISNULL(Markup_Percentage, 0) / 100)), 2)), 2)
                            FROM AS_Markup_Categories_Groups
                            WHERE Lup_AC_Markup_Categories_ID = @CostPlusCategoryID AND
                                  Lup_AP_Markup_Groups_ID = @CostPlusGroupID AND
                                  Slu_AW_Active_ID = 1

                            --> Perhaps the COSTS were ZERO !!
                            IF @UnitPrice = 0
                                BEGIN
                                    SET @UnitPrice = @RetailPrice
                                END
                        END
                END
        END


    --------------------------------------------------------------------
    --> CONTRACT Billing
    --------------------------------------------------------------------
    IF @UnitPrice = 0
        BEGIN
            SET @Today = CONVERT(datetime, CONVERT(CHAR(10), getdate(), 121))

            --> Perhaps there is an ACTIVE Contract Price
            SELECT TOP 1 @ContractPrice = ISNULL(Unit_Price, 0),
                         @DiscPerc = ISNULL(Discount_Perc, 0),
                         @DiscAmount = ISNULL(Discount_Amount, 0)
            FROM AC_Contract_Prices
            WHERE AC_Customers_ID = @CustomerID AND
                  AP_Products_ID = @ProductID AND
                 (@Today >= Start_Date AND
                  @Today <= End_Date) AND
                  Slu_AW_Active_ID = 1

            IF @ContractPrice > 0 OR @DiscPerc > 0 OR @DiscAmount > 0
                BEGIN
                    --> Do DISCOUNT% - Only ONE discount can apply - defaults to DiscPerc
                    IF @DiscPerc > 0
                        BEGIN
                            SET @DiscAmount = 0
        
                            --> 1. Contract Price with a Discount %
                            IF @ContractPrice > 0
                                BEGIN
                                    SET @UnitPrice = ROUND(@ContractPrice - (ROUND((@ContractPrice * (ISNULL(@DiscPerc, 0) / 100)), 2)), 2)
                                END
                        END

                    --> Do DISCOUNT AMOUNT
                    ELSE
                    IF @DiscAmount > 0
                        BEGIN
                            SET @DiscPerc = 0
        
                            --> 2. Contract Price with a Discount Amount
                            IF @ContractPrice > 0
                                BEGIN
                                    SET @UnitPrice = ROUND(@ContractPrice - @DiscAmount, 2)
                                END
                        END

                    --> Do CONTRACT PRICE
                    ELSE
                    IF @ContractPrice > 0
                        BEGIN
                            SET @UnitPrice = ROUND(@ContractPrice, 2)
                        END
                END
        END


    --------------------------------------------------------------------
    --> DISCOUNT Billing
    --------------------------------------------------------------------
    IF @UnitPrice = 0
        BEGIN
            --> Perhaps there is a MATRIX DISCOUNT
            SELECT @DiscPerc = Discount_Percentage
            FROM AS_Discount_Categories_Groups
            WHERE Lup_AP_Discount_Groups_ID = @DiscGroupID AND
                  Lup_AC_Discount_Categories_ID = @DiscCategoryID AND
                  Slu_AW_Active_ID = 1

            IF @DiscPerc > 0
                BEGIN
                    SET @UnitPrice = ROUND(@RetailPrice - (ROUND((@RetailPrice * (ISNULL(@DiscPerc, 0) / 100)), 2)), 2)
                END
        END


    --------------------------------------------------------------------
    --> NORMAL Billing
    --------------------------------------------------------------------
    IF @UnitPrice = 0
        BEGIN
            SET @UnitPrice = @RetailPrice
        END


    --------------------------------------------------------------------
    --> PROFIT PROTECTOR
    --------------------------------------------------------------------
    IF @MinGPPerc <> 0
        BEGIN
            SET @GPAmount = @UnitPrice - @CostPrice

            IF @UnitPrice <> 0
                BEGIN
                    SET @GPPerc = ROUND(((@GPAmount / @UnitPrice) * 100), 2)
                END

            IF @GPPerc < @MinGPPerc
                BEGIN
                    IF @ApplyMinGPPerc = 1
                        BEGIN
                            IF @MinGPPerc > 0
                                BEGIN
                                    SET @UnitPrice = ROUND((@CostPrice / (1 - (@MinGPPerc / 100))) * 1, 2)
                                END
                        END
                END
        END
    --------------------------------------------------------------------



RETURN @UnitPrice












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description	:sp_AF_Get_Waybill_GRV_ID
--Purpose       :Gets the FIRST GRV number of a Waybill
--Date			:2011/04/26
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Get_Waybill_GRV_ID
	(
        @WaybillID int,
        @GRVID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @GRVID = 0

	SELECT TOP 1 @GRVID = ISNULL(AO_GRV_ID, 0)
	FROM AF_Job_Tickets
	WHERE AF_Waybills_ID = @WaybillID


RETURN @GRVID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AF_Insert_GRN_Refund_Detail
--Purpose       :Inserts GRN Factory Refund Details
--              :Lifted from sp_AO_Insert_GRV_Return
--Date          :2011/06/28
--Authors       :TB
--MODS          :
--V6.2	RL		:2016-06-22	:Product Bin qty changes
--V6.2	RL		:2016-06-22	:Added cost adjustment to AP_Inventory_Adjustments
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Insert_GRN_Refund_Detail]
    (		
    	@GRVID int,
    	@ProductID int,
    	@Qty decimal(9,3),
    	@FactoryCredit money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@UserID int,
    	@CompanyID int
    )

AS
	
	DECLARE @Prev_On_Hand Decimal(9,3),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
            @Prev_LastCostTotal money,
            @Prev_AvgCostTotal money,
            @New_LastCostTotal money,
            @New_AvgCostTotal money,
            @New_On_Hand Decimal(9,3),
            @COS_Adjust money,
            @Prev_Average_On_Hand_Value money,
            @New_Last_Cost money,
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @GRNValue money,
            @User_Name varchar(40),
            @ProductRef varchar(30),
            @ProdCode varchar(20),
            @AdjustmentType int,
            @Note varchar(70)

    BEGIN
        ---------------------------------------------------------------------------
        --> Get the CLAIM Product stuff
        ---------------------------------------------------------------------------
    	SELECT @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
               @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
    		   @ProdCode = ISNULL(Product_Code, '')
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID

        ---------------------------------------------------------------------------
        --> Calculate AVERAGE COST (lifted from Stock Returns)
        ---------------------------------------------------------------------------
        SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
        SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

        SET @New_LastCostTotal = @Prev_LastCostTotal - @FactoryCredit
        SET @New_AvgCostTotal = @Prev_AvgCostTotal - @FactoryCredit

        SET @New_On_Hand = @Prev_On_Hand - @Qty
        SET @New_Last_Cost = @FactoryCredit

        IF @New_On_Hand <> 0
            BEGIN
                -- Calculate NEW Average_Cost
                SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
            END
        ELSE
            BEGIN
                -- Retain OLD Average_Cost
                SET @New_Average_Cost = @Prev_Average_Cost
            END


    	SET @Qty = (ISNULL(@Qty, 0) * -1)
    	SET @TradeDisc = (ISNULL(@TradeDisc, 0) * - 1)
    	SET @RebateDisc = (ISNULL(@RebateDisc, 0) * -1)
    	SET @OtherDisc = (ISNULL(@OtherDisc, 0) * -1)
    	SET @NetAmount = (ISNULL(@NetAmount, 0) * -1)
    	SET @TaxAmount = (ISNULL(@TaxAmount, 0) * -1)
    	SET @TotalCost = (ISNULL(@TotalCost, 0) * -1)


		INSERT INTO AO_GRV_Details
            (
                AO_GRV_ID,
                AP_Products_ID,
                Qty,
                Unit_Price,
                Trade_Discount_Amount,	
                Rebate_Discount_Amount,
                Other_Discount_Amount,
                Net_Amount,
                Sys_AW_Tax_Codes_ID,
                Tax_Amount,
                Total_Cost,
                [User_ID],
                AW_User_Companies_ID
            )

		VALUES
            (
                @GRVID,
                @ProductID,
                @Qty,
                @FactoryCredit,
                @TradeDisc,
                @RebateDisc,
                @OtherDisc,
                @NetAmount,
                @Tax_Code_ID,
                @TaxAmount,
                @TotalCost,
                @UserID,
                @CompanyID
            )


    	UPDATE AP_Products 
    	SET Last_Cost = ABS(@New_Last_Cost),
            Average_Cost = ABS(@New_Average_Cost),
            On_Hand = @New_On_Hand,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID
   
		EXEC sp_AP_Products_Bins_Update_Insert
 				@ProductID,		--@ProductID int,
				1,	--@ProductBinID int,
				@Qty,			--@Qty decimal(9,3)
				'FAC GRN',	--@Source varchar(10),
				0,				--@Batch_No
				@UserID,		--@UserID int,
				@CompanyID		--@CompanyID int  
								
    	--RL V6.2
        IF @Prev_Last_Cost <> @New_Last_Cost
		BEGIN

            --> Assign the Adjustment Type
            SET @AdjustmentType = 30    --Factory Returned

			SELECT @User_Name = ISNULL(FirstName, '')
			FROM AW_Users
			WHERE AW_Users_ID = @UserID

            SET @Note = 'Factory Claim by '

			SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'
			SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 

            --> Stock Reval/Deval Adjustment for Last_Cost changes
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        		    0,
        			0,
        		    0,
        			@New_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			0 ,
        			0,
        			0,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID
                )

        END
    	
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--------------------------------------------------------------------------------
--Description   :sp_AF_Insert_GRV
--Purpose       :Inserts Factory Goods Received and Goods Returned Voucher
--Date          :2011/05/04
--Authors       :TB
--MODS          :
--2004.5.3      :25/08/11 - Removed setting all amount parameters to negative if
--              :           Factory Returned Voucher (@AW_Transaction_Type = 30)
--------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Insert_GRV
    (
    	@Suppliers_ID int,
    	@AW_Transaction_Type int,
    	@Order_ID int = 0,
    	@DateReceived DateTime ,
    	@InvoiceNo varchar(20),
    	@SupplierRef varchar(20),
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@TaxTotal Money = 0,
    	@TotalAmount Money = 0,
    	@User_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @GRV_ID int,
    	    @Date datetime

    BEGIN
    	
--     	IF @AW_Transaction_Type = 30    --Factory Returned - PJFRT - Done in UI
--     		BEGIN
--     			SET @TradeDisc = (isnull(@TradeDisc, 0) * -1)
--     			SET @RebateDisc = (isnull(@RebateDisc, 0) * -1)
--     			SET @OtherDisc = (isnull(@OtherDisc, 0) * -1)
--     			SET @NetAmount = (isnull(@NetAmount, 0) * -1)
--     			SET @TaxTotal = (isnull(@TaxTotal, 0) * - 1)
--     			SET @TotalAmount = (isnull(@TotalAmount, 0) * -1)
--     		END
    									
    	SET @Date = CONVERT(datetime, @DateReceived)
    				
    	INSERT INTO AO_GRV
            (
                AO_Suppliers_ID,
        		Sys_AW_Transaction_Types_ID,
        		AO_Orders_ID,
        		Date_Received,
        		Delivery_Note_Number,
        		Supplier_Reference,
        		Trade_Discount_Total,
        		Rebate_Discount_Total,
        		Other_Discount_Total,
        		Net_Amount,
        		Total_Tax_Amount,
        		Total_Amount,
        		[User_ID],
        		AW_User_Companies_ID
            )
    	VALUES
            (
                @Suppliers_ID,
    			@AW_Transaction_Type,
    			@Order_ID,
    			@Date,
    			@InvoiceNo,
    			@SupplierRef,
    			@TradeDisc,
    			@RebateDisc,
    			@OtherDisc,
    			@NetAmount,
    			@TaxTotal,
    			@TotalAmount,
    			@User_ID,
    			@Company_ID
            )
    	
    	SELECT @GRV_ID = SCOPE_IDENTITY() 
    
    	RETURN @GRV_ID
    
    END

SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






















-------------------------------------------------------------------------------
--Description   :sp_AF_Insert_Job_Tickets
--Purpose       :Inserts new Job Tickets and UPDATE Product Stock On Hand
--Date          :2011/04/25
--Authors       :TB
--MODS          :
--2004.5.5      :06/10/11 - Added Comment field !! - TW 
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AF_Insert_Job_Tickets
    (
        @JobNo int,
        @JobDate datetime,
        @CustomerID int,
        @OrderNo varchar(20),
        @ProductID int,
        @MakeID int,
        @SerialNo varchar(20),
        @InstructionID smallint,
        @Comment varchar(20),
        @DatePosted datetime,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @JobID int,
            @Prev_On_Hand Decimal(9,3),
            @New_On_Hand Decimal(9,3)


	INSERT INTO AF_Job_Tickets
        (
            Post,
            Job_No,
            Job_Date,
            AC_Customers_ID,
            Order_No,
            AP_Products_ID,
            Lup_AP_Product_Manufacturers_ID,
            Serial_No,
            Lup_AF_Instructions_ID,
            Comment,
            Job_User_ID,
            Date_Captured,
            AW_User_Companies_ID
        )
	VALUES 
        (
            0,
            @JobNo,
            @JobDate,
            @CustomerID,
            @OrderNo,
            @ProductID,
            @MakeID,
            @SerialNo,
            @InstructionID,
            @Comment,
            @UserID,
            @DatePosted,
            @CompanyID
        )

	SELECT @JobID = Scope_Identity() 


    ------------------------------------------------------------------------
    --> DO NOT update Stock On Hand for Product
    ------------------------------------------------------------------------


RETURN @JobID





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















--------------------------------------------------------------------------------
--Description   :sp_AF_Insert_OR_Update_GRV_Detail
--Purpose       :Inserts GRV Detail and Updates Inventory Last_Cost, On_Hand
--              :and does REVAL/DEVAL Stock Adjustment in sp_AP_Update_Inventory_Details
--Functionality :Applies standard inventory controls and costings
--Source        :Lifted from sp_AO_Insert_OR_Update_GRV_Detail and removed superfluous
--Date          :2011/05/04
--Authors       :TB
--MODS          :
--2004.5.2      :28/06/11 - Removed superfluous AO_Suppliers_ID (first) input parameter
--2004.5.3      :13/09/11 - SET @New_Last_Cost = ABS(@New_Last_Cost) because Cost can NEVER be
--              :           NEGATIVE and this sp also used to [Return Job No] on Factory GRV History
--------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Insert_OR_Update_GRV_Detail
    (	
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(9,3),
    	@Unit_Last_Cost money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE @Prev_Last_Cost money,
            @Prev_On_Hand Decimal(9,3),
    		@Prev_Job_Reserved decimal(9,3),
    		@Prev_Sales_Order_Reserved decimal(9,3),
    		@Prev_Quote_Reserved decimal(9,3),
            @New_Last_Cost money,
            @New_On_Hand Decimal(9,3),
    		@Net_Purchase_Price money,
    		@Note varchar(70)


    SET @Prev_Job_Reserved = 0
    SET @Prev_Sales_Order_Reserved = 0
    SET @Prev_Quote_Reserved = 0


	INSERT INTO AO_GRV_Details
        (
            AO_GRV_ID,
			AP_Products_ID,
			Qty,
			Unit_Price,
			Trade_Discount_Amount,	
			Rebate_Discount_Amount,
			Other_Discount_Amount,
			Net_Amount,
			Sys_AW_Tax_Codes_ID,
			Tax_Amount,
			Total_Cost,
			[User_ID],
			AW_User_Companies_ID
        )
	VALUES
        (
            @AO_GRV_ID ,
			@AP_Products_ID ,
			@Qty ,
			@Unit_Last_Cost ,
			@TradeDisc ,
			@RebateDisc ,
			@OtherDisc ,
			@NetAmount ,
			@Tax_Code_ID ,
			@TaxAmount ,
			@TotalCost ,
			@UserID ,
			@CompanyID
        )


    SELECT @Prev_On_Hand = ISNULL(On_Hand, 0),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @AP_Products_ID


    --> SET NEW On Hand
	SET @New_On_Hand = @Prev_On_Hand + @Qty


    --> SET NEW Last Cost
    SET @Net_Purchase_Price = ISNULL(@Unit_Last_Cost, 0) * ISNULL(@Qty, 1)
    SET @New_Last_Cost = ROUND(@Net_Purchase_Price, 2)
    --> NEW 2004.5.3 - Cost can NEVER be NEGATIVE
    SET @New_Last_Cost = ABS(@New_Last_Cost)


    ------------------------------------------------------------------------
    --> Updates Last_Cost & Inventory Adjustment for Reval/Deval
    ------------------------------------------------------------------------
    SET @Note = 'Goods Received by '

	EXEC sp_AP_Update_Inventory_Details
            @AO_GRV_ID,
            @AP_Products_ID,
			@New_Last_Cost,
			@New_On_Hand,
			@Prev_Job_Reserved,
			@Prev_Sales_Order_Reserved,
			@Prev_Quote_Reserved,
			@Note,
			@UserID ,
			@CompanyID
    ------------------------------------------------------------------------



SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AF_Insert_Waybills
--Purpose       :Inserts new Waybill
--Date          :2011/04/26
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Insert_Waybills
    (
        @FactoryID int,
        @WaybillDate datetime,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @WaybillID int


	INSERT INTO AF_Waybills
        (
            AO_Suppliers_ID,
            Waybill_Date,
            User_ID,
            AW_User_Companies_ID
        )
	VALUES 
        (
            @FactoryID,
            @WaybillDate,
            @UserID,
            @CompanyID
        )

	SELECT @WaybillID = Scope_Identity() 


RETURN @WaybillID
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AF_Modules_Select
--Purpose       :Build Modules for Reports Library
--Date          :2011/04/25
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Modules_Select

AS

SET NOCOUNT ON

    SELECT Sys_AF_Modules_ID AS [ID], 
          [Description] AS [Module]
    FROM Sys_AF_Modules
    WHERE Slu_AW_Active_ID = 1
    ORDER BY [ID]

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------------
--Description   :sp_AF_RPT_GRV_Print        from: sp_AO_Select_GRV_Report_Data
--Purpose       :Factory GRV Report print
--Date          :2011/05/02
--Authors       :TB
--Mods		    :
--RL	v6.2	2015-09-01	Took out space between AF_Waybills_ID And Job_No for TP. Details don't fit on report
----------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_RPT_GRV_Print]
    (
    	@GRV_ID int
    )
AS

SET NOCOUNT ON

	
	SELECT  h.AO_Suppliers_ID AS [SupplierID],
            s.Supplier_Name AS [Supp Name],	
            s.Post_Box AS [Supp PostBox],
            s.Post_Office AS [Supp PostOffice],
            s.Post_Code AS [Supp PostCode],
            s.Supplier_Telephone AS [Supp TelNo],
            s.Supplier_Fax AS [Supp FaxNo],
            s.Tax_Number AS [Supp TaxNo],
            c.Company_Trading_Name AS [Co Name],
            ISNULL(c.Company_Name, '') + ISNULL(', ' + c.Company_Trading_Name, '') AS [Co Name],
            c.Company_Registration_Number AS [Co RegNo],
            c.Company_Addr1 AS [Co Address1],
            c.Company_Addr2 AS [Co Address2],
            c.Company_Post_Code	AS [Co PostCode],
            c.Tel_No AS [Co TelNo],
            c.Fax_No AS [Co FaxNo],
            c.TAX_Number AS [Co TaxNo],
            h.AO_GRV_ID AS [GRVID],
            h.Date_Received AS [Date Received],
            h.Sys_AW_Transaction_Types_ID AS [TranTypeID],
            h.Delivery_Note_Number AS [Del Note Number],
            h.Supplier_Reference AS [Supp Ref],
            p.Product_Code AS [Product Code],
            p.[Description] AS [Product Desc],
            1 AS [Qty],
            j.AO_Suppliers_ID AS [FactoryID],
            j.Invoice_No AS [InvoiceNo],
            CONVERT(CHAR(10), j.GRV_Date, 111) AS [InvoiceDate],
            ISNULL(j.Retread_Cost, 0) AS [Retread Cost],
            ISNULL(j.Repair_Cost, 0) AS [Repair Cost],
            ISNULL(j.Other_Cost, 0) AS [Other Cost],
            ISNULL(j.Retread_Cost, 0) + ISNULL(j.Repair_Cost, 0) + ISNULL(j.Other_Cost, 0) AS [TotalCost],
            j.Job_No AS [Job No],
            j.AF_Waybills_ID AS [Waybill No],
            CONVERT(varchar(10), j.AF_Waybills_ID) + '/' + CONVERT(varchar(10), j.Job_No) AS [JobWbill],
            h.Net_Amount AS [SubTotal],
            h.Total_Tax_Amount AS [Tax Amount],
            h.Total_Amount AS [Total Cost],
            ISNULL(u.Firstname, '' + ' ') + ISNULL(u.Surname, '') AS [Username]
	FROM AF_Job_Tickets j 
		LEFT JOIN AO_GRV h 
			ON j.AO_GRV_ID = h.AO_GRV_ID
        LEFT JOIN AO_Suppliers s
			ON h.AO_Suppliers_ID = s.AO_Suppliers_ID 
		LEFT JOIN AW_User_Companies c 
			ON h.AW_User_Companies_ID = c.AW_User_Companies_ID
		LEFT JOIN AW_Users u 
			ON j.GRV_User_ID = u.AW_Users_ID
		INNER JOIN AP_Products p 
			ON j.AP_Products_ID = p.AP_Products_ID
	WHERE h.AO_GRV_ID = @GRV_ID




SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AF_RPT_Waybill_Print
--Purpose       :Factory Waybill printing
--Date          :2011/04/27
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_RPT_Waybill_Print
    (
    	@WaybillID int
    )

AS

SET NOCOUNT ON

    DECLARE @DefaultMessage varchar(100),
            @PrintDefaultMessage varchar(10),
            @sql varchar(8000)


	SET @sql = ' SELECT '
    SET @sql = @sql + ' t.AF_Job_Tickets_ID AS [JobTicketID], '
	SET @sql = @sql + ' RTRIM(LTRIM(s.Supplier_Name)) AS [SupplierName], '
	SET @sql = @sql + ' ISNULL(s.Street_Address, '''') AS [StreetAddress], '
	SET @sql = @sql + ' ISNULL(s.Suburb, '''') AS [StreetSuburb], '
	SET @sql = @sql + ' ISNULL(s.City, '''') AS [StreetCity], '
	SET @sql = @sql + ' ISNULL(s.Street_Post_Code, '''') AS [StreetPostCode], '
	SET @sql = @sql + ' ISNULL(s.Supplier_Number, '''') + ''('' + CONVERT(VARCHAR(12), s.AO_Suppliers_ID) + '')'' AS [SupplierNo], '
    SET @sql = @sql + ' uc.Tax_Number AS [CompanyTaxNumber], '
    SET @sql = @sql + ' uc.E_Mail AS [CompanyEmail], '
    SET @sql = @sql + ' uc.Company_Name AS [CompanyName], '
    SET @sql = @sql + ' uc.Company_Trading_Name AS [TradingName], '
    SET @sql = @sql + ' uc.Company_Addr1 AS [CompanyAddress1], '
    SET @sql = @sql + ' uc.Company_Addr2 AS [CompanyAddress2], '
    SET @sql = @sql + ' uc.Company_City AS [CompanyCity], '
    SET @sql = @sql + ' uc.Company_Post_Code AS [CompanyPostCode], '
    SET @sql = @sql + ' uc.Company_Registration_Number AS [CompanyRegNo], '
    SET @sql = @sql + ' uc.Tel_No AS [CompanyTelNo], '
    SET @sql = @sql + ' uc.Fax_No AS [CompanyFaxNo], '
    SET @sql = @sql + ' CONVERT(varchar(12), t.Waybill_Date, 103) AS [WaybillDate], '
    SET @sql = @sql + ' t.AF_Waybills_ID AS [WaybillNo], '
    SET @sql = @sql + ' 0 AS [TransactionAmount], '
    SET @sql = @sql + ' 0 AS [TransactionTotalAmount], '
    SET @sql = @sql + ' 0 AS [TransactionTotalDiscount], '
    SET @sql = @sql + ' 0 AS [TransactionTotalTax], '
    SET @sql = @sql + ' p.Product_Code AS [ProductCode], '
    SET @sql = @sql + ' p.Description AS [ProductDescription], '
    SET @sql = @sql + ' ISNULL(p.Pack_Mass, 0) AS [PackMass], '
    SET @sql = @sql + ' ISNULL(p.Pack_Volume, 0) AS [PackVolume], '
    SET @sql = @sql + ' 1 AS [DetailQty], '
    SET @sql = @sql + ' 0 AS [DetailUnitPrice], '
    SET @sql = @sql + ' 0 AS [DetailAmount], '
    SET @sql = @sql + ' 0 AS [DetailTaxAmount], '
    SET @sql = @sql + ' 0 AS [DetailExtendedAmount], '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(hour, t.Waybill_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(minute, t.Waybill_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(second, t.Waybill_Date)) AS [WaybillTime], '
    SET @sql = @sql + ' u.UserName AS [UserName], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(s.Supplier_Telephone)), '''') + '
    SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(s.Contact_Cellphone)), '''') + '
    SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(s.Supplier_Fax)), '''') AS [TelNos], '
    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.Job_No AS [JobNo], '
    SET @sql = @sql + ' t.Serial_No AS [SerialNo], '
    SET @sql = @sql + ' m.Old_Code AS [Make], '
    SET @sql = @sql + ' i.Description AS [Instruction], '
    SET @sql = @sql + ' c.Surname AS [Customer], '
    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(s.Email_Address)), '''') AS [Emails] '

    SET @sql = @sql + ' FROM AF_Job_Tickets t '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_User_Companies uc '
    SET @sql = @sql + '         ON t.AW_User_Companies_ID = uc.AW_User_Companies_ID '
    SET @sql = @sql + '     LEFT JOIN AP_Products p '
    SET @sql = @sql + '         ON t.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON t.Waybill_User_ID = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON t.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AF_Instructions i '
    SET @sql = @sql + '         ON t.Lup_AF_Instructions_ID = i.Lup_AF_Instructions_ID '

    SET @sql = @sql + ' WHERE t.AF_Waybills_ID = ' + CONVERT(varchar(20), @WaybillID)

    SET @sql = @sql + ' ORDER BY AF_Job_Tickets_ID '



EXEC (@sql)


SET NOCOUNT OFF

































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AF_Refund_Job_No_Detail_Insert
--Purpose       :INSERTS CUSTOMER Refund Job No DETAILS (from Invoice Details)
--              :    also UPDATES AP_Products: On_Hand as OUTGOING STOCK 
--              :         UPDATES AS_Transactions: Total_Cost with FACTORY CREDIT
--Functionality :AS_Transactions types with Detail only: 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/08/28
--Authors       :TB
--MODS          :
--V6.2 RL	2016-06-26	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Refund_Job_No_Detail_Insert]
    (
		@DocumentID int,
		@ProductID int,
		@Qty decimal(9,3),
		@UnitCost money,
		@UnitPrice money,
		@OrigPrice money,
		@OrigDisc money,
		@Discount money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobRefID int,
        @Make varchar(6),
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
        	@OppositeQty decimal(9,3)


    SET @DocumentDetailsID = 0


    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI (Set as NEGATIVE)
    ---------------------------------------------------------------------------
    UPDATE AP_Products
    SET On_Hand = On_Hand + -@Qty
    WHERE AP_Products_ID = @ProductID
    ---------------------------------------------------------------------------

	--Update Bin Qty
	IF @Qty <> 0
	BEGIN
		SET @OppositeQty = @Qty * -1
		EXEC sp_AP_Products_Bins_Update_Insert 
			@ProductID,	--@ProductID int,
			1,					--@ProductBinID int,
			@OppositeQty,		--@Qty decimal(9,3)
			'GRN',				--@Source varchar(10),
			0,					--@Batch_No
			@UserID,			--@UserID int,
			@CompanyID			--@CompanyID int
	END	
    
	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
            Original_Discount,
            Discount_Amount,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@UnitCost,
			@UnitPrice,
			@OrigPrice,
            @OrigDisc,
            @Discount,
			@Tax,
			@Total,
            @JobRefID,
            @Make,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()



RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AF_Refund_Job_No_Header_Insert
--Purpose       :INSERTS CUSTOMER Refund Job No TRANSACTION (Factory Customer Billing)
--Functionality :Financial AS_Transactions types only: 4
--              :NB NB - SIGN REVERSAL DONE IN UI
--Date          :2011/08/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Refund_Job_No_Header_Insert
    (
        @TranDate datetime,
    	@CustomerID int,
    	@TranTypeID tinyint,
        @RefNo varchar(19),
        @TotalCost money,
        @Amount money,
        @Tax money,
        @Total money,
    	@GLAccountID int,
    	@Comment varchar(20),
        @DatePosted datetime,
    	@UserID int,
    	@CompanyID int
    )

AS

	DECLARE @DocumentID int


	IF NOT @TranTypeID = 5
        BEGIN
            SET @GLAccountID = NULL
        END


	INSERT AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Total_Cost,
            Amount,
            Total_Tax_Amount,
            Total_Amount,
            Transaction_Date,
            Customer_Reference,
            Comment,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
		)
	VALUES
		(
            @CustomerID,
            @GLAccountID,
            @RefNo,
            @TotalCost,
            @Amount,
            @Tax,
            @Total,
            @TranDate,
            '',
            @Comment,
            @UserID,
            @TranTypeID,
            @DatePosted,
            @UserID,
            @CompanyID
		)

    SELECT @DocumentID = Scope_Identity()


    --> Update the Customer Account Balance
	UPDATE AC_Customers
    SET Account_Balance = Account_Balance + @Total
    WHERE AC_Customers_ID = @CustomerID



RETURN @DocumentID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Billing_History_Detail
--Purpose       :Selects Billing History Detail
--Date          :2011/05/09
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Select_Billing_History_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT d.AS_Transaction_Details_ID AS [ID],
           j.Job_No AS [Job No],
           j.Job_Date AS [Job Date],
           d.AP_Products_ID AS [Product],
           d.Make AS [Make],
           d.Serial_No AS [Serial No],
           d.Unit_Cost AS [Unit Cost],
           d.Unit_Price AS [Unit Price],
           d.Original_Price AS [Orig Price],
           d.Extended_Amount - d.Tax_Amount AS [Amount],
           d.Tax_Amount AS [Tax Amount],
           d.Extended_Amount AS [Total]
    FROM AS_Transaction_Details d
        INNER JOIN AF_Job_Tickets j
            ON d.AS_Job_References_ID = j.Job_No
    WHERE d.AS_Transactions_ID = @HeaderID AND
          d.AW_User_Companies_ID = @CompanyID
    ORDER BY [ID]












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Billing_History_Header
--Purpose       :Selects Billing History Header
--Date          :2011/05/09
--Authors       :TB
--MODS          :
--2004.5.3      :24/08/11 - Added Customer Search criteria
--              :28/08/11 - Modified to SELECT FROM AS_Transactions with a GROUP BY and
--              :           INNER JOIN of AS_Transaction_Details and AF_Job_Tickets on AS_Job_References_ID
--              :           This allows displaying [Refund Job No] Tax Credit Notes that was
--              :           not possible with previous WHERE j.AS_Transactions_ID IS NOT NULL
--2004.5.5      :06/10/11 - Replaced [Customer] with [Job Customer]
--              :           to SEPARATE the Customer ACTIVE and DISABLED lists
-------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_AF_Select_Billing_History_Header
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-------------------------------------------------------------------------------
-- ORIGINAL CODE (FROM = AF_Job_Tickets) - This CANNOT fetch Tax Credit Notes
--                                         Does NOT use GROUP BY
-------------------------------------------------------------------------------
--     SET @sql = ' SELECT DISTINCT '
--     SET @sql = @sql + ' j.AS_Transactions_ID AS [ID], '
--     SET @sql = @sql + ' j.AC_Customers_ID AS [CustomerID], '
--     SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
--     SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
--     SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
--     SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
--     SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
--     SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Job Customer], '
--     SET @sql = @sql + ' j.Billing_No AS [Doc No], '
--     SET @sql = @sql + ' j.Billing_Date AS [Doc Date], '
--     SET @sql = @sql + ' j.Amount AS [Amount], '
--     SET @sql = @sql + ' j.Tax AS [Tax], '
--     SET @sql = @sql + ' j.Total AS [Total], '
--     SET @sql = @sql + ' t.Comment AS [Comment], '
--     SET @sql = @sql + ' ISNULL(u.FirstName + '' '', '''') + ISNULL(u.Surname, '''') AS [User] '
-- 
--     SET @sql = @sql + ' FROM AF_Job_Tickets j '
--     SET @sql = @sql + '     LEFT JOIN AC_Customers c '
--     SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
--     SET @sql = @sql + '     LEFT JOIN AS_Transactions t '
--     SET @sql = @sql + '         ON j.AS_Transactions_ID = t.AS_Transactions_ID '
--     SET @sql = @sql + '     LEFT JOIN AW_Users u '
--     SET @sql = @sql + '         ON j.Billing_User_ID = u.AW_Users_ID '
--     SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
--     SET @sql = @sql + '   AND j.AS_Transactions_ID IS NOT NULL '
--     SET @sql = @sql + '   AND j.AP_Inventory_Adjustments_ID IS NULL '


-------------------------------------------------------------------------------
-- 2004.5.3 NEW CODE (FROM = AS_Transactions) - This CAN fetch Tax Credit Notes
--                                              Uses GROUP BY
-------------------------------------------------------------------------------
    SET @sql = ' SELECT '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [ID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' ISNULL(MAX(c.Surname), '''') + '
    SET @sql = @sql + ' ISNULL('', '' + MAX(c.Firstnames), '''') + '
    SET @sql = @sql + ' ISNULL('', '' + MAX(c.Street_Address), '''') + '
    SET @sql = @sql + ' ISNULL('', '' + MAX(c.Suburb), '''') + '
    SET @sql = @sql + ' ISNULL('', '' + MAX(c.City), '''') AS [Job Customer], '
    SET @sql = @sql + ' MAX(tt.Description) AS [Transaction Type], '
    SET @sql = @sql + ' MAX(t.Transaction_Number) AS [Doc No], '
    SET @sql = @sql + ' MAX(t.Transaction_Date) AS [Doc Date], '
    SET @sql = @sql + ' MAX(t.Amount) AS [Amount], '
    SET @sql = @sql + ' MAX(t.Total_Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' MAX(t.Total_Amount) AS [Total], '
    SET @sql = @sql + ' MAX(t.Comment) AS [Comment], '
    SET @sql = @sql + ' ISNULL(MAX(u.FirstName) + '' '', '''') + ISNULL(MAX(u.Surname), '''') AS [User] '

    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + '         ON t.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AF_Job_Tickets j '
    SET @sql = @sql + '         ON d.AS_Job_References_ID = j.Job_No '
    SET @sql = @sql + '     INNER 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 AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Billing_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (t.Transaction_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END


    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND t.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END

    SET @sql = @sql + ' GROUP BY t.AS_Transactions_ID, t.AC_Customers_ID, t.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + ' ORDER BY [Doc No] DESC '


--PRINT @sql

    EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Billing_Job_Tickets
--Purpose       :Fetch Job Ticket to ALTER  a Stock Receipt GRV
--Functionality :uses BETWEEN
--Date          :2011/05/05
--Authors       :TB
--MODS          :
--2004.5.4      :13/09/11 - Added 'OR g.Sys_AW_Transaction_Types_ID = 30' in WHERE clause
--              :           to include Factory Claim Refund credits
-------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_AF_Select_Billing_Job_Tickets
    (
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' h.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' h.Post AS [Post], '
    SET @sql = @sql + ' h.Job_No AS [Job No], '
    SET @sql = @sql + ' h.Job_Date AS [Date], '
    SET @sql = @sql + ' h.Order_No AS [Order No], '
    SET @sql = @sql + ' h.Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' h.Serial_No AS [Serial No], '
    SET @sql = @sql + ' h.AP_Products_ID AS [Retread Product], '
    SET @sql = @sql + ' h.Retread_Cost AS [Retread Cost], '
    SET @sql = @sql + ' h.Retread_Price AS [Retread Price], '
    SET @sql = @sql + ' h.AP_Repair_Products_ID AS [Repair Product], '
    SET @sql = @sql + ' h.Repair_Cost AS [Repair Cost], '
    SET @sql = @sql + ' h.Repair_Price AS [Repair Price], '
    SET @sql = @sql + ' h.AP_Other_Products_ID AS [Other Product], '
    SET @sql = @sql + ' h.Other_Cost AS [Other Cost], '
    SET @sql = @sql + ' h.Other_Price AS [Other Price] '

    SET @sql = @sql + ' FROM AF_Job_Tickets h '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON h.AO_GRV_ID = g.AO_GRV_ID '

    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    SET @sql = @sql + '   AND h.AO_GRV_ID IS NOT NULL '
    SET @sql = @sql + '   AND h.AS_Transactions_ID IS NULL '
    SET @sql = @sql + '   AND (g.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '    OR g.Sys_AW_Transaction_Types_ID = 30) '

    SET @sql = @sql + ' ORDER BY [Job No] '

--PRINT @sql

    EXEC (@sql)



































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Casing_Credit_History_Detail
--Purpose       :Selects Casing Credit History Detail
--Date          :2011/05/11
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Select_Casing_Credit_History_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT
           d.AS_Transaction_Details_ID AS [ID],
           j.Job_No AS [Job No],
           j.Job_Date AS [Job Date],
           d.AP_Products_ID AS [Casing Product],
           d.Make AS [Make],
           d.Serial_No AS [Serial No],
           j.Stock_Cost AS [Stock Cost],
           j.AP_Stock_Products_ID AS [Stock Product],
           d.Unit_Price AS [Casing Credit],
           d.Tax_Amount AS [Tax Amount],
           d.Extended_Amount AS [Total]
    FROM AS_Transaction_Details d
        INNER JOIN AF_Job_Tickets j
            ON d.AS_Job_References_ID = j.Job_No
    WHERE d.AS_Transactions_ID = @HeaderID AND
          d.AW_User_Companies_ID = @CompanyID
    ORDER BY [ID]












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Casing_Credit_History_Header
--Purpose       :Selects Casing Credit History Header
--Date          :2011/05/11
--Authors       :TB
--MODS          :
--2004.5.3      :24/08/11 - Added Customer Search criteria
--2004.5.5      :06/10/11 - Replaced [Customer] with [Job Customer]
--              :           to SEPARATE the Customer ACTIVE and DISABLED lists
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AF_Select_Casing_Credit_History_Header
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' j.AS_Transactions_ID AS [ID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Job Customer], '
    SET @sql = @sql + ' t.Transaction_Number AS [Doc No], '
    SET @sql = @sql + ' t.Transaction_Date AS [Doc Date], '
    SET @sql = @sql + ' t.Amount AS [Amount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    SET @sql = @sql + ' ISNULL(u.FirstName + '' '', '''') + ISNULL(u.Surname, '''') AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions t '
    SET @sql = @sql + '         ON j.AS_Transactions_ID = t.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Adjustment_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND j.AS_Transactions_ID IS NOT NULL '
    SET @sql = @sql + '   AND j.AP_Inventory_Adjustments_ID IS NOT NULL '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (j.Adjustment_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END


    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND j.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql + ' ORDER BY [Doc No] DESC '


--PRINT @sql

    EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


































-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Casing_Credit_Job_Tickets
--Purpose       :Fetch Job Tickets to CREDIT Customer for CASING
--              :and take the Retreaded/Repaired product into Stock
--Functionality :uses BETWEEN
--Date          :2011/05/10
--Authors       :TB
--MODS          :
--2004.5.4      :13/09/11 - Added 'OR g.Sys_AW_Transaction_Types_ID = 29' in WHERE clause
--              :           to ONLY include Factory GRV's and NOT Factory Claim Refund credits
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AF_Select_Casing_Credit_Job_Tickets
    (
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' h.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' h.Post AS [Post], '
    SET @sql = @sql + ' h.Job_No AS [Job No], '
    SET @sql = @sql + ' h.Job_Date AS [Date], '
    SET @sql = @sql + ' h.Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' h.Serial_No AS [Serial No], '
    SET @sql = @sql + ' h.AP_Products_ID AS [Casing Product], '
    SET @sql = @sql + ' h.Retread_Cost AS [Retread Cost], '
    SET @sql = @sql + ' h.Repair_Cost AS [Repair Cost], '
    SET @sql = @sql + ' h.Other_Cost AS [Other Cost], '
    SET @sql = @sql + ' h.Casing_Credit AS [Casing Credit], '
    SET @sql = @sql + ' h.AP_Stock_Products_ID AS [Stock Product], '
    SET @sql = @sql + ' h.AP_Repair_Products_ID AS [RepairProductID], '
    SET @sql = @sql + ' h.AP_Other_Products_ID AS [OtherProductID] '

    SET @sql = @sql + ' FROM AF_Job_Tickets h '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON h.AO_GRV_ID = g.AO_GRV_ID '

    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    SET @sql = @sql + '   AND h.AO_GRV_ID IS NOT NULL '
    SET @sql = @sql + '   AND h.AS_Transactions_ID IS NULL '
    SET @sql = @sql + '   AND h.AP_Inventory_Adjustments_ID IS NULL '
    SET @sql = @sql + '   AND g.Sys_AW_Transaction_Types_ID = 29 '

    SET @sql = @sql + ' ORDER BY [Job No] '

--PRINT @sql

    EXEC (@sql)

































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Claim_History_Detail
--Purpose       :Selects GRN Claim History Detail
--Date          :2011/06/28
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AF_Select_Claim_History_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT
        AF_Job_Tickets_ID AS [ID],
        AF_Waybills_ID AS [Waybill No],
        CONVERT(CHAR(10), Waybill_Date, 111) AS [Waybill Date],
        Job_No AS [Job No],
        CONVERT(CHAR(10), Job_Date, 111) AS [Job Date],
        AC_Customers_ID AS [Customer],
        Lup_AP_Product_Manufacturers_ID AS [Make],
        ISNULL(Serial_No, '') AS [Serial No],
        Lup_AP_Fail_Reasons_ID AS [Fail Reason],
        AP_Products_ID AS [Retread Product],
        ISNULL(Retread_Cost, 0) AS [Retread Credit],
        AP_Repair_Products_ID AS [Repair Product],
        ISNULL(Repair_Cost, 0) AS [Repair Credit],
        AP_Other_Products_ID AS [Other Product],
        ISNULL(Other_Cost, 0) AS [Other Credit]
    FROM AF_Job_Tickets
    WHERE AO_GRV_ID = @HeaderID AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY [ID]











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Claim_History_Header
--Purpose       :Selects GRN Claim History Header
--Date          :2011/04/27
--Authors       :TB
--MODS          :
--2004.5.3      :24/08/11 - Added Customer Search criteria
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AF_Select_Claim_History_Header
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' MAX(AF_Job_Tickets_ID) AS [ID], '
    SET @sql = @sql + ' h.AO_GRV_ID AS [GRN No], '
    SET @sql = @sql + ' MAX(s.Supplier_Name) AS [Factory], '
    SET @sql = @sql + ' MAX(h.GRV_Date) AS [GRN Date], '

    SET @sql = @sql + ' MAX(g.Delivery_Note_Number) AS [Refund No], '
    SET @sql = @sql + ' MAX(g.Net_Amount) AS [Amount], '
    SET @sql = @sql + ' MAX(g.Total_Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' MAX(g.Total_Amount) AS [Total], '

    SET @sql = @sql + ' MAX(g.Date_Captured) AS [Captured], '
    SET @sql = @sql + ' ISNULL(MAX(u.FirstName) + '' '', '''') + ISNULL(MAX(u.Surname), '''') AS [User], '
    SET @sql = @sql + ' MAX(a.[Description]) AS [Active], '
    SET @sql = @sql + ' MAX(h.Slu_AW_Active_ID) AS [ActiveID] '
    SET @sql = @sql + ' FROM AF_Job_Tickets h '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON h.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON h.AO_GRV_ID = g.AO_GRV_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON h.GRV_User_ID = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a '
    SET @sql = @sql + '         ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.AO_Grv_ID IS NOT NULL '
    SET @sql = @sql + '   AND g.Sys_AW_Transaction_Types_ID = 30 '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (h.GRV_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END


    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql + ' GROUP BY h.AO_GRV_ID '

    SET @sql = @sql + ' ORDER BY [GRN No] DESC '


--PRINT @sql

    EXEC (@sql)














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Claim_Refund_Job_Tickets
--Purpose       :Fetch Job Ticket to refund claim to Customer
--Functionality :uses BETWEEN
--Date          :2011/06/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AF_Select_Claim_Refund_Job_Tickets
    (
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000)

    SET @sql = ' SELECT '
    SET @sql = @sql + ' h.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' h.Post AS [Post], '
    SET @sql = @sql + ' h.Job_No AS [Job No], '
    SET @sql = @sql + ' h.Job_Date AS [Date], '
    SET @sql = @sql + ' h.Order_No AS [Order No], '
    SET @sql = @sql + ' h.Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' h.Serial_No AS [Serial No], '
    SET @sql = @sql + ' h.Lup_AP_Fail_Reasons_ID AS [Fail Reason], '
    SET @sql = @sql + ' h.AP_Products_ID AS [Retread Product], '
    SET @sql = @sql + ' h.Retread_Cost AS [Retread Credit], '
    SET @sql = @sql + ' h.Retread_Price AS [Retread Refund], '
    SET @sql = @sql + ' h.AP_Repair_Products_ID AS [Repair Product], '
    SET @sql = @sql + ' h.Repair_Cost AS [Repair Credit], '
    SET @sql = @sql + ' h.Repair_Price AS [Repair Refund], '
    SET @sql = @sql + ' h.AP_Other_Products_ID AS [Other Product], '
    SET @sql = @sql + ' h.Other_Cost AS [Other Credit], '
    SET @sql = @sql + ' h.Other_Price AS [Other Refund] '

    SET @sql = @sql + ' FROM AF_Job_Tickets h '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON h.AO_GRV_ID = g.AO_GRV_ID '

    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    SET @sql = @sql + '   AND h.AO_GRV_ID IS NOT NULL '
    SET @sql = @sql + '   AND h.AS_Transactions_ID IS NULL '
    SET @sql = @sql + '   AND g.Sys_AW_Transaction_Types_ID = 30 '

    SET @sql = @sql + ' ORDER BY [Job No] '

--PRINT @sql

    EXEC (@sql)


































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-----------------------------------------------------------------------------
--Description   :sp_AF_Select_Factory_Lups
--Purpose       :Factory Lookups
--Date          :2011/04/24
--Authors       :TB
--MODS          :
--2004.5.2      :28/06/11 - Added Option 24 from Lup_AP_Fail_Reasons as [Reason]
--              :28/06/11 - Modified Option 18 DISTINCT Customers with OPEN GRVs
--              :           (for Customer Billing) to select ONLY GRV Type 29
--              :28/06/11 - Added Option 25 DISTINCT Customers with OPEN GRNs
--              :           (for Claim Refunds) to select ONLY GRV Type 30
--2004.5.3      :23/08/11 - Added Option 26 ALL Customers (including de-activated)
--              :           for Factory Receipts instead of using Option 2
--2004.5.3      :28/08/11 - Added Option 27 Transaction Types
--              :19/09/11 - Added Option 28 for ALL Users not only ACTIVE Users
--              :           that are not displayed in grids if they are NOT ACTIVE
--2004.5.5      :06/10/11 - Option 22 replaced [Customer] with [Job Customer]
--              :           to SEPARATE the Customer ACTIVE and DISABLED lists
-----------------------------------------------------------------------------

CREATE                                   PROCEDURE sp_AF_Select_Factory_Lups
    (
    	@Choice int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON


        --> Suppliers (Factories)
    	IF @Choice = 1
    		SELECT AO_Suppliers_ID AS [ID], 
    		       Supplier_Name AS [Factory] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Factory]

        --> Customers
        ELSE
    	IF @Choice = 2
            SELECT c.AC_Customers_ID AS [ID],
            	   ISNULL(c.Surname, '') +
                   ISNULL(', ' + c.Firstnames, '') +
                   ISNULL(', ' + c.Street_Address, '') +
                   ISNULL(', ' + c.Suburb, '') +
                   ISNULL(', ' + c.City, '') AS [Customer],
                   ISNULL(c.Orders_URL, '') AS [E-Mail],
                   c.Sys_AW_Tax_Codes_ID AS [CustTaxCode],
                   tc.Tax_Rate AS [CustTaxRate]
            FROM AC_Customers c
                LEFT JOIN Sys_AW_Tax_Codes tc
                    ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
            WHERE c.AW_User_Companies_ID = @CompanyID AND
                  c.Slu_AW_Active_ID = 1
            ORDER BY [Customer]

        --> Products
        ELSE
    	IF @Choice = 3
    		SELECT AP_Products_ID AS [ID], 
    		       ISNULL(Description, '') AS [Product] 
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Product]

        --> Status
        ELSE
    	IF @Choice = 5
    		SELECT Slu_AF_Job_Status_ID AS [ID], 
    		       ISNULL(Description, '') AS [Status] 
    		FROM Slu_AF_Job_Status
            WHERE  Slu_AW_Active_ID = 1
            ORDER BY [Status]

        --> Makes (Manufacturer long Description)
    	ELSE
    	IF @Choice = 6
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    		       ISNULL(Description, '') As [Make]
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Make]

        --> Instructions
    	ELSE
    	IF @Choice = 7
    		SELECT Lup_AF_Instructions_ID AS [ID],
    		       ISNULL(Description, '') As [Instruction] 
    		FROM Lup_AF_Instructions
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Instruction]

        --> Active
    	ELSE
    	IF @Choice = 8
    		SELECT Slu_AW_Active_ID AS [ID],
    		       ISNULL(Description, '') As [Active] 
    		FROM Slu_AW_Active
    
        --> AW YesNO
    	ELSE
    	IF @Choice = 9
    		SELECT Slu_AW_YesNo_ID AS [ID], 
    		       ISNULL(Description, '') AS [AW YesNo] 
    		FROM Slu_AW_YesNo
    
        --> Tax Codes
    	ELSE
    	IF @Choice = 10
    		SELECT Sys_AW_Tax_Codes_ID AS [ID],
    		       ISNULL(Description, '') As [Tax Code],
                   Tax_Rate AS [Tax] 
    		FROM sys_AW_Tax_Codes

        --> Sales Discount Groups
    	ELSE
    	IF @Choice = 11
    		SELECT Lup_AP_Discount_Groups_ID AS [ID],
    		       ISNULL(Description, '') As [DiscountGroup] 
    		FROM Lup_AP_Discount_Groups
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
        --> Cost+Plus Groups
    	ELSE
    	IF @Choice = 12
    		SELECT Lup_AP_Markup_Groups_ID AS [ID],
    		       ISNULL(Description, '') As [CostPlusGroup] 
    		FROM Lup_AP_Markup_Groups
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Description]

        --> Last Job No
    	ELSE
    	IF @Choice = 13
    		SELECT TOP 1 ISNULL(Job_No, 0) AS [LastJobNo]
    		FROM AF_Jobs
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Job_No DESC

    	--> ACTIVE Users
        ELSE
        IF @Choice = 14
          	SELECT AW_Users_ID as [ID],
                   Surname + ISNULL(', ' + FirstName, '') AS [User]
            FROM AW_Users
            WHERE Slu_AW_Active_ID = 1
            ORDER BY [User]

        --> DISTINCT Factories (Suppliers) with OPEN Waybills (for GRV's)
        ELSE
    	IF @Choice = 15
    		SELECT DISTINCT s.AO_Suppliers_ID AS [ID], 
    		                s.Supplier_Name AS [Factory] 
            FROM AF_Job_Tickets j
                INNER JOIN AO_Suppliers s
                    ON j.AO_Suppliers_ID = s.AO_Suppliers_ID
            WHERE j.AW_User_Companies_ID = @CompanyID
              AND j.AF_Waybills_ID IS NOT NULL
              AND j.AO_GRV_ID IS NULL
            ORDER BY [Factory]

        --> Months
        ELSE
        IF @Choice = 16
        	SELECT Slu_AW_Months_ID AS [ID], 
                  [Description] AS [Month] 
        	FROM Slu_AW_Months
        
        --> Years
        ELSE
        IF @Choice = 17
        	SELECT Slu_AW_Years_ID AS [ID], 
                  [Description] AS [Year] 
        	FROM Slu_AW_Years

        --> DISTINCT Customers with OPEN GRVs (for Billing)
        ELSE
    	IF @Choice = 18
    		SELECT DISTINCT c.AC_Customers_ID AS [ID], 
                    	    ISNULL(c.Surname, '') +
                            ISNULL(', ' + c.Firstnames, '') +
                            ISNULL(', ' + c.Street_Address, '') +
                            ISNULL(', ' + c.Suburb, '') +
                            ISNULL(', ' + c.City, '') AS [Customer],
                            ISNULL(c.Orders_URL, '') AS [E-Mail],
                            c.Sys_AW_Tax_Codes_ID AS [CustTaxCode],
                            tc.Tax_Rate AS [CustTaxRate]
            FROM AF_Job_Tickets j
                LEFT JOIN AC_Customers c
                    ON j.AC_Customers_ID = c.AC_Customers_ID
                LEFT JOIN Sys_AW_Tax_Codes tc
                    ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT JOIN AO_GRV g
                    ON j.AO_GRV_ID = g.AO_GRV_ID
            WHERE j.AW_User_Companies_ID = @CompanyID
              AND j.AO_GRV_ID IS NOT NULL
              AND j.AS_Transactions_ID IS NULL
              AND g.Sys_AW_Transaction_Types_ID = 29
            ORDER BY [Customer]

        --> Makes (Manufacturer short Description)
    	ELSE
    	IF @Choice = 19
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    		       ISNULL(Old_Code, '') As [Make]
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Make]

        --> Most POPULAR Factories used (in PREVIOUS Waybills) and ORDER BY COUNT of Job Tickets
        ELSE
    	IF @Choice = 20
    		SELECT j.AO_Suppliers_ID AS [ID], 
	               MAX(s.Supplier_Name) AS [FactoriesUsed],
                   COUNT(*) AS [JobCNT]
            FROM AF_Job_Tickets j
                LEFT JOIN AO_Suppliers s
                    ON j.AO_Suppliers_ID = s.AO_Suppliers_ID
            WHERE j.AW_User_Companies_ID = @CompanyID
              AND s.Slu_AW_Active_ID = 1
              AND AF_Waybills_ID IS NOT NULL
            GROUP BY j.AO_Suppliers_ID
            ORDER BY [JobCNT] DESC

        --> DISTINCT Customers with OPEN JOBs (for Waybills)
        ELSE
    	IF @Choice = 21
    		SELECT DISTINCT c.AC_Customers_ID AS [ID], 
                    	    ISNULL(c.Surname, '') +
                            ISNULL(', ' + c.Firstnames, '') +
                            ISNULL(', ' + c.Street_Address, '') +
                            ISNULL(', ' + c.Suburb, '') +
                            ISNULL(', ' + c.City, '') AS [Customer],
                            ISNULL(c.Orders_URL, '') AS [E-Mail],
                            c.Sys_AW_Tax_Codes_ID AS [CustTaxCode],
                            tc.Tax_Rate AS [CustTaxRate]
            FROM AF_Job_Tickets j
                LEFT JOIN AC_Customers c
                    ON j.AC_Customers_ID = c.AC_Customers_ID
                LEFT JOIN Sys_AW_Tax_Codes tc
                    ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
            WHERE j.AW_User_Companies_ID = @CompanyID
              AND j.AF_Waybills_ID IS NULL
            ORDER BY [Customer]

        --> DISTINCT Customers with JOBs (for Job Master Control)
        ELSE
    	IF @Choice = 22
    		SELECT DISTINCT c.AC_Customers_ID AS [ID], 
                    	    ISNULL(c.Surname, '') +
                            ISNULL(', ' + c.Firstnames, '') +
                            ISNULL(', ' + c.Street_Address, '') +
                            ISNULL(', ' + c.Suburb, '') +
                            ISNULL(', ' + c.City, '') AS [Job Customer],
                            ISNULL(c.Orders_URL, '') AS [E-Mail],
                            c.Sys_AW_Tax_Codes_ID AS [CustTaxCode],
                            tc.Tax_Rate AS [CustTaxRate]
            FROM AF_Job_Tickets j
                LEFT JOIN AC_Customers c
                    ON j.AC_Customers_ID = c.AC_Customers_ID
                LEFT JOIN Sys_AW_Tax_Codes tc
                    ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
            WHERE j.AW_User_Companies_ID = @CompanyID
              AND j.Job_No IS NOT NULL
            ORDER BY [Job Customer]

        --> Customer E-Mail addresses
        ELSE
        IF @Choice = 23
            BEGIN
                SELECT Orders_URL as [E-Mail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CompanyID

                UNION

                SELECT Home_Email as [E-Mail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CompanyID

                UNION

                SELECT Work_Email as [E-Mail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CompanyID
            END

        --> Fail Reasons
    	ELSE
    	IF @Choice = 24
    		SELECT Lup_AP_Fail_Reasons_ID AS [ID],
    		       ISNULL(Description, '') As [Fail Reason] 
    		FROM Lup_AP_Fail_Reasons
    		WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Fail Reason]

        --> DISTINCT Customers with OPEN GRNs (for Claim Refunfs)
        ELSE
    	IF @Choice = 25
    		SELECT DISTINCT c.AC_Customers_ID AS [ID], 
                    	    ISNULL(c.Surname, '') +
                            ISNULL(', ' + c.Firstnames, '') +
                            ISNULL(', ' + c.Street_Address, '') +
                            ISNULL(', ' + c.Suburb, '') +
                            ISNULL(', ' + c.City, '') AS [Customer],
                            ISNULL(c.Orders_URL, '') AS [E-Mail],
                            c.Sys_AW_Tax_Codes_ID AS [CustTaxCode],
                            tc.Tax_Rate AS [CustTaxRate]
            FROM AF_Job_Tickets j
                LEFT JOIN AC_Customers c
                    ON j.AC_Customers_ID = c.AC_Customers_ID
                LEFT JOIN Sys_AW_Tax_Codes tc
                    ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT JOIN AO_GRV g
                    ON j.AO_GRV_ID = g.AO_GRV_ID
            WHERE j.AW_User_Companies_ID = @CompanyID
              AND j.AO_GRV_ID IS NOT NULL
              AND j.AS_Transactions_ID IS NULL
              AND g.Sys_AW_Transaction_Types_ID = 30
            ORDER BY [Customer]


        --> ALL Customers (including de-activated) (for Factory Receipts)
        --  In the event a customer was DE-ACTIVATED before Factory Receipts !!!!
        --  Copied from @Choice = 2
        ELSE
    	IF @Choice = 26
            SELECT c.AC_Customers_ID AS [ID],
            	   ISNULL(c.Surname, '') +
                   ISNULL(', ' + c.Firstnames, '') +
                   ISNULL(', ' + c.Street_Address, '') +
                   ISNULL(', ' + c.Suburb, '') +
                   ISNULL(', ' + c.City, '') AS [Customer],
                   ISNULL(c.Orders_URL, '') AS [E-Mail],
                   c.Sys_AW_Tax_Codes_ID AS [CustTaxCode],
                   tc.Tax_Rate AS [CustTaxRate]
            FROM AC_Customers c
                LEFT JOIN Sys_AW_Tax_Codes tc
                    ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
            WHERE c.AW_User_Companies_ID = @CompanyID
--              AND c.Slu_AW_Active_ID = 1
            ORDER BY [Customer]


        --> Customer Billing Transaction Types
        ELSE
        IF @Choice = 27
            SELECT Sys_AW_Transaction_Types_ID as [ID],
                  [Description] AS [Transaction Type]
            FROM Sys_AW_Transaction_Types
            WHERE Sys_AW_Transaction_Types_ID = 3 or
                  Sys_AW_Transaction_Types_ID = 4


    	--> ALL Users
        ELSE
        IF @Choice = 28
          	SELECT AW_Users_ID as [ID],
                   Surname + ISNULL(', ' + FirstName, '') AS [User]
            FROM AW_Users
            --WHERE Slu_AW_Active_ID = 1
            ORDER BY [User]


SET NOCOUNT OFF








































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Factory_Refund_Job_Tickets
--Purpose       :Fetch Job Tickets for Factory Refunds GRN
--Functionality :uses BETWEEN
--Date          :2011/06/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Select_Factory_Refund_Job_Tickets
    (
        @FactoryID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' Post AS [Post], '
    SET @sql = @sql + ' AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' Job_No AS [Job No], '
    SET @sql = @sql + ' AC_Customers_ID AS [Customer], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' Serial_No AS [Serial No], '
    SET @sql = @sql + ' Lup_AP_Fail_Reasons_ID AS [Fail Reason], '
    SET @sql = @sql + ' AP_Products_ID AS [Retread Product], '
    SET @sql = @sql + ' Retread_Cost AS [Retread Credit], '
    SET @sql = @sql + ' AP_Repair_Products_ID AS [Repair Product], '
    SET @sql = @sql + ' Repair_Cost AS [Repair Credit], '
    SET @sql = @sql + ' AP_Other_Products_ID AS [Other Product], '
    SET @sql = @sql + ' Other_Cost AS [Other Credit] '

    SET @sql = @sql + ' FROM AF_Job_Tickets '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND AO_Suppliers_ID = ' + CONVERT(varchar(10), @FactoryID) + ' '
    SET @sql = @sql + ' AND AF_Waybills_ID IS NOT NULL '
    SET @sql = @sql + ' AND AO_GRV_ID IS NULL '

    SET @sql = @sql + ' ORDER BY [Waybill No], [Job No] '

--PRINT @sql

    EXEC (@sql)



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_GRN_History_Header   -   *** NOT USED ***
--Purpose       :Selects GRN (Refund) History Header
--Date          :2011/06/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Select_GRN_History_Header
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' MAX(AF_Job_Tickets_ID) AS [ID], '
    SET @sql = @sql + ' h.AO_GRV_ID AS [GRN No], '
    SET @sql = @sql + ' MAX(s.Supplier_Name) AS [Factory], '
    SET @sql = @sql + ' MAX(h.GRV_Date) AS [GRN Date], '

    SET @sql = @sql + ' MAX(g.Delivery_Note_Number) AS [Refund No], '
    SET @sql = @sql + ' MAX(g.Net_Amount) AS [Amount], '
    SET @sql = @sql + ' MAX(g.Total_Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' MAX(g.Total_Amount) AS [Total], '

    SET @sql = @sql + ' MAX(g.Date_Captured) AS [Captured], '
    SET @sql = @sql + ' ISNULL(MAX(u.FirstName) + '' '', '''') + ISNULL(MAX(u.Surname), '''') AS [User], '
    SET @sql = @sql + ' MAX(a.[Description]) AS [Active], '
    SET @sql = @sql + ' MAX(h.Slu_AW_Active_ID) AS [ActiveID] '
    SET @sql = @sql + ' FROM AF_Job_Tickets h '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON h.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON h.AO_GRV_ID = g.AO_GRV_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON h.GRV_User_ID = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a '
    SET @sql = @sql + '         ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.AO_Grv_ID IS NOT NULL '
    SET @sql = @sql + '   AND h.Sys_AW_Transaction_Types_ID = 30 '

--     IF @ChkDate = 1
--         BEGIN
--             SET @sql = @sql + ' AND (h.GRV_Date BETWEEN ' +
--                                      '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
--             SET @sql = @sql + ' AND ' +
--                                      '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '
--         END

    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (h.GRV_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END

    SET @sql = @sql + ' GROUP BY h.AO_GRV_ID '

    SET @sql = @sql + ' ORDER BY [GRV No] DESC '


--PRINT @sql

    EXEC (@sql)














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------
--Description   :sp_AF_Select_GRV_Detail
--Functionality :Fetch GRV details for one GRV 
--Date          :2011/08/27
--Authors       :TB
--MODS			:
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Select_GRV_Detail
    (
    	@GRVID int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        a.AO_GRV_Details_ID AS [ID],
        a.AO_GRV_ID AS [FK ID],
        a.AP_Products_ID AS [ProductsID],
        p.[Description] AS [Product],
        p.Product_Code AS [Code],
        a.Qty AS [Qty],
        a.Unit_Price AS [Unit Price],
        a.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        tc.[Description] AS [Tax Code],
        a.Net_Amount AS [Amount],
        a.Tax_Amount AS [Tax],
        a.Total_Cost AS [Total]
    FROM AO_GRV_Details a
        LEFT JOIN AP_Products p
            ON a.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
    WHERE a.AO_GRV_ID = @GRVID AND
          a.AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AF_Select_GRV_Header
--Functionality :Factory GRV/GRN Header
--Date          :2011/08/27
--Authors       :TB
--MODS			:
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Select_GRV_Header
    (
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkIncludeAll tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AO_GRV_ID AS [ID], '
    SET @sql = @sql + ' h.AO_Suppliers_ID AS [FactoryID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Factory], '
    SET @sql = @sql + ' tt.Description AS [GRV Type], '
    SET @sql = @sql + ' h.AO_GRV_ID AS [GRV No], '
    SET @sql = @sql + ' h.Date_Received AS [GRV Date], '
    SET @sql = @sql + ' t.Slu_AW_Months_ID AS [Month], '
    SET @sql = @sql + ' t.Slu_AW_Years_ID AS [Year], '
    SET @sql = @sql + ' h.Delivery_Note_Number AS [Ref No], '
    SET @sql = @sql + ' h.Net_Amount AS [Amount], '
    SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' h.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    SET @sql = @sql + ' h.Date_Captured AS [Captured], '
    SET @sql = @sql + ' ISNULL(u.FirstName + '' '', '''') + ISNULL(u.Surname, '''') AS [User] '
    SET @sql = @sql + ' FROM AO_GRV h '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON h.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Transactions t '
    SET @sql = @sql + '         ON h.AO_GRV_ID = t.AO_GRV_ID '

    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '         ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkIncludeAll = 0
        BEGIN
            SET @sql = @sql + '   AND h.Sys_AW_Transaction_Types_ID = 30 '
        END


    IF @ChkIncludeAll = 1
        BEGIN
            SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 29 '
            SET @sql = @sql + '    OR  h.Sys_AW_Transaction_Types_ID = 30) '
        END


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (h.Date_Received BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END


    SET @sql = @sql + ' ORDER BY [GRV No] DESC '


--PRINT @sql

    EXEC (@sql)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AF_Select_GRV_History_Detail
--Purpose       :Selects GRV History Detail
--Date          :2011/05/03
--Authors       :TB
--Mods          :
--2004.5.3      :24/08/11 - Converted to DYNAMIC SQL to add Customer Search criteria
--2004.5.5      :06/10/11 - Replaced [Customer] with [Job Customer]
--              :           to SEPARATE the Customer ACTIVE and DISABLED lists
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AF_Select_GRV_History_Detail
    (
        @HeaderID int,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' CONVERT(CHAR(10), Waybill_Date, 111) AS [Waybill Date], '
    SET @sql = @sql + ' Job_No AS [Job No], '
    SET @sql = @sql + ' CONVERT(CHAR(10), Job_Date, 111) AS [Job Date], '
    SET @sql = @sql + ' AC_Customers_ID AS [Job Customer], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' ISNULL(Serial_No, '''') AS [Serial No], '
    SET @sql = @sql + ' AP_Products_ID AS [Retread Product], '
    SET @sql = @sql + ' ISNULL(Retread_Cost, 0) AS [Retread Cost], '
    SET @sql = @sql + ' AP_Repair_Products_ID AS [Repair Product], '
    SET @sql = @sql + ' ISNULL(Repair_Cost, 0) AS [Repair Cost], '
    SET @sql = @sql + ' AP_Other_Products_ID AS [Other Product], '
    SET @sql = @sql + ' ISNULL(Other_Cost, 0) AS [Other Cost] '
    SET @sql = @sql + ' FROM AF_Job_Tickets '
    SET @sql = @sql + ' WHERE AO_GRV_ID = ' + CONVERT(varchar(10), @HeaderID) + ' '
    SET @sql = @sql + '   AND AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql + ' ORDER BY [ID] '


--PRINT @sql

    EXEC (@sql)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_GRV_History_Header
--Purpose       :Selects GRV History Header
--Date          :2011/04/27
--Authors       :TB
--MODS          :
--2004.5.3      :24/08/11 - Added Customer Search criteria
--              :25/08/11 - Added filter Sys_AW_Transaction_Types_ID = 30
--              :25/08/11 - Added [Month] and [Year] with new AO_Transactions JOIN
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AF_Select_GRV_History_Header
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' MAX(AF_Job_Tickets_ID) AS [ID], '
    SET @sql = @sql + ' MAX(s.Supplier_Name) AS [Factory], '
    SET @sql = @sql + ' h.AO_GRV_ID AS [GRV No], '
    SET @sql = @sql + ' MAX(h.GRV_Date) AS [GRV Date], '
    SET @sql = @sql + ' MAX(t.Slu_AW_Months_ID) AS [Month], '
    SET @sql = @sql + ' MAX(t.Slu_AW_Years_ID) AS [Year], '
    SET @sql = @sql + ' MAX(g.Delivery_Note_Number) AS [Invoice No], '
    SET @sql = @sql + ' MAX(g.Net_Amount) AS [Amount], '
    SET @sql = @sql + ' MAX(g.Total_Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' MAX(g.Total_Amount) AS [Total], '
    SET @sql = @sql + ' MAX(g.Date_Captured) AS [Captured], '
    SET @sql = @sql + ' ISNULL(MAX(u.FirstName) + '' '', '''') + ISNULL(MAX(u.Surname), '''') AS [User], '
    SET @sql = @sql + ' MAX(a.[Description]) AS [Active], '
    SET @sql = @sql + ' MAX(h.Slu_AW_Active_ID) AS [ActiveID] '
    SET @sql = @sql + ' FROM AF_Job_Tickets h '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON h.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON h.AO_GRV_ID = g.AO_GRV_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Transactions t '
    SET @sql = @sql + '         ON h.AO_GRV_ID = t.AO_GRV_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON h.GRV_User_ID = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a '
    SET @sql = @sql + '         ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.AO_Grv_ID IS NOT NULL '
    SET @sql = @sql + '   AND (g.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '    OR  g.Sys_AW_Transaction_Types_ID = 30) '   --Job Ticket JOIN makes this IMPOSSIBLE


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (h.GRV_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END


    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql + ' GROUP BY h.AO_GRV_ID '

    SET @sql = @sql + ' ORDER BY [GRV No] DESC '


--PRINT @sql

    EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AF_Select_GRV_Item_Detail
--Purpose       :Select GRV Item Detail (a Job No record) of ONE HeaderID
--Date          :2011/08/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AF_Select_GRV_Item_Detail
    (
        @JobTicketID int
    )

AS

SET NOCOUNT ON


    SELECT Job_No AS [JobNo],
           AO_Suppliers_ID AS [FactoryID],
           AO_GRV_ID AS [GRVNo],
           GRV_Date AS [GRVDate],
           Invoice_No AS [InvoiceNo],
           ISNULL(AP_Products_ID, 0) AS [RetreadProductID],
           ISNULL(AP_Repair_Products_ID, 0) AS [RepairProductID],
           ISNULL(AP_Other_Products_ID, 0) AS [OtherProductID],
           ISNULL(Retread_Cost, 0) AS [RetreadCost],
           ISNULL(Repair_Cost, 0) AS [RepairCost],
           ISNULL(Other_Cost, 0) AS [OtherCost]
    FROM AF_Job_Tickets
    WHERE AF_Job_Tickets_ID = @JobTicketID




SET NOCOUNT OFF


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_GRV_Job_Tickets
--Purpose       :Fetch Job Ticket to ALTER  a Stock Receipt GRV
--Functionality :uses BETWEEN
--Date          :2011/04/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AF_Select_GRV_Job_Tickets
    (
        @FactoryID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' Post AS [Post], '
    SET @sql = @sql + ' AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' Job_No AS [Job No], '
    SET @sql = @sql + ' AC_Customers_ID AS [Customer], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' Serial_No AS [Serial No], '
    SET @sql = @sql + ' AP_Products_ID AS [Retread Product], '
    SET @sql = @sql + ' Retread_Cost AS [Retread Cost], '
    SET @sql = @sql + ' AP_Repair_Products_ID AS [Repair Product], '
    SET @sql = @sql + ' Repair_Cost AS [Repair Cost], '
    SET @sql = @sql + ' AP_Other_Products_ID AS [Other Product], '
    SET @sql = @sql + ' Other_Cost AS [Other Cost] '

    SET @sql = @sql + ' FROM AF_Job_Tickets '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND AO_Suppliers_ID = ' + CONVERT(varchar(10), @FactoryID) + ' '
    SET @sql = @sql + ' AND AF_Waybills_ID IS NOT NULL '
    SET @sql = @sql + ' AND AO_GRV_ID IS NULL '

    SET @sql = @sql + ' ORDER BY [Waybill No], [Job No] '

--PRINT @sql

    EXEC (@sql)

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Invoice_Item_Detail
--Purpose       :Select ALL Invoice Detail records of ONE HeaderID
--Date          :2011/08/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Select_Invoice_Item_Detail
    (
        @ASTranID int,
        @JobNo int
    )

AS

SET NOCOUNT ON


    SELECT AS_Transaction_Details_ID AS [DetailID],
           AP_Products_ID AS [ProductID],
           Quantity AS [Qty],
           Unit_Cost AS [UnitCost],
           Unit_Price AS [UnitPrice],
           Original_Price AS [OrigPrice],
           Original_Discount AS [OrigDisc],
           Discount_Amount AS [Discount],
           Tax_Amount AS [Tax],
           Extended_Amount AS [Total],
           AS_Job_References_ID AS [JobRefID],
           Serial_No AS [SerialNo],
           Make AS [Make],
           Customer AS [Customer],
           Date_Captured AS [Captured]
    FROM AS_Transaction_Details
    WHERE AS_Transactions_ID = @ASTranID
      AND AS_Job_References_ID = @JobNo









SET NOCOUNT OFF




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Job_Ticket_History
--Purpose       :Fetch Job Ticket History
--Functionality :uses BETWEEN
--Date          :2011/04/25
--Authors       :TB
--MODS          :
--2004.5.2      :28/06/11 - Added Lup_AP_Fail_Reasons_ID AS [Fail Reason]
-------------------------------------------------------------------------------

CREATE                       PROCEDURE sp_AF_Select_Job_Ticket_History
    (
        @ChkFactory tinyint,
        @FactoryID int,
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
        @chkSearch tinyint,
        @Search varchar(50),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    IF @chkSearch = 1
        BEGIN
        	SET @Filter = '%' + RTRIM(LTRIM(@Search)) + '%'
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' Job_No AS [Job No], '
    SET @sql = @sql + ' Job_Date AS [Date], '
    SET @sql = @sql + ' AC_Customers_ID AS [Job Customer], '
    SET @sql = @sql + ' Order_No AS [Order No], '
    SET @sql = @sql + ' AP_Products_ID AS [Product], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' Serial_No AS [Serial No], '
    SET @sql = @sql + ' Lup_AF_Instructions_ID AS [Instruction], '
    SET @sql = @sql + ' Job_User_ID AS [Job User], '
    SET @sql = @sql + ' AO_Suppliers_ID AS [Factory], '
    SET @sql = @sql + ' Waybill_Date AS [Waybill Date], '
    SET @sql = @sql + ' AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' Waybill_User_ID AS [Waybill User], '

    SET @sql = @sql + ' GRV_Date AS [GRV Date], '
    SET @sql = @sql + ' AO_GRV_ID AS [GRV No], '
    SET @sql = @sql + ' Invoice_No AS [Invoice No], '
    SET @sql = @sql + ' Retread_Cost AS [Retread Cost], '
    SET @sql = @sql + ' Repair_Cost AS [Repair Cost], '
    SET @sql = @sql + ' Other_Cost AS [Other Cost], '
    SET @sql = @sql + ' AP_Repair_Products_ID AS [Repair Product], '
    SET @sql = @sql + ' AP_Other_Products_ID AS [Other Product], '
    SET @sql = @sql + ' Lup_AP_Fail_Reasons_ID AS [Fail Reason], '
    SET @sql = @sql + ' GRV_User_ID AS [GRV User], '

    SET @sql = @sql + ' Billing_Date AS [Billing Date], '
    SET @sql = @sql + ' Billing_No AS [Doc No], '
    SET @sql = @sql + ' Retread_Price AS [Retread Price], '
    SET @sql = @sql + ' Repair_Price AS [Repair Price], '
    SET @sql = @sql + ' Other_Price AS [Other Price], '
    SET @sql = @sql + ' Amount AS [Amount], '
    SET @sql = @sql + ' Tax AS [Tax], '
    SET @sql = @sql + ' Total AS [Total], '
    SET @sql = @sql + ' Comment AS [Comment], '
    SET @sql = @sql + ' Billing_User_ID AS [Billing User], '

    SET @sql = @sql + ' Adjustment_Date AS [Adjustment Date], '
    SET @sql = @sql + ' AP_Inventory_Adjustments_ID AS [ADJ No], '
    SET @sql = @sql + ' AP_Stock_Products_ID AS [Stock Product], '
    SET @sql = @sql + ' Casing_Credit AS [Casing Credit], '
    SET @sql = @sql + ' Stock_Cost AS [Stock Cost], '
    SET @sql = @sql + ' Adjustment_User_ID AS [ADJ User], '
    SET @sql = @sql + ' Date_Captured AS [Captured] '

    SET @sql = @sql + ' FROM AF_Job_Tickets '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkFactory = 1
        BEGIN
            SET @sql = @sql + ' AND AO_Suppliers_ID = ' + CONVERT(varchar(10), @FactoryID) + ' ' 
        END

    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (Job_Date BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '

            SET @sql = @sql + ' OR (Waybill_Date BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '

            SET @sql = @sql + ' OR (GRV_Date BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '

            SET @sql = @sql + ' OR (Billing_Date BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '

            SET @sql = @sql + ' OR (Adjustment_Date BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '

            SET @sql = @sql + ' OR (Date_Captured BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '
        END
    
    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END
    
    IF @chkSearch = 1
        BEGIN
            SET @sql = @sql + ' AND (CONVERT(varchar(10), Job_No) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  Order_No LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  Serial_No LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(10), AF_Waybills_ID) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(10), AO_GRV_ID) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  Invoice_No LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  Billing_No LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  CONVERT(varchar(10), AP_Inventory_Adjustments_ID) LIKE ' + '''' + @Filter+ ''''  + ' '
            SET @sql = @sql + '  OR  Comment LIKE ' + '''' + @Filter+ ''''  + ') '
        END
    

    SET @sql = @sql + ' ORDER BY [Job No] '



--PRINT @sql

    EXEC (@sql)

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Product_Cardex - WIP
--Purpose       :Fetch Job Ticket Inventory physical movement
--Functionality :    uses UNION ALL
--Date          :2011/05/13
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Select_Product_Cardex
    (
        @StartDate as datetime,
        @ProductID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-------------------------------------------------------------------------------
-- JOBS TICKETS
-------------------------------------------------------------------------------

    SET @sql = ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.Job_Date, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), j.Job_No) '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(c.Surname)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''JOB'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     0 AS [Unit Price], '
    SET @sql = @sql + '     0 AS [Total], '
    SET @sql = @sql + '     j.Job_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.Job_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '


    SET @sql = @sql + ' UNION ALL '


-------------------------------------------------------------------------------
-- WAYBILLS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.Waybill_Date, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), j.AF_Waybills_ID) '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''WBL'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     0 AS [Unit Price], '
    SET @sql = @sql + '     0 AS [Total], '
    SET @sql = @sql + '     j.Waybill_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.Waybill_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '


    SET @sql = @sql + ' UNION ALL '


-- -------------------------------------------------------------------------------
-- -- FACTORY GRV - ALL
-- -------------------------------------------------------------------------------
-- 
--     SET @sql = @sql + ' SELECT '
-- 
--     SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
--     SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
--     SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.GRV_Date, 121)) AS [Date], '
--     SET @sql = @sql + '     CONVERT(varchar(10), j.AO_GRV_ID) '
--     SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
--     SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
--     SET @sql = @sql + '     ''GRV'' AS [Type], '
--     SET @sql = @sql + '     1 AS [Qty], '
--     SET @sql = @sql + '     ISNULL(Retread_Cost, 0) + ISNULL(Repair_Cost, 0) + ISNULL(Other_Cost, 0) AS [Unit Price], '
--     SET @sql = @sql + '     ISNULL(Retread_Cost, 0) + ISNULL(Repair_Cost, 0) + ISNULL(Other_Cost, 0) AS [Total], '
--     SET @sql = @sql + '     j.GRV_Date AS [Date Captured], '
--     SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '
-- 
--     SET @sql = @sql + ' FROM AF_Job_Tickets j '
--     SET @sql = @sql + '     INNER JOIN AP_Products p '
--     SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
--     SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
--     SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
--     SET @sql = @sql + '     LEFT JOIN AW_Users u '
--     SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
--     SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
--     SET @sql = @sql + '   AND j.GRV_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
--     SET @sql = @sql + '   AND j.Retread_Cost IS NOT NULL '
--     SET @sql = @sql + '   AND j.Retread_Cost > 0 '
-- 
-- 
--     SET @sql = @sql + ' UNION ALL '


-------------------------------------------------------------------------------
-- FACTORY GRV - RETREAD
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.GRV_Date, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), j.AO_GRV_ID) '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''GRV RTD'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     ISNULL(Retread_Cost, 0) AS [Unit Price], '
    SET @sql = @sql + '     ISNULL(Retread_Cost, 0) AS [Total], '
    SET @sql = @sql + '     j.GRV_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE j.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.GRV_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND j.Retread_Cost IS NOT NULL '
    SET @sql = @sql + '   AND j.Retread_Cost > 0 '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- FACTORY GRV - REPAIR
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.GRV_Date, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), j.AO_GRV_ID) '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''GRV REP'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     ISNULL(Other_Cost, 0)AS [Unit Price], '
    SET @sql = @sql + '     ISNULL(Other_Cost, 0) AS [Total], '
    SET @sql = @sql + '     j.GRV_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Repair_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE j.AP_Repair_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.GRV_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND j.Other_Cost IS NOT NULL '
    SET @sql = @sql + '   AND j.Other_Cost > 0 '

    SET @sql = @sql + ' UNION ALL '


-------------------------------------------------------------------------------
-- FACTORY GRV - OTHER
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.GRV_Date, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), j.AO_GRV_ID) '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''GRV OTH'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     ISNULL(Repair_Cost, 0) AS [Unit Price], '
    SET @sql = @sql + '     ISNULL(Repair_Cost, 0) AS [Total], '
    SET @sql = @sql + '     j.GRV_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Other_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE j.AP_Other_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.GRV_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND j.Repair_Cost IS NOT NULL '
    SET @sql = @sql + '   AND j.Repair_Cost > 0 '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- SALES - MAY WANT TO SPLIT SALES LIKE GRV's
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.Billing_Date, 121)) AS [Date], '
    SET @sql = @sql + '     j.Billing_No '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(c.Surname)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''SALE'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     ISNULL(Retread_Price, 0) + ISNULL(Repair_Price, 0) + ISNULL(Other_Price, 0) AS [Unit Price], '
    SET @sql = @sql + '     ISNULL(Amount, 0) AS [Total], '
    SET @sql = @sql + '     j.Billing_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.Billing_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND j.AS_Transactions_ID IS NOT NULL '


    SET @sql = @sql + ' UNION ALL '


-------------------------------------------------------------------------------
-- ADJUSTMENTS - SOURCE MUST BE ADJUSTMENT to show ADJ on ALL 3 PRODUCTS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     j.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), j.Adjustment_Date, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), j.Refund_No) '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), j.Job_No) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(c.Surname)) AS [Supplier/Customer], '
    SET @sql = @sql + '     ''CCR'' AS [Type], '
    SET @sql = @sql + '     1 AS [Qty], '
    SET @sql = @sql + '     0 AS [Unit Price], '
    SET @sql = @sql + '     0 AS [Total], '
    SET @sql = @sql + '     j.Waybill_Date AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Stock_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Job_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND j.Adjustment_Date >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '


    SET @sql = @sql + ' ORDER BY [CompanyID], [Date Captured] '


--PRINT @sql

EXEC (@sql)






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------
--Description   :sp_AP_Select_Filtered_Products
--Functionality :Fetches latest product status for Stock Adjustments
--Date          :2011/05/10
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Select_Product_Status
    (
        @ProductID int,
        @OnHand decimal(9, 3) OUTPUT,
        @LastCost money OUTPUT,
        @AvgCost money OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @OnHand = ISNULL(On_Hand, 0),
           @LastCost =  ISNULL(Last_Cost, 0),
           @AvgCost = ISNULL(Average_Cost, 0)
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Refund_History_Detail
--Purpose       :Selects Customer Claim Refund History Detail
--Date          :2011/06/29
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Select_Refund_History_Detail
    (
        @HeaderID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT
           d.AS_Transaction_Details_ID AS [ID],
           j.Job_No AS [Job No],
           j.Job_Date AS [Job Date],
           d.AP_Products_ID AS [Product],
           d.Make AS [Make],
           d.Serial_No AS [Serial No],
           j.Lup_AP_Fail_Reasons_ID AS [Fail Reason],
           d.Unit_Cost AS [Unit Cost],
           d.Unit_Price AS [Unit Price],
           d.Original_Price AS [Orig Price],
           d.Unit_Price AS [Amount],
           d.Tax_Amount AS [Tax Amount],
           d.Extended_Amount AS [Total]
    FROM AS_Transaction_Details d
        INNER JOIN AF_Job_Tickets j
            ON d.AS_Job_References_ID = j.Job_No
    WHERE d.AS_Transactions_ID = @HeaderID AND
          d.AW_User_Companies_ID = @CompanyID
    ORDER BY [ID]












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Refund_History_Header
--Purpose       :Selects Customer Claim Refund History Header
--Date          :2011/06/29
--Authors       :TB
--MODS          :
--2004.5.3      :24/08/11 - Added Customer Search criteria
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Select_Refund_History_Header
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' j.AS_Transactions_ID AS [ID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Customer], '
    SET @sql = @sql + ' j.Billing_No AS [Doc No], '
    SET @sql = @sql + ' j.Billing_Date AS [Doc Date], '
    SET @sql = @sql + ' j.Amount AS [Amount], '
    SET @sql = @sql + ' j.Tax AS [Tax], '
    SET @sql = @sql + ' j.Total AS [Total], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    SET @sql = @sql + ' ISNULL(u.FirstName + '' '', '''') + ISNULL(u.Surname, '''') AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     LEFT JOIN AO_GRV g '
    SET @sql = @sql + '         ON j.AO_GRV_ID = g.AO_GRV_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions t '
    SET @sql = @sql + '         ON j.AS_Transactions_ID = t.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON j.Billing_User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND j.AS_Transactions_ID IS NOT NULL '
    SET @sql = @sql + '   AND j.AP_Inventory_Adjustments_ID IS NULL '
    SET @sql = @sql + '   AND g.Sys_AW_Transaction_Types_ID = 30 '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (j.Billing_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END


    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND j.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql + ' ORDER BY [Doc No] DESC '


--PRINT @sql

    EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Reports_Library
--Purpose       :Select Factory System Reports from the Reports Library
--Date          :2011/04/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Select_Reports_Library
    (
        @ReportModule varchar(50),
        @TypeID tinyint,
        @Option tinyint
    )

AS

SET NOCOUNT ON

    IF @Option = 0       -- Report Module Library
        BEGIN
            SELECT
                Sys_AF_Reports_ID AS [ID], 
                Sys_AF_Modules_ID AS [ModuleID], 
                Type_ID AS [TypeID],
                Location AS [Location], 
                Report_No AS [Report], 
                Report_Name AS [Report Name], 
                Description AS [User Description], 
                Object_DLL AS [ObjectDLL], 
                Class_Name AS [ClassName], 
                Method_Name AS [MethodName]
            FROM Sys_AF_Reports
            WHERE Location = @ReportModule AND
                  Type_ID = @TypeID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Report_No
        END

    ELSE
    IF @Option = 1        -- Full Reports Library
        BEGIN
            SELECT
                Sys_AF_Reports_ID AS [ID], 
                Sys_AF_Modules_ID AS [ModuleID], 
                Type_ID AS [TypeID],
                Location AS [Location], 
                Report_No AS [Report], 
                Report_Name AS [Report Name], 
                Description AS [User Description], 
                Object_DLL AS [ObjectDLL], 
                Class_Name AS [ClassName], 
                Method_Name AS [MethodName]
            FROM Sys_AF_Reports
            WHERE Type_ID = @TypeID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Report_No
        END
          


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Touched_Products
--Purpose       :Selects products for Factory Jobs
--Functionality :Uses TABLE datatype
--Date          :2011/05/12
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Select_Touched_Products
    (
        @CompanyID int,
        @StartDate datetime
    )
AS

SET NOCOUNT ON

---------------------------------------------
--> Using TABLE datatype
---------------------------------------------
    DECLARE @ActiveProducts table
                (
                    [AP_Products_ID] int
                )

    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AF_Job_Tickets
    WHERE AW_User_Companies_ID = @CompanyID AND
          AP_Products_ID IS NOT NULL AND
          Date_Captured >= @StartDate


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Repair_Products_ID AS [AP_Products_ID]
    FROM AF_Job_Tickets
    WHERE AW_User_Companies_ID = @CompanyID AND
          AP_Repair_Products_ID IS NOT NULL AND
          Date_Captured >= @StartDate


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Other_Products_ID AS [AP_Products_ID]
    FROM AF_Job_Tickets
    WHERE AW_User_Companies_ID = @CompanyID AND
          AP_Other_Products_ID IS NOT NULL AND
          Date_Captured >= @StartDate


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Stock_Products_ID AS [AP_Products_ID]
    FROM AF_Job_Tickets
    WHERE AW_User_Companies_ID = @CompanyID AND
          AP_Stock_Products_ID IS NOT NULL AND
          Date_Captured >= @StartDate


	SELECT DISTINCT a.AP_Products_ID AS [ID],
           ISNULL(p.Product_Code, '') AS [Code],
           ISNULL(p.[Description], '') AS [Product]
    FROM @ActiveProducts a
        INNER JOIN AP_Products p
            ON a.AP_Products_ID = p.AP_Products_ID
    ORDER BY [Product]



SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-----------------------------------------------------------------------------
--Description   :sp_AF_Select_User_Applications
--Purpose       :Build Modules and Applications per user for login
--Date          :2011/04/23
--Authors       :TB
--MODS          :
--2004.5.5      :05/10/11 - Added SET @StartupApp = 1 IF @StartupApp IS NULL [OR @StartupApp = 0]
-----------------------------------------------------------------------------

CREATE                PROCEDURE sp_AF_Select_User_Applications
	(
		@UserID int,
		@CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @StartupApp smallint

    SET @StartupApp = 1

    SELECT DISTINCT
            m.Sys_AF_Modules_ID AS [ModID], 
            m.[Description] AS [Module],
            a.Sys_AF_Applications_ID AS [AppID], 
            a.[Description] AS [Application],  
            a.Form_Name AS [FormName],
            '' as [LargeIcon],
            '' as [SmallIcon],
            m.Module_Seq,
            a.Application_Seq
    FROM Sys_AF_Applications a
        INNER JOIN Sys_AF_Modules m
            ON a.Sys_AF_Modules_ID = m.Sys_AF_Modules_ID
    WHERE a.Slu_AW_Active_ID = 1
    ORDER BY  m.Module_Seq, a.Application_Seq  


--> Return Value = Startup APP ID (glngUserStartupApp)
    SELECT TOP 1 @StartupApp = ISNULL(Sys_AF_Applications_ID, 1)
    FROM Sys_AF_App_Startup
    WHERE AW_Users_ID = @UserID


    -- NEW 2004.5.5 - [OR @StartupApp = 0]
    IF @StartupApp IS NULL OR @StartupApp = 0
        BEGIN
            SET @StartupApp = 1
        END


RETURN @StartupApp



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Waybill_Detail
--Purpose       :Select Waybill History Detail rows of a HeaderID
--Date          :2011/05/05
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Select_Waybill_Detail
    (
        @WaybillID int
    )

AS

SET NOCOUNT ON


    SELECT AF_Job_Tickets_ID AS [JobID],
           AF_Waybills_ID AS [WaybillID],
           AO_Suppliers_ID AS [FactoryID],
           AP_Products_ID AS [ProductID]
    FROM AF_Job_Tickets
    WHERE AF_Waybills_ID = @WaybillID




SET NOCOUNT OFF






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Waybill_History_Detail
--Purpose       :Selects Waybill History Detail
--Date          :2011/04/27
--Authors       :TB
--Mods          :
--2004.5.3      :24/08/11 - Converted to DYNAMIC SQL to add Customer Search criteria
--2004.5.5      :06/10/11 - Replaced [Customer] with [Job Customer]
--              :           to SEPARATE the Customer ACTIVE and DISABLED lists
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AF_Select_Waybill_History_Detail
    (
        @HeaderID int,
        @ChkCustomer tinyint,
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' Job_No AS [Job No], '
    SET @sql = @sql + ' Job_Date AS [Job Date], '
    SET @sql = @sql + ' AC_Customers_ID AS [Job Customer], '
    SET @sql = @sql + ' Order_No AS [Order No], '
    SET @sql = @sql + ' AP_Products_ID AS [Product], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' Serial_No AS [Serial No], '
    SET @sql = @sql + ' Lup_AF_Instructions_ID AS [Instruction], '
    SET @sql = @sql + ' Comment AS [Comment], '
    SET @sql = @sql + ' Date_Captured AS [Captured], '
    SET @sql = @sql + ' Job_User_ID AS [Job User] '
    SET @sql = @sql + ' FROM AF_Job_Tickets '
    SET @sql = @sql + ' WHERE AF_Waybills_ID = ' + CONVERT(varchar(10), @HeaderID) + ' '
    SET @sql = @sql + '   AND AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql + ' ORDER BY [ID] '


--PRINT @sql

    EXEC (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Waybill_History_Header
--Purpose       :Selects Waybill History Header
--Date          :2011/04/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Select_Waybill_History_Header]
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,       
        @CompanyID int        
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    SET @sql = ' SELECT Distinct '

    SET @sql = @sql + ' h.AF_Waybills_ID AS [ID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Factory], '
    SET @sql = @sql + ' h.AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' h.Waybill_Date AS [Waybill Date], '
    SET @sql = @sql + ' ISNULL(u.FirstName + '' '', '''') + ISNULL(u.Surname, '''') AS [User], '
    SET @sql = @sql + ' a.[Description] AS [Active], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [ActiveID] '
    SET @sql = @sql + ' FROM AF_Waybills h '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON h.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AF_Job_Tickets t '
    SET @sql = @sql + '         ON h.AF_Waybills_ID = t.AF_Waybills_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON h.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a '
    SET @sql = @sql + '         ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (h.Waybill_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END

    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND t.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END

    SET @sql = @sql + ' ORDER BY [Waybill Date] DESC '

--PRINT @sql

    EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Waybill_Job_Tickets
--Purpose       :Fetch Job Ticket to ALTER  a Waybill
--Functionality :uses BETWEEN
--Date          :2011/04/26
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AF_Select_Waybill_Job_Tickets
    (
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,
--         @chkSearch tinyint,
--         @Search varchar(50),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


--     IF @chkSearch = 1
--         BEGIN
--         	SET @Filter = '%' + RTRIM(LTRIM(@Search)) + '%'
--         END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' Post AS [Post], '
    SET @sql = @sql + ' Job_No AS [Job No], '
    SET @sql = @sql + ' Job_Date AS [Date], '
    SET @sql = @sql + ' AC_Customers_ID AS [Customer], '
    SET @sql = @sql + ' Order_No AS [Order No], '
    SET @sql = @sql + ' AP_Products_ID AS [Product], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Make], '
    SET @sql = @sql + ' Serial_No AS [Serial No], '
    SET @sql = @sql + ' Lup_AF_Instructions_ID AS [Instruction], '
    SET @sql = @sql + ' Comment AS [Comment], '
    SET @sql = @sql + ' Date_Captured AS [Captured], '
    SET @sql = @sql + ' Job_User_ID AS [Job User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND AF_Waybills_ID IS NULL '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (Job_Date BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '

            SET @sql = @sql + ' OR (Date_Captured BETWEEN ' +
                                     '''' + CONVERT(CHAR(10), @FromDate, 121) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(CHAR(10), @ToDate, 121) + '''' + ') '
        END
    
    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END
    
--     IF @chkSearch = 1
--         BEGIN
--             SET @sql = @sql + ' AND (CONVERT(varchar(10), Job_No) LIKE ' + '''' + @Filter+ ''''  + ' '
--             SET @sql = @sql + '  OR  Order_No LIKE ' + '''' + @Filter+ ''''  + ' '
--             SET @sql = @sql + '  OR  Serial_No LIKE ' + '''' + @Filter+ ''''  + ' '
--             SET @sql = @sql + '  OR  CONVERT(varchar(10), AF_Waybills_ID) LIKE ' + '''' + @Filter+ ''''  + ' '
--             SET @sql = @sql + '  OR  Invoice_No LIKE ' + '''' + @Filter+ ''''  + ' '
--             SET @sql = @sql + '  OR  Billing_No LIKE ' + '''' + @Filter+ ''''  + ' '
--             SET @sql = @sql + '  OR  Comment LIKE ' + '''' + @Filter+ ''''  + ') '
--         END
    

    SET @sql = @sql + ' ORDER BY [Job No] '



--PRINT @sql

    EXEC (@sql)























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















----------------------------------------------------------------------------
--Description   :sp_AF_Set_User_App
--Date          :2011/04/30
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Set_User_App
   (        
        @AppID smallint,
        @UserID int
    )

AS


SET NOCOUNT OFF

    IF NOT EXISTS
        (
            SELECT Sys_AF_App_Startup_ID
            FROM Sys_AF_App_Startup
            WHERE AW_Users_ID = @UserID
        )
        BEGIN
            INSERT Sys_AF_App_Startup
                (
                    Sys_AF_Applications_ID,
                    AW_Users_ID
                )
            VALUES
                (
                    @AppID,
                    @UserID
                )
        END
    ELSE
        BEGIN
            UPDATE Sys_AF_App_Startup
            SET Sys_AF_Applications_ID = @AppID
            WHERE AW_Users_ID = @UserID
        END





SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AF_Transaction_Detail_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (Factory Customer Billing)
--              :    also UPDATES AP_Products: On_Hand, Last_Sale_Date
--              :         UPDATES AS_Transactions: Total_Cost
--Functionality :AS_Transactions types with Detail only: 3, 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/05/08
--Authors       :TB
--MODS          :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Transaction_Detail_Insert]
    (
		@DocumentID int,
		@TranTypeID int,
		@ProductID int,
        @CostMethod tinyint,
		@Qty decimal(9,3),
		@UnitPrice money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobNo int,
        @Make int,
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
            @Cost money,
            @TotalCost money,
    		@OriginalPrice money,
            @SmallMake varchar(6),
            @Oppisite_Qty decimal(9,3)


    SET @DocumentDetailsID = 0


    ---------------------------------------------------------------------------
    --> Set Product Cost
    ---------------------------------------------------------------------------
    IF @CostMethod = 0        --Average
        BEGIN
            SELECT @Cost = Average_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 1        --Last
        BEGIN
            SELECT @Cost = Last_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 2        --Standard
        BEGIN
            SELECT @Cost = Standard_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END

    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
    SET @TotalCost = ROUND(@Qty * @Cost, 2)

    UPDATE AS_Transactions
    SET Total_Cost = ISNULL(Total_Cost, 0) + @TotalCost
    WHERE AS_Transactions_ID = @DocumentID

    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
	IF @TranTypeID = 3    --> Invoice
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate(),
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
            
            			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					1,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'Sale',			--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END				
		END

	ELSE
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
            
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					1,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'Sale',			--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END	            
		END
    ---------------------------------------------------------------------------

    SELECT @SmallMake = LEFT(ISNULL(Old_Code, ''), 6)
    FROM Lup_AP_Product_Manufacturers
    WHERE Lup_AP_Product_Manufacturers_ID = @Make


	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@Cost,
			@UnitPrice,
			@OriginalPrice,
			@Tax,
			@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()
	
	--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	--RL Check Rounding of Tax amount in code
	--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	Update AS_Transactions
	Set Total_Tax_Amount = (Select Sum(ISNULL(Tax_Amount,0)) From AS_Transaction_Details Where AS_Transactions_ID = @DocumentID),
		Total_Amount = (Select Sum(ISNULL(Extended_Amount,0)) From AS_Transaction_Details Where AS_Transactions_ID = @DocumentID) --Sum(ISNULL(Extended_Amount,0))
		--Date_Captured = '2016-01-01'
	Where AS_Transactions_ID = @DocumentID

RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AF_Transaction_Header_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTIONS (Factory Customer Billing)
--              :ALSO USED BY: Casing for Credit AND Customer Claim Refunds
--Functionality :Financial AS_Transactions types only: 3, 4
--              :NB NB - SIGN REVERSAL DONE IN UI
--Date          :2011/05/08
--Authors       :TB
--MODS          :
--2004.5.3      :23/08/11 - Increased @Notes from varchar(250) to varchar(500)
--2004.5.5      :25/10/11 - Added @TotalCost input variable. Costs are summed in UI
--              :           using system Valuation Method and sp_AF_Get_Product_Cost
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Transaction_Header_Insert
    (
        @TranDate datetime,
    	@CustomerID int,
    	@TranTypeID tinyint,
        @RefNo varchar(19),
        @TotalCost money,
        @Amount money,
        @Tax money,
        @Total money,
    	@GLAccountID int,
    	@Comment varchar(20),
    	@Notes varchar(500),
        @DatePosted datetime,
    	@UserID int,
    	@CompanyID int
    )

AS

	DECLARE @DocumentID int,
            @CommentID int


    IF @TranTypeID = 3 OR @TranTypeID = 4
        BEGIN
            IF RTRIM(LTRIM(@Notes)) <> ''
                BEGIN
                    EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Notes
                END
        END


	IF NOT @TranTypeID = 5
        BEGIN
            SET @GLAccountID = NULL
        END


	INSERT AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Total_Cost,
            Amount,
            Total_Tax_Amount,
            Total_Amount,
            Transaction_Date,
            Customer_Reference,
            Comment,
            AW_Comments_ID,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
		)
	VALUES
		(
            @CustomerID,
            @GLAccountID,
            @RefNo,
            @TotalCost,
            @Amount,
            @Tax,
            @Total,
            @TranDate,
            'See note below',
            @Comment,
            @CommentID,
            @UserID,
            @TranTypeID,
            @DatePosted,
            @UserID,
            @CompanyID
		)

    SELECT @DocumentID = Scope_Identity()


    --> Update the Customer Account Balance
	UPDATE AC_Customers
    SET Account_Balance = Account_Balance + @Total
    WHERE AC_Customers_ID = @CustomerID



RETURN @DocumentID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AF_Transaction_Refund_Detail_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (from a Factory Claim Refund)
--              :    also UPDATES AP_Products: On_Hand as OUTGOING STOCK 
--              :         UPDATES AS_Transactions: Total_Cost with FACTORY CREDIT
--Functionality :AS_Transactions types with Detail only: 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/06/29
--Authors       :TB
--MODS          :
--2004.5.5      :26/10/11 - Fixed UPDATE Header Tran Total_Cost section that set the Total_Cost =
--              :           ACTUAL FACTORY CREDITED COST. Must be current AVERAGE COST because
--              :           cost was AVERAGED when claim was RECEIVED from Factory
--V6.0	RL	2014-09-01	:Added Product audit trail info
--V6.2	RL	2015-12-01	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Transaction_Refund_Detail_Insert]
    (
		@DocumentID int,
		@TranTypeID int,
		@ProductID int,
        @CostMethod tinyint,
		@Qty decimal(9,3),
		@UnitCost money,
		@UnitPrice money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobNo int,
        @Make int,
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
            @Cost money,
            @TotalCost money,
    		@OriginalPrice money,
            @SmallMake varchar(6),
            @Oppisite_Qty decimal(9,3)


    SET @DocumentDetailsID = 0


--     ---------------------------------------------------------------------------
--     --> Set Product Cost (The same Factory Credit that went into Inventory)
--     ---------------------------------------------------------------------------
--     SET @Cost = ROUND(@UnitCost, 2)
--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
--    SET @OriginalPrice = @Cost


    ---------------------------------------------------------------------------
    --> Set Product Cost - NEW 2004.5.5 - Copied from sp_AF_Transaction_Detail_Insert
    -->                    Because cost was AVERAGED when claim was RECEIVED
    --                     Therfore cost MUST BE TAKEN OUT at AVERAGE
    ---------------------------------------------------------------------------
    IF @CostMethod = 0        --Average
        BEGIN
            SELECT @Cost = Average_Cost,
					--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 1        --Last
        BEGIN
            SELECT @Cost = Last_Cost,
					--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 2        --Standard
        BEGIN
            SELECT @Cost = Standard_Cost,
					--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END

    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
    SET @TotalCost = ROUND(@Qty * @Cost, 2)

    UPDATE AS_Transactions
    SET Total_Cost = ISNULL(Total_Cost, 0) + @TotalCost
    WHERE AS_Transactions_ID = @DocumentID


    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI (Set as NEGATIVE)
    ---------------------------------------------------------------------------
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + -@Qty,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
                        
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
			
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					1,	--@ProductBinID int,
					@Oppisite_Qty,			--@Qty decimal(9,3)
					'FAC CLREF',	--@Source varchar(10),
					0,				--@Batch_No
					@UserID,		--@UserID int,
					@CompanyID		--@CompanyID int
			END	    	
            
		END
    ---------------------------------------------------------------------------

    SELECT @SmallMake = LEFT(ISNULL(Old_Code, ''), 6)
    FROM Lup_AP_Product_Manufacturers
    WHERE Lup_AP_Product_Manufacturers_ID = @Make


	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			--RL 2016-05-30 Unit_Cost is always positive
			@Cost,				--Unit_Cost
			-@UnitPrice,		--Unit_Price
			@OriginalPrice,		--Original_Price
			@Tax,
			@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Deleted_Waybill_Job
--Purpose       :Update Jobs data with deleted Waybill data
--Date          :2011/05/05
--Authors       :TB
--MODS          :
--V6.0	RL	2014-09-01	:Added Product audit trail info
--V6.0	RL	2014-10-16	:Remove product quantity update.
--						 Only Waybills with no GRVs can be deleted, therefore stock has not been affected yet
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Update_Deleted_Waybill_Job]
    (
        @JobTicketID int,
        @ProductID int,
        @UserID		int
    )
AS

SET NOCOUNT ON

    DECLARE @RetCode int,
            @Prev_On_Hand Decimal(9,3),
            @New_On_Hand Decimal(9,3)


    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET AO_Suppliers_ID = Null,
                Waybill_Date = Null,
                AF_Waybills_ID = Null,
                Waybill_User_ID = Null
            WHERE AF_Job_Tickets_ID = @JobTicketID


--V6.0	RL	2014-10-16	:Remove product quantity update.
--						 Only Waybills with no GRVs can be deleted, therefore stock has not been affected yet
            ------------------------------------------------------------------------
            --> Updates Stock On Hand for Product
            ------------------------------------------------------------------------
         --   SELECT @Prev_On_Hand = ISNULL(On_Hand, 0)
        	--FROM AP_Products
        	--WHERE AP_Products_ID = @ProductID


         --   --> SET NEW On Hand
        	--SET @New_On_Hand = @Prev_On_Hand - 1


         --   UPDATE AP_Products
         --   SET On_Hand = @New_On_Hand,
         --   [User_ID] = @UserID
         --   WHERE AP_Products_ID = @ProductID
            ------------------------------------------------------------------------


            SET @RetCode = 1
        END

RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


























-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_Billing
--Purpose       :Update Jobs with new Billing data
--Date          :2011/05/08
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AF_Update_Job_Billing
    (
        @JobTicketID int,
        @OrderNo varchar(20),
        @InvoiceNo varchar(20),
        @InvoiceDate datetime,
        @RetreadProductID int,
        @RetreadPrice money,
        @RepairProductID int,
        @RepairPrice money,
        @OtherProductID int,
        @OtherPrice money,
        @TotalNet money,
        @TotalTax money,
        @Total money,
        @ASTranID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Post = 0,
                Order_No = @OrderNo,
                Billing_No = @InvoiceNo,
                Billing_Date = @InvoiceDate,
                AP_Products_ID = @RetreadProductID,
                Retread_Price = @RetreadPrice,
                AP_Repair_Products_ID = @RepairProductID,
                Repair_Price = @RepairPrice,
                AP_Other_Products_ID = @OtherProductID,
                Other_Price = @OtherPrice,
                Amount = @TotalNet,
                Tax = @TotalTax,
                Total = @Total,
                AS_Transactions_ID = @ASTranID,
                Billing_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID

            SET @RetCode = 1
        END


RETURN @RetCode

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




























-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_Casing_Credits
--Purpose       :Update Jobs with new Casing Credit data
--Date          :2011/05/08
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AF_Update_Job_Casing_Credits
    (
        @JobTicketID int,
        @ASTranID int,
        @RefundNo varchar(20),
        @RefundDate datetime,
        @TotalNet money,
        @TotalTax money,
        @Total money,
        @AdjustmentID int,
        @CasingCredit money,
        @StockCost money,
        @StockProductID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Post = 0,
                AS_Transactions_ID = @ASTranID,
                Billing_No = @RefundNo,
                Billing_Date = @RefundDate,
                Casing_Credit = @CasingCredit,
                Amount = @TotalNet,
                Tax = @TotalTax,
                Total = @Total,
                Billing_User_ID = @UserID,
                Adjustment_Date = @RefundDate,
                AP_Inventory_Adjustments_ID = @AdjustmentID,
                Stock_Cost = @StockCost,
                AP_Stock_Products_ID = @StockProductID,
                Adjustment_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID

            SET @RetCode = 1
        END


RETURN @RetCode



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_Claim_GRN
--Purpose       :Update Jobs with new Claim GRN data
--Date          :2011/06/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AF_Update_Job_Claim_GRN
    (
        @JobTicketID int,
        @InvoiceNo varchar(20),
        @InvoiceDate datetime,
        @FailReasonID smallint,
        @RetreadProductID int,
        @RetreadCost money,
        @RepairProductID int,
        @RepairCost money,
        @OtherProductID int,
        @OtherCost money,
        @GRVID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Post = 0,
                Invoice_No = @InvoiceNo,
                GRV_Date = @InvoiceDate,
                Lup_AP_Fail_Reasons_ID = @FailReasonID,
                AP_Products_ID = @RetreadProductID,
                Retread_Cost = @RetreadCost,
                AP_Repair_Products_ID = @RepairProductID,
                Repair_Cost = @RepairCost,
                AP_Other_Products_ID = @OtherProductID,
                Other_Cost = @OtherCost,
                AO_GRV_ID = @GRVID,
                GRV_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID

            SET @RetCode = 1
        END


RETURN @RetCode
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_Claim_Refund
--Purpose       :Update Jobs with new Customer Claim Refund data
--Date          :2011/06/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Update_Job_Claim_Refund
    (
        @JobTicketID int,
        @OrderNo varchar(20),
        @InvoiceNo varchar(20),
        @InvoiceDate datetime,
        @FailReasonID smallint,
        @RetreadProductID int,
        @RetreadPrice money,
        @RepairProductID int,
        @RepairPrice money,
        @OtherProductID int,
        @OtherPrice money,
        @TotalNet money,
        @TotalTax money,
        @Total money,
        @ASTranID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int,
            @FailDesc varchar(50),
            @Notes varchar(100),    
            @Comments varchar(250),
            @CommentID int

    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Post = 0,
                Order_No = @OrderNo,
                Billing_No = @InvoiceNo,
                Billing_Date = @InvoiceDate,
                Lup_AP_Fail_Reasons_ID = @FailReasonID,
                AP_Products_ID = @RetreadProductID,
                Retread_Price = @RetreadPrice,
                AP_Repair_Products_ID = @RepairProductID,
                Repair_Price = @RepairPrice,
                AP_Other_Products_ID = @OtherProductID,
                Other_Price = @OtherPrice,
                Amount = @TotalNet,
                Tax = @TotalTax,
                Total = @Total,
                AS_Transactions_ID = @ASTranID,
                Billing_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID


            --> ADD the FAIL REASON to the AS_Transactions.Comment
            IF @FailReasonID > 0
                BEGIN
                    SELECT @CommentID = ISNULL(AW_Comments_ID, 0)
                    FROM AS_Transactions
                    WHERE AS_Transactions_ID = @ASTranID

                    IF @CommentID > 0
                        BEGIN
                            SELECT @FailDesc = ISNULL(Description, '')
                            FROM Lup_AP_Fail_Reasons
                            WHERE Lup_AP_Fail_Reasons_ID = @FailReasonID

                            SET @Notes = 'Job No ' + CONVERT(varchar(20), @JobTicketID) + ': ' + RTRIM(LTRIM(@FailDesc)) + ',  '

                            SELECT @Comments = ISNULL(Comment, '')
                            FROM AW_Comments
                            WHERE AW_Comments_ID = @CommentID

                            SET @Comments = @Comments + @Notes
                            SET @Comments = LEFT(@Comments, 500)

                            UPDATE AW_Comments
                            SET Comment = @Comments
                            WHERE AW_Comments_ID = @CommentID
                        END
                END

            SET @RetCode = 1
        END


RETURN @RetCode


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_GRV
--Purpose       :Update Jobs with new GRV data
--Date          :2011/05/01
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AF_Update_Job_GRV
    (
        @JobTicketID int,
        @InvoiceNo varchar(20),
        @InvoiceDate datetime,
        @RetreadProductID int,
        @RetreadCost money,
        @RepairProductID int,
        @RepairCost money,
        @OtherProductID int,
        @OtherCost money,
        @GRVID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Post = 0,
                Invoice_No = @InvoiceNo,
                GRV_Date = @InvoiceDate,
                AP_Products_ID = @RetreadProductID,
                Retread_Cost = @RetreadCost,
                AP_Repair_Products_ID = @RepairProductID,
                Repair_Cost = @RepairCost,
                AP_Other_Products_ID = @OtherProductID,
                Other_Cost = @OtherCost,
                AO_GRV_ID = @GRVID,
                GRV_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID

            SET @RetCode = 1
        END


RETURN @RetCode















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_Tickets
--Purpose       :Update edited Job Ticket data
--Date          :2011/06/10
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AF_Update_Job_Tickets
    (
        @JobTicketID int,
        @JobNo int,
        @JobDate datetime,
        @CustomerID int,
        @OrderNo varchar(20),
        @ProductID int,
        @MakeID int,
        @SerialNo varchar(20),
        @InstructionID smallint,
        @Comment varchar(20),
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0


    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Job_No = @JobNo,
                Job_Date = @JobDate,
                AC_Customers_ID = @CustomerID,
                Order_No = @OrderNo,
                AP_Products_ID = @ProductID,
                Lup_AP_Product_Manufacturers_ID = @MakeID,
                Serial_No = @SerialNo,
                Lup_AF_Instructions_ID = @InstructionID,
                Comment = @Comment,
                Job_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID

            SET @RetCode = 1
        END


RETURN @RetCode
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Job_Waybills
--Purpose       :Update Jobs with new Waybill data
--Date          :2011/04/26
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AF_Update_Job_Waybills
    (
        @JobTicketID int,
        @JobDate datetime,
        @CustomerID int,
        @OrderNo varchar(20),
        @ProductID int,
        @MakeID int,
        @SerialNo varchar(20),
        @InstructionID smallint,
        @Comment varchar(20),
        @WaybillNo int,
        @WaybillDate datetime,
        @FactoryID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int,
            @Prev_On_Hand Decimal(9,3),
            @New_On_Hand Decimal(9,3)


    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET Post = 0,
                Job_Date = @JobDate,
                AC_Customers_ID = @CustomerID,
                Order_No = @OrderNo,
                AP_Products_ID = @ProductID,
                Lup_AP_Product_Manufacturers_ID = @MakeID,
                Serial_No = @SerialNo,
                Lup_AF_Instructions_ID = @InstructionID,
                Comment = @Comment,
                AF_Waybills_ID = @WaybillNo,
                Waybill_Date = @WaybillDate,
                AO_Suppliers_ID = @FactoryID,
                Waybill_User_ID = @UserID
            WHERE AF_Job_Tickets_ID = @JobTicketID


            ------------------------------------------------------------------------
            --> DO NOT update Stock On Hand for Product
            ------------------------------------------------------------------------


            SET @RetCode = 1
        END


RETURN @RetCode














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Refund_Job_No
--Purpose       :CLEAR ONE Job No Billing data for Refund Job No
--Date          :2011/08/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Update_Refund_Job_No
    (
        @JobNo int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int


    SET @RetCode = 0


    IF @JobNo > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET AS_Transactions_ID = Null,
                Billing_Date = Null,
                Billing_No = Null,
                Retread_Price = Null,
                Repair_Price = Null,
                Other_Price = Null,
                Amount = Null,
                Tax = Null,
                Total = Null,
                Comment = Null,
                Billing_User_ID = Null
            WHERE Job_No = @JobNo

            -- Stock On Hand update is done in:    sp_AF_Refund_Job_No_Detail_Insert

            SET @RetCode = 1
        END


RETURN @RetCode



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Returned_GRV_Item
--Purpose       :Update Jobs data with Returned GRV Item data
--Date          :2011/08/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AF_Update_Returned_GRV_Item
    (
        @JobTicketID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int


    SET @RetCode = 0


    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET AO_GRV_ID = Null,
                GRV_Date = Null,
                Invoice_No = '',
                Retread_Cost = Null,
                Repair_Cost = Null,
                Other_Cost = Null,
                AP_Repair_Products_ID = Null,
                AP_Other_Products_ID = Null,
                GRV_User_ID = Null
            WHERE AF_Job_Tickets_ID = @JobTicketID

            -- Stock On Hand update is done in:    sp_AP_Update_Inventory_Details

            SET @RetCode = 1
        END


RETURN @RetCode
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AO_4000
--Purpose       :Retrieves List of Products based on Search Filter for Forecasting
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          :2001/07/08
--Authors       :TB
--Version       :
--2004.4.5      :24/05/09 - Added @SearchFilter = 11 - 3Sigma Touched Products
--2004.4.8      :29/04/10 - Modified Active Products with On Hand NOT YET SELECTED to
--              :           EXCLUDE Non-Stock and INCLUDE non-zero Min_Stock_Level items
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_4000
    (
        @CompanyID int, 
        @SearchFilter int,
        @FetchChoice int,
        @Value int,
        @StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

-->ALL Products
    IF @SearchFilter = 0
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY [Description]
    ELSE
--TYPE
    IF @SearchFilter = 1
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Types_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY [Description]
    ELSE
--DEPARTMENT
    IF @SearchFilter = 2
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Departments_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY [Description]
    ELSE
--TOP 20%
    IF @SearchFilter = 3
        SELECT  [ID], [Description] as Product, Code
        FROM dbo.fn_AS_Top20Perc_Sales_Tran_Value(@CompanyID, @FetchChoice, @StartDate, @EndDate)
    ELSE
--GROUP
    IF @SearchFilter = 4
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Groups_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY [Description]
    ELSE
--LOCATION
    IF @SearchFilter = 5
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Locations_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY [Description]
    ELSE
--NEXT 30%
    IF @SearchFilter = 6
        SELECT a.[ID], a.[Description] as Product, a.Code
        FROM dbo.fn_AS_Top50Perc_Sales_Tran_Value(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
             LEFT JOIN dbo.fn_AS_Top20Perc_Sales_Tran_Value(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.ID = b.ID
        WHERE b.ID is null
    ELSE
--SUPPLIER
    IF @SearchFilter = 7
        SELECT p.AP_Products_ID as [ID], p.[Description] as Product, p.Product_Code as Code
        FROM AP_Products p
                 JOIN AO_Suppliers s
                     ON p.Default_Supplier_ID = s.AO_Suppliers_ID
                 JOIN AP_Products_Suppliers ps
                     ON p.AP_Products_ID = ps.AP_Products_ID 
        WHERE ps.AO_Suppliers_ID = @Value AND
              p.AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY p.[Description]
    ELSE
--MANUFACTURER
    IF @SearchFilter = 8
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Manufacturers_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY [Description]
--LAST 50%
    IF @SearchFilter = 9
        SELECT a.[ID], a.[Description] as Product, a.Code
        FROM dbo.fn_AS_Top100Perc_Sales_Tran_Value(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
             LEFT JOIN dbo.fn_AS_Top50Perc_Sales_Tran_Value(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.ID = b.ID
        WHERE b.ID is null
-->Below MSL
    IF @SearchFilter = 10
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Min_Stock_Level > 0 AND
              On_Hand <= Min_Stock_Level
        ORDER BY [Description]

---------------------------------------------------------------------------
--> 3Sigma Touched Products - Borrowed from Cardex sp_AP_Select_Touched_Products
---------------------------------------------------------------------------
    IF @SearchFilter = 11
        BEGIN
            DECLARE @ActiveProducts table
                        (
                            [AP_Products_ID] int
                        )

            --> Active Products with Sales
            INSERT INTO @ActiveProducts
            SELECT DISTINCT AP_Products_ID
            FROM AS_Transaction_Details
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1 AND
                  dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


            --> Active Orders
            INSERT INTO @ActiveProducts
            SELECT DISTINCT AP_Products_ID
            FROM AO_Order_Details od
                INNER JOIN AO_Orders oh
                    ON od.AO_Orders_ID = oh.AO_Orders_ID
            WHERE oh.AW_User_Companies_ID = @CompanyID AND
                  oh.Slu_AW_Active_ID = 1 AND
                  oh.Date_Ordered IS NOT NULL AND
                  oh.Complete <> 1 AND
                  ISNULL(od.Order_Qty, 0) +
                  ISNULL(od.Back_Order_Qty, 0) -
                  ISNULL(od.Received_Qty, 0) > 0 AND
                  dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


            --> Active Products with On Hand NOT YET SELECTED
            INSERT INTO @ActiveProducts
            SELECT DISTINCT AP_Products_ID
            FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1 AND
                  Slu_AW_YesNo_Non_Stock_Item = 0 AND
                 (On_Hand <> 0 OR Min_Stock_Level <> 0) AND
                  AP_Products_ID NOT IN
                      (
                            SELECT DISTINCT AP_Products_ID
                            FROM @ActiveProducts
                      )


        	SELECT DISTINCT a.AP_Products_ID AS [ID],
                   ISNULL(p.[Description], '') AS [Product],
                   ISNULL(p.Product_Code, '') AS [Code]
            FROM @ActiveProducts a
                INNER JOIN AP_Products p
                    ON a.AP_Products_ID = p.AP_Products_ID
            ORDER BY [Product]
        END



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--Description   : sp_AO_4010
--Purpose       : Retrieves List of Products based on Search Filter for Forecasting
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          : 02 Aug 2001
--Authors       : TB
--Version       : 1.0
-------------------------------------------------------------------------------
--Returns a recordset of:
--    prior 24 WEEK sales, aggregated by WEEK NUMBER 
--    prior 24 MONTH sales, aggregated by MONTH NUMBER
--------------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE          PROCEDURE sp_AO_4010
	@ProductID int,
    @DataChoice int,
	@StartDate datetime,
	@EndDate datetime,
	@StartWeekNo int OUTPUT,
	@EndWeekNo int OUTPUT 
AS

SET NOCOUNT ON

IF @DataChoice = 0        --GET WEEKS
    BEGIN
        SET @StartWeekNo = CONVERT(int, @StartDate) / 7
        SET @EndWeekNo = CONVERT(int, @EndDate) / 7

        SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
               SUM(d.Quantity) as SumQty
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID and
             (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
              CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4)
        GROUP BY CONVERT(int, h.Transaction_Date) / 7
        ORDER BY WeekNo DESC
    END

IF @DataChoice = 1        --GET MONTHS
    BEGIN
        SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
        SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
        
        SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
               SUM(d.Quantity) as SumQty
        FROM AS_Transaction_Details d
             INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID and
             (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
              dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4)
        GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
        ORDER BY DateString DESC
    END

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-----------------------------------------------------------------------------
--Description   :sp_AO_4020
--Purpose       :Retrieves Order Qty, Orders Pending & Candidates Pending
--              :
--Parameters    :
--Date          :02 Aug 2001
--Authors       :TB
--Version       :1.0
--Mods          :13/04/03 - Added ISNULL validation
-----------------------------------------------------------------------------

CREATE         Procedure sp_AO_4020
    (
        @ProductID int
    )

AS

SET NOCOUNT ON

SELECT (SELECT (ISNULL(SUM(od.Order_Qty), 0) +
                ISNULL(SUM(od.Back_Order_Qty), 0) -
                ISNULL(SUM(od.Received_Qty), 0))
        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 = @ProductID) AS [Qty on order],
       
       (SELECT ISNULL(SUM(od.Order_Qty), 0) +
               ISNULL(SUM(od.Back_Order_Qty), 0)
        FROM AO_Order_Details od
            INNER JOIN AO_Orders o
                ON od.AO_Orders_ID = o.AO_Orders_ID
        WHERE o.Date_Ordered IS NULL AND
              od.AP_Products_ID = @ProductID) AS [Orders Pending],

       (SELECT ISNULL(SUM(oc.Qty), 0)
        FROM AO_Order_Candidates oc
        WHERE oc.AP_Products_ID = @ProductID) AS [Candidates Pending]

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_4030
--Purpose       :Retrieves Product Data for one product
--Parameters    :
--Date          :02 Aug 2001
--Authors       :TB
--MODS          :22/08/02 - Dynamically SELECT [Last Sale Date] from AS_Transactions
--2004.4.5      :23/05/09 - Replaced AS_Transaction_Details AS source of [Last Sale Date]
--              :           because this fetched Latest Date of ANY Transaction Type !!!!
--              :           with p.Last_Sale_Date AS [Last Sale Date] which gets the
--              :           [Last Sale Date] of an INVOICE for the product
--              :24/05/09 - Replaced [Stock Reserved] with standard DYNAMIC reserved
--              :24/05/09 - Added fields [Supplier No] [LastCost] [AvgCost] [UnitPrice]
--              :28/05/09 - Added fields [PurchDate] [PurchQty]
--              :25/06/09 - Commented [Manuf Description] [Manuf Code] [PurchDate] PurchQty]
--              :           [StdCost] and [UnitPrice] because they are NOT USED
--2004.4.8      :06/05/10 - Changed JOINS to LEFT JOIN
-------------------------------------------------------------------------------

CREATE              Procedure sp_AO_4030
    (
        @ProductID int
    )
AS

SET NOCOUNT ON

    SELECT p.AP_Products_ID AS [ID],
           p.Description AS [Description],
           p.Product_Code AS [Product Code],
--            p.Manufacturer_Description AS [Manuf Description],
--            p.Manufacturer_Code AS [Manuf Code],
           s.AO_Suppliers_ID AS [Default Supplier ID],
           s.Supplier_Name AS [Default Supplier],
           s.Supplier_Number AS [Supplier No],
           p.On_Hand AS [Stock On Hand],
           CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) AS [Stock Reserved],
           p.Last_Sale_Date AS [Last Sale Date],
--            CONVERT(datetime, dbo.fn_AP_Get_Last_Purchase_Date(p.AP_Products_ID)) AS [PurchDate],
--            CONVERT(decimal(12, 3), dbo.fn_AP_Get_Last_Purchase_Qty(p.AP_Products_ID)) AS [PurchQty],
           p.Service_Level AS [Service Level],
           p.Min_Order_Qty AS [Min Order Qty],
           p.Max_Order_Qty AS [Max Order Qty],
           ps.Lead_Time AS [Lead Time],
           p.Min_Stock_Level AS [Min Stock Level],
           p.Last_Cost AS [LastCost],
           p.Average_Cost AS [AvgCost]
--            p.Standard_Cost AS [StdCost],
--            CONVERT(money, dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate())) AS [UnitPrice]
    FROM AP_Products p
             LEFT JOIN AO_Suppliers s
                 ON p.Default_Supplier_ID = s.AO_Suppliers_ID
             LEFT JOIN AP_Products_Suppliers ps
                 ON p.AP_Products_ID = ps.AP_Products_ID 
    WHERE p.AP_Products_ID = @ProductID

SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--Description   : sp_AO_4040
--Purpose       : Builds lists for Search Filters
--              :
--Parameters    :
--Date          : 02 Aug 2001
--Authors       : TB
--Version       : 1.0
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AO_4040
    (
        @DataMember varchar(20) ,
        @CompanyID int = Null
    )  
AS

SET NOCOUNT ON

   IF @DataMember = 'Types'
      SELECT Lup_AP_Product_Types_ID as [ID], [Description] 
      FROM Lup_AP_Product_Types
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @DataMember = 'Groups'
      SELECT Lup_AP_Product_Groups_ID as [ID], [Description]
      FROM Lup_AP_Product_Groups
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @DataMember = 'Suppliers'
      SELECT AO_Suppliers_ID AS [ID], [Supplier_Name] as [Description]
      FROM AO_Suppliers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @DataMember = 'Departments'
      SELECT Lup_AP_Product_Departments_ID as [ID], [Description]
      FROM Lup_AP_Product_Departments
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @DataMember = 'Manufacturers'
      SELECT Lup_AP_Product_Manufacturers_ID as [ID], [Description]
      FROM Lup_AP_Product_Manufacturers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @DataMember = 'Locations'
      SELECT Lup_AP_Product_Locations_ID as [ID], [Description]
      FROM Lup_AP_Product_Locations
      WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AO_Add_Order_Candidates_To_Scan_List
--Purpose       :Inventory Manager Add to Shopping List button
--Date          :05 OCT 2003
--Authors       :TB
--Version       :1.0.0
--MODS          :13/10/03 - Added @RemoteID input parameter
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Add_Order_Candidates_To_Scan_List
    (
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @RemoteID int,
            @ReturnValue int


    SET @ReturnValue = 0


    SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          Default_Connection = 1


    BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		BEGIN TRANSACTION

            INSERT AO_Order_Candidates_Temp
                (
                    AP_Products_ID,
                    AO_Suppliers_ID,
                    Product_Description,
                    Product_Code,
                    Order_Item,
                    On_Hand,
                    Order_Qty,
                    Selling,
                    Trade_Discount,
                    Last_Cost,
                    Outstanding_Order_Qty,
                    Pending_Order_Qty,
                    Last_Order_Date,
                    Last_Sale_Date,
                    Service_Level,
                    Min_Stock_Level,
                    Max_Order_Qty,
                    Min_Order_Qty,
                    Sales_Order_Reserved,
                    Job_Reserved,
                    Notes,
                    AW_Remote_Access_ID,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
            SELECT
                a.AP_Products_ID,
                b.AO_Suppliers_ID,
                a.[Description],
                a.Product_Code,
                b.Ready,
                ISNULL(a.On_Hand, 0),
                ISNULL(b.Qty, 0),
                ISNULL(a.Price1_Price1, 0),
                ISNULL(d.Trade_Disc_Perc, 0),
                ISNULL(b.Last_Cost, 0),
        
        --> On Order
                (SELECT
                    CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                         THEN 0
                         ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                         END
                    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 = a.AP_Products_ID),
        --> Pending Orders
                (SELECT
                    CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                         THEN 0
                         ELSE (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty))
                         END
                    FROM AO_Order_Details od
                        INNER JOIN AO_Orders o
                            ON od.AO_Orders_ID = o.AO_Orders_ID
                    WHERE o.Date_Ordered IS NULL AND
                          od.AP_Products_ID = a.AP_Products_ID),
        
        --> Last Order Date
                (SELECT TOP 1 CONVERT(CHAR(10), Date_Ordered, 121)
                    FROM AO_Order_Details od
                        INNER JOIN AO_Orders o
                            ON od.AO_Orders_ID = o.AO_Orders_ID
                    WHERE o.Date_Ordered IS NOT NULL AND
                          od.AP_Products_ID = a.AP_Products_ID
                    ORDER BY Date_Ordered DESC),
        
                CONVERT(CHAR(10), a.Last_Sale_Date, 121),
                ISNULL(a.Service_Level, 1) AS [SL],
                ISNULL(a.Min_Stock_Level, 0) AS [MSL],
                ISNULL(a.Min_Order_Qty, 0) as [Min],
                ISNULL(a.Max_Order_Qty, 0) as [Max],
                ISNULL(Sales_Order_Reserved, 0),
                ISNULL(Job_Reserved, 0),
                b.Notes AS [Notes],
                @RemoteID,
                b.Date_Captured,
                b.[User_ID],
                @CompanyID
        
            FROM AP_Products a
                INNER JOIN AO_Order_Candidates b
                    ON a.AP_Products_ID = b.AP_Products_ID
                LEFT JOIN AO_Suppliers c
                    ON b.AO_Suppliers_ID = c.AO_Suppliers_ID
                INNER JOIN AP_Products_Suppliers d
                    ON d.AP_Products_ID = b.AP_Products_ID AND
                       d.AO_Suppliers_ID = b.AO_Suppliers_ID
            WHERE b.AW_User_Companies_ID = @CompanyID


            SET @ReturnValue = 1


        COMMIT TRANSACTION

    END


    IF @ReturnValue = 1
        BEGIN
            DELETE
            FROM AO_Order_Candidates
            WHERE AW_User_Companies_ID = @CompanyID
        END        


RETURN @ReturnValue



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Add_Product_To_Order_Candidates
--Purpose       :Check if @ProductID exists in Order Candidates
--				:If EXISTS then UPDATE else ADD new Candidate
--Date          :13 JAN 2002
--Authors       :TB
--MODS          :13/10/03 - Added @RemoteID input parameter
--2004.3.7      :22/11/07 - Added using Standard_Cost as @Unit_Cost if 
--              :           chkProcureStdCostPricing parameter = '1'
--              :24/11/07 - Added Select CURRENT SELLING if @Unit_Cost = 0
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AO_Add_Product_To_Order_Candidates
    (
       	@ProductID int,
       	@SuppliersID int = 0,
    	@Qty decimal(9,3) = 0,
       	@Notes varchar(50) = null,
       	@Originator int,
       	@User_ID int,
       	@CompanyID int,
        @RemoteID int
    )

AS

SET NOCOUNT ON


    DECLARE @AO_Order_Candidates_ID int,
            @Unit_Cost money,
            @ExistingID int,
            @Last_Qty decimal(9,3),
            @Last_Reviews int,
            @UseStdCost varchar(250)


    BEGIN	
    	SELECT @ExistingID = AO_Order_Candidates_ID,
               @Last_Qty = Qty,
               @Last_Reviews = Reviews
    	FROM AO_Order_Candidates
    	WHERE AP_Products_ID = @ProductID AND
    		  AO_Suppliers_ID = @SuppliersID AND
    		  AW_User_Companies_ID = @CompanyID

    	
--     	SELECT @Unit_Cost = Last_Cost
--     	FROM AP_Products
--     	WHERE AP_Products_ID = @ProductID AND
--     		  AW_User_Companies_ID = @CompanyID	

        -------------------------------------------------------
    --> Get Use Product Standard Cost in Procurement Manager Unit Pricing parameter
        -------------------------------------------------------
        SELECT @UseStdCost = ISNULL(Control_Value, '')
        FROM Sys_AW_Options
        WHERE Control_Type = 'CheckBox' AND
              Control_Name = 'chkProcureStdCostPricing' AND
              Control_Index = 0 AND
              AW_User_Companies_ID = @CompanyID


        IF @UseStdCost = '1'
            BEGIN
            	SELECT @Unit_Cost = ISNULL(Standard_Cost, 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END

            IF @Unit_Cost = 0
                BEGIN
                	SELECT @Unit_Cost = ISNULL(Last_Cost, 0)
                	FROM AP_Products
                	WHERE AP_Products_ID = @ProductID AND
                		  AW_User_Companies_ID = @CompanyID
                END

        IF @UseStdCost <> '1'
            BEGIN
            	SELECT @Unit_Cost = ISNULL(Last_Cost, 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END


        IF @Unit_Cost = 0
            BEGIN
                SELECT @Unit_Cost = ISNULL(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()), 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END
        -------------------------------------------------------

    	IF @ExistingID is NULL
    		EXEC sp_AO_Insert_Order_Candidates @ProductID,
                                               @SuppliersID,
                                               @Qty,
                                               @Unit_Cost,
                                               @Notes,
                                               1,
                                               @Originator,
                                               @User_ID,
                                               @CompanyID,
                                               @RemoteID
    	ELSE 
    		UPDATE AO_Order_Candidates							
    		SET Qty = @Last_Qty + @Qty,
    			Last_Cost = @Unit_Cost,
    			Reviews = @Last_Reviews + 1,
    			Notes = @Notes,
    			Originator = @Originator,
    			[User_ID] = @User_ID
    		WHERE AO_Order_Candidates_ID = @ExistingID


    END



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Add_Product_To_Order_Candidates_RET
--Purpose       :Check if @ProductID exists in Order Candidates
--				:If EXISTS then UPDATE else ADD new Candidate
--Date          :13 JAN 2002
--Authors       :TB
--MODS          :13/10/03 - Added @RemoteID input parameter
--2004.3.7      :22/11/07 - Added using Standard_Cost as @Unit_Cost if 
--              :           chkProcureStdCostPricing parameter = '1'
--              :24/11/07 - Added Select CURRENT SELLING if @Unit_Cost = 0
--RL	V6.3	:2017-02-09 - Added return value AO_Order_Candidates_ID to be used in sales order
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Add_Product_To_Order_Candidates_RET]
    (
       	@ProductID int,
       	@SuppliersID int = 0,
    	@Qty decimal(9,3) = 0,
       	@Notes varchar(50) = null,
       	@Originator int,
       	@User_ID int,
       	@CompanyID int,
        @RemoteID int
    )
AS

SET NOCOUNT ON

    DECLARE @AO_Order_Candidates_ID int,
            @Unit_Cost money,
            @ExistingID int,
            @Last_Qty decimal(9,3),
            @Last_Reviews int,
            @UseStdCost varchar(250),
			@ExistingNote varchar(50)
            
    BEGIN	
    	SELECT @ExistingID = AO_Order_Candidates_ID,
               @Last_Qty = Qty,
               @Last_Reviews = Reviews,
			   @ExistingNote = Notes
    	FROM AO_Order_Candidates
    	WHERE AP_Products_ID = @ProductID AND
    		  AO_Suppliers_ID = @SuppliersID AND
    		  AW_User_Companies_ID = @CompanyID

    	
--     	SELECT @Unit_Cost = Last_Cost
--     	FROM AP_Products
--     	WHERE AP_Products_ID = @ProductID AND
--     		  AW_User_Companies_ID = @CompanyID	

        -------------------------------------------------------
    --> Get Use Product Standard Cost in Procurement Manager Unit Pricing parameter
        -------------------------------------------------------
        SELECT @UseStdCost = ISNULL(Control_Value, '')
        FROM Sys_AW_Options
        WHERE Control_Type = 'CheckBox' AND
              Control_Name = 'chkProcureStdCostPricing' AND
              Control_Index = 0 AND
              AW_User_Companies_ID = @CompanyID


        IF @UseStdCost = '1'
            BEGIN
            	SELECT @Unit_Cost = ISNULL(Standard_Cost, 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END

            IF @Unit_Cost = 0
                BEGIN
                	SELECT @Unit_Cost = ISNULL(Last_Cost, 0)
                	FROM AP_Products
                	WHERE AP_Products_ID = @ProductID AND
                		  AW_User_Companies_ID = @CompanyID
                END

        IF @UseStdCost <> '1'
            BEGIN
            	SELECT @Unit_Cost = ISNULL(Last_Cost, 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END


        IF @Unit_Cost = 0
            BEGIN
                SELECT @Unit_Cost = ISNULL(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()), 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END
        -------------------------------------------------------
--Select @ExistingID As '@ExistingID'
    	IF @ExistingID is NULL
    	BEGIN
    		EXEC @ExistingID = sp_AO_Insert_Order_Candidates	@ProductID,
																@SuppliersID,
																@Qty,
																@Unit_Cost,
																@Notes,
																1,
																@Originator,
																@User_ID,
																@CompanyID,
																@RemoteID
                                               
			--SELECT @ExistingID = Scope_Identity()
		END
    	ELSE
    	BEGIN
			IF @ExistingNote Like '%Back Order - %'
			BEGIN
				IF @Notes Like '%Back Order - %'
				BEGIN
					SELECT @Notes = REPLACE(@Notes, 'Back Order - ',', ')

					SELECT @Notes = LEFT(@ExistingNote + @Notes,50)
				END
			END
		 
    		UPDATE AO_Order_Candidates							
    		SET Qty = @Last_Qty + @Qty,
    			Last_Cost = @Unit_Cost,
    			Reviews = @Last_Reviews + 1,
    			Notes = @Notes,
    			Originator = @Originator,
    			[User_ID] = @User_ID
    		WHERE AO_Order_Candidates_ID = @ExistingID
		END

    END
RETURN @ExistingID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AO_Add_Scan_List_To_Order_Candidates
--Purpose       :Inventory Manager Add to Scan List button
--Date          :05 OCT 2003
--Authors       :TB
--Version       :1.0.0
--MODS          :13/10/03 - Added @RemoteID input parameter
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Add_Scan_List_To_Order_Candidates
	(
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @ProductID int,
            @SupplierID int,
            @OrderQty decimal(9,3),
            @Notes varchar(50),
            @OriginatorID int,
            @UserID int,
            @Companies_ID int,
            @RemoteID int,
            @ReturnValue int


    SET @ReturnValue = 0

    BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		BEGIN TRANSACTION

        	DECLARE Scan_Cursor CURSOR FOR
                (
                    SELECT
                       	AP_Products_ID,
                       	AO_Suppliers_ID,
                    	Order_Qty,
                       	Notes,
                       	[User_ID],
                       	AW_User_Companies_ID,
                        AW_Remote_Access_ID
                    FROM AO_Order_Candidates_Temp
                    WHERE AW_User_Companies_ID = @CompanyID
                )
        
        	OPEN Scan_Cursor
        
            	FETCH NEXT FROM Scan_Cursor 
            	INTO
                   	@ProductID,
                   	@SupplierID,
                	@OrderQty,
                   	@Notes,
                   	@UserID,
                   	@Companies_ID,
                    @RemoteID
            	
            	WHILE @@FETCH_STATUS = 0
            	BEGIN

                    SET @OriginatorID = @UserID

                    EXEC sp_AO_Add_Product_To_Order_Candidates 
                                               	@ProductID,
                                               	@SupplierID,
                                            	@OrderQty,
                                               	@Notes,
                                               	@OriginatorID,
                                               	@UserID,
                                               	@Companies_ID,
                                                @RemoteID
    
                	FETCH NEXT FROM Scan_Cursor 
                	INTO
                       	@ProductID,
                       	@SupplierID,
                    	@OrderQty,
                       	@Notes,
                       	@UserID,
                       	@Companies_ID,
                        @RemoteID
        
            	END
        	
        	CLOSE Scan_Cursor
        
        	DEALLOCATE Scan_Cursor
    
    
            SET @ReturnValue = 1


        COMMIT TRANSACTION

    END


    IF @ReturnValue = 1
        BEGIN
            DELETE
            FROM AO_Order_Candidates_Temp
            WHERE AW_User_Companies_ID = @CompanyID
        END        


RETURN @ReturnValue


SET NOCOUNT OFF























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AO_Certify_Order_As_Complete
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/01/16
--Authors       :TB 
--Version       :1.0
--MODS          :
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Certify_Order_As_Complete
    (
    	@Order_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	

	UPDATE AO_Orders
	SET Complete = 1 
	WHERE AO_Orders_ID = @Order_ID AND
		  AW_User_Companies_ID	= @Company_ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AO_Clear_Order_Candidates
--Purpose       :
--Date          :27 SEP 2003
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Clear_Order_Candidates

AS

SET NOCOUNT ON


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates]

    
    CREATE TABLE [dbo].[AO_Order_Candidates] (
    	[AO_Order_Candidates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Ready] [bit] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Reviews] [int] NULL ,
    	[Originator] [int] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Order_Candidates] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Order_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Originator]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Ready]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Reviews]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Candidates].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates].[User_ID]'

    
    setuser










SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AO_Clear_Order_Candidates_Temp
--Purpose       :
--Date          :27 SEP 2003
--Authors       :TB
--Version       :1.0.0
--              :30/09/03 - Added AW_Remote_Access_ID and Network_Identity_Number
--              :01/10/03 - Added Total_Cost column
--              :04/10/03 - Added Selling and Trade_discount
--2004.3.7      :24/11/07 - Modified [Cost] and bracketed discount calc section
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Clear_Order_Candidates_Temp

AS

SET NOCOUNT ON


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates_Temp]

    
    CREATE TABLE [dbo].[AO_Order_Candidates_Temp] (
    	[AO_Order_Candidates_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Order_Item] [bit] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Selling] [money] NULL ,
    	[Trade_Discount] [money] NULL ,
    	[Cost] AS (round(([Selling] - ([Selling] * [Trade_Discount] / 100)),2)) ,
    	[Total_Cost] AS (round(([Order_Qty] * ([Selling] - [Selling] * [Trade_Discount] / 100)),2)) ,
    	[Last_Cost] [money] NULL ,
    	[Outstanding_Order_Qty] [decimal](9, 3) NULL ,
    	[Pending_Order_Qty] [decimal](9, 3) NULL ,
    	[Last_Order_Date] [datetime] NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Order_Candidates_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_Temp_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates_Temp].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates_Temp].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Order_Candidates_Temp].[Notes]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Outstanding_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Pending_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Selling]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[Service_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Trade_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates_Temp].[User_ID]'

    
    setuser















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--exec sp_AO_Select_Procurement_Orders 1

-------------------------------------------------------------------------------
--Description   :sp_AO_Create_Procurement_Purchase_Orders
--Purpose       :Create Candidates Temp Orders in Procurement Manager
--Date          :2003/11/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Create_Procurement_Purchase_Orders
    (
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT
        @CompanyID AS [CompanyID],
        a.AO_Order_Candidates_Temp_ID AS [ID],
        a.AW_Remote_Access_ID AS [Originator],
        a.AO_Suppliers_ID AS [SupplierID],
        a.AP_Products_ID AS [ProductID],
        b.Supplier_Name AS [Supplier],
        a.Order_Item AS [Order],

        a.Product_Description AS [Product],
        a.Product_Code as [Code],
        a.On_Hand AS [On Hand],
        a.Order_Qty AS [To Order],

        a.Selling AS [Selling],
        a.Trade_Discount AS [Disc %],
        a.Cost AS [Cost],
        a.Last_Cost AS [Last Cost],
        a.Total_Cost AS [Total Cost],

        a.Min_Stock_Level AS [MSL],
        a.Min_Order_Qty AS [Min],
        a.Max_Order_Qty AS [Max],
        a.Service_Level AS [SL],

        a.Notes AS [Notes],
        CONVERT(CHAR(10), a.Date_Captured, 121) AS [Captured],
        c.UserName AS [User]
    FROM AO_Order_Candidates_Temp a
        LEFT JOIN AO_Suppliers b
            ON a.AO_Suppliers_ID = b.AO_Suppliers_ID
        LEFT JOIN AW_Users c
            ON a.[User_ID] = c.AW_Users_ID
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.Order_Item = 1
    ORDER BY [Originator], [SupplierID], [Product]



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Delete_Inactive_Supplier
--Purpose       :DELETE ONE UNUSED Supplier Account with NO ACTIVITY VALIDATED in UI
--Date          :2009/03/15
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AO_Delete_Inactive_Supplier
	(
		@SupplierID int,
        @CompanyID int,
        @ActivityCNT int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int


    SET @ReturnCode = 0


    --> If ZERO ACTIVITY
    IF @ActivityCNT = 0
        BEGIN
            BEGIN TRAN Delete_Supplier
        
            	BEGIN
                    DELETE AO_Suppliers
                    WHERE AO_Suppliers_ID = @SupplierID AND
                          AW_User_Companies_ID = @CompanyID
                END

            COMMIT TRAN Delete_Supplier

            SET @ReturnCode = 1
        END




RETURN @ReturnCode












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   :sp_AO_Delete_Order_Candidate
--Purpose       :Removes a specified Record from Order Candidates
--Functionality :
--Parameters    :
--Date          : 2001/04/09
--Authors       : Charl
--Version       :1.0.0

CREATE Procedure sp_AO_Delete_Order_Candidate
(
    @Order_Candidates_ID int
)

AS
	DELETE 
	FROM AO_Order_Candidates
	WHERE  AO_Order_Candidates_ID = @Order_Candidates_ID

	SET NOCOUNT ON








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








--Description   :sp_AO_Delete_Order_Details
--Purpose       :Removes a specified Record from Order Details
--Functionality :
--Parameters    :
--Date          : 2001/04/26
--Authors       : Charl
--Version       : 1.0.0

CREATE  PROCEDURE sp_AO_Delete_Order_Details
(
    @Order_Details_ID int
)

AS
	DELETE 
	FROM AO_Order_Details
	WHERE  AO_Order_Details_ID = @Order_Details_ID

	SET NOCOUNT ON









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













---------------------------------------------------------------------------------
--Description   :sp_AO_Delete_Replenish_Scan_Product
--Purpose       :Deletes a selected Replenish Scan Product
--Functionality :
--Parameters    :
--Date          :2003/10/05
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Delete_Replenish_Scan_Product
    (
        @CandidateID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AO_Order_Candidates_Temp_ID
            FROM AO_Order_Candidates_Temp
            WHERE AO_Order_Candidates_Temp_ID = @CandidateID

        )
        BEGIN
            DELETE AO_Order_Candidates_Temp
            WHERE AO_Order_Candidates_Temp_ID = @CandidateID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AO_Drop_Enterprise_Supplier_Ageing
--Purpose       :Drops and re-creates AO_Enterprise_Supplier_Ageing table
--Date          :2008/10/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_AO_Drop_Enterprise_Supplier_Ageing

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0




    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Supplier_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Supplier_Ageing]

    
    CREATE TABLE [dbo].[AO_Enterprise_Supplier_Ageing] (
    	[AO_Enterprise_Supplier_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SuppNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Supplier_Ageing] ON [dbo].[AO_Enterprise_Supplier_Ageing]([Filter], [Supplier], [SuppNo]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Enterprise_Supplier_Ageing] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Supplier_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Supplier_Ageing_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Enterprise_Supplier_Ageing].[CompanyID]'

    
    setuser





    SET @ReturnValue = 1


RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AO_Enterprise_Ageing_Temp_Insert
--Purpose       :Saves an Ad-Hoc snapshot of Supplier AccountTransactions AS AT Now
--Functionality :ONLY Suppliers that have had transactions are selected
--Date          :2008/10/27
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AO_Enterprise_Ageing_Temp_Insert
	(
        @DatePicked DateTime, 
        @Filter varchar(50),
        @CompanyID int,
        @UserID int,
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
	)

AS

SET NOCOUNT ON

	DECLARE
        @PeriodProcedureID int,
        @FilterDesc varchar(50),
        @SupplierID int,
        @SupplierName varchar(90),
        @SupplierNumber varchar(10),
        @AccountBalance money,
        @StatementID int,
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @ReturnValue int,
        @Period1 varchar(6)


    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)

    SET @PeriodProcedureID = 0


--Wipe the TEMP table-------
    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AO_Enterprise_Ageing_Temp]

        
        CREATE TABLE [dbo].[AO_Enterprise_Ageing_Temp] (
        	[AO_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Supplier_Name] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Account_Balance] [money] NULL ,
        	[Current] [money] NULL ,
        	[30Days] [money] NULL ,
        	[60Days] [money] NULL ,
        	[90Days] [money] NULL ,
        	[120Days] [money] NULL ,
        	[150Days] [money] NULL ,
        	[180+Days] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Ageing_Temp] ON [dbo].[AO_Enterprise_Ageing_Temp]([Filter], [Supplier_Name], [Supplier_Number]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AO_Enterprise_Ageing_Temp] ADD 
        	CONSTRAINT [PK_AO_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AO_Enterprise_Ageing_Temp_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[120Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[150Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[180+Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[30Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[60Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[90Days]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Account_Balance]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Current]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Enterprise_Ageing_Temp].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Payment]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Enterprise_Ageing_Temp].[User_ID]'

        
        setuser



    END
----------------------------

    BEGIN
    
    --> Define a CURSOR for AO_Suppliers
    	DECLARE Supplier_Temp_Cursor CURSOR FOR
            (
                SELECT DISTINCT
                    c.AO_Suppliers_ID,
                    ISNULL(c.Supplier_Name, ''),
                    ISNULL(c.Supplier_Number, '')
                FROM AO_Suppliers c
                    INNER JOIN AO_Transactions t
                        ON c.AO_Suppliers_ID = t.AO_Suppliers_ID
                WHERE c.AW_User_Companies_ID = @CompanyID
            )
    
    	OPEN Supplier_Temp_Cursor
    
        	FETCH NEXT FROM Supplier_Temp_Cursor 
        	INTO
                @SupplierID,
                @SupplierName,
                @SupplierNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN

                IF @Filter = 'Type'
                    BEGIN
                        SELECT @FilterDesc = RTRIM(LTRIM(f.Description))
                        FROM Lup_AO_Supplier_Types f
                            INNER JOIN AO_Suppliers c
                                ON c.Lup_AO_Supplier_Types_ID = f.Lup_AO_Supplier_Types_ID
                        WHERE c.AO_Suppliers_ID = @SupplierID
                    END
                ELSE
                IF @Filter = 'Group'
                    BEGIN
                        SELECT @FilterDesc = RTRIM(LTRIM(f.Description))
                        FROM Lup_AO_Supplier_Groups f
                            INNER JOIN AO_Suppliers c
                                ON c.Lup_AO_Supplier_Groups_ID = f.Lup_AO_Supplier_Groups_ID
                        WHERE c.AO_Suppliers_ID = @SupplierID
                    END


        		SELECT
                        @AgePayment = Payment,
                        @AgeAmount = Amount,
                        @AgeCurrent = [Current],
                        @Age30Days = [30 Days],
                        @Age60Days = [60 Days],
                        @Age90Days = [90 Days],
                        @Age120Days = [120 Days],
                        @Age150Days = [150 Days],
                        @Age180Days = [180+ Days]
                FROM dbo.fn_AO_Supplier_Period_Ageing_Values
                        (
                        	@SupplierID, 
                        	@M1, @Y1,
                        	@M2, @Y2,
                        	@M3, @Y3,
                        	@M4, @Y4,
                        	@M5, @Y5,
                        	@M6, @Y6,
                        	@M7, @Y7
                        ) 


                SET @AccountBalance = @AgeCurrent + 
                                      @Age30Days + 
                                      @Age60Days + 
                                      @Age90Days + 
                                      @Age120Days + 
                                      @Age150Days + 
                                      @Age180Days

                IF NOT @AccountBalance = 0             --AND
--                         @AgeCurrent = 0 AND
--                         @Age30Days = 0 AND
--                         @Age60Days = 0 AND
--                         @Age90Days = 0 AND
--                         @Age120Days = 0 AND
--                         @Age150Days = 0 AND
--                         @Age180Days = 0

                BEGIN
            		INSERT INTO AO_Enterprise_Ageing_Temp
            			(
                            Filter,
                            AO_Suppliers_ID,
                            Supplier_Name,
                            Supplier_Number,
                            [User_ID],
                            AW_User_Companies_ID,
                            Amount,
                            Payment,
                            Account_Balance,
                            [Current],
                            [30Days],
                            [60Days],
                            [90Days],
                            [120Days],
                            [150Days],
                            [180+Days],
                            Date_Captured
                        )
            		VALUES
            			(
                            @FilterDesc,
                            @SupplierID,
                            rtrim(ltrim(@SupplierName)),
                            @SupplierNumber,
                            @UserID,
                            @CompanyID,
                            @AgeAmount,
                            @AgePayment,
                            @AccountBalance,
                            @AgeCurrent,
                            @Age30Days,
                            @Age60Days,
                            @Age90Days,
                            @Age120Days,
                            @Age150Days,
                            @Age180Days,
                            @DatePicked
                        )
                END

            --> Clear the Ageing Balances of THIS Supplier
            --> In the event that the next Suppliers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Supplier_Temp_Cursor 
            	INTO
                    @SupplierID,
                    @SupplierName,
                    @SupplierNumber
    
        	END
    	
    	CLOSE Supplier_Temp_Cursor
    
    	DEALLOCATE Supplier_Temp_Cursor

        SET @ReturnValue = 1

    END


SET NOCOUNT OFF


RETURN @ReturnValue

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--------------------------------------------------------------------------
--Description   :sp_AO_Fix_NULL_Payment_Accounting_Periods
--Date          :2003/12/23
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Fix_NULL_Payment_Accounting_Periods

AS

    SET NOCOUNT ON

	DECLARE @TranID int,
            @Date datetime,
            @ThisMonthID tinyint,
            @ThisYearID int,
            @LastMonthID tinyint,
            @LastYearID int,
            @Month tinyint,
        	@Year smallint,
            @YearID int,
            @CNT int

    SET @ThisMonthID = 0
    SET @ThisYearID = 0
    SET @LastMonthID = 0
    SET @LastYearID = 0
    SET @CNT = 0


------------------------------------------------------------------------
-- UPDATE AO_Transactions FROM AB_GL_Transactions 
------------------------------------------------------------------------
    UPDATE t
    SET t.Slu_AW_Months_ID = g.Slu_AW_Months_ID,
        t.Slu_AW_Years_ID = g.Slu_AW_Years_ID
    FROM AO_Transactions t
        INNER JOIN AO_Transactions_Transactions tt
            ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
        INNER JOIN AB_GL_Transactions g
            ON tt.Source_AO_Transactions_ID = g.AB_Transaction_Ref
    WHERE t.Sys_AW_Transaction_Types_ID = 12 AND
          t.Total_Amount = g.AB_Transaction_Amount
------------------------------------------------------------------------

------------------------------------------------------------------------
-- UPDATE REMAINING AO_Transactions FROM AO_Transactions 
------------------------------------------------------------------------
    BEGIN

    	DECLARE Supplier_Tran_Cursor CURSOR FOR
            (
                SELECT AO_Transactions_ID,
                       Document_Date AS [Date],
                       ISNULL(Slu_AW_Months_ID, 0),
                       ISNULL(Slu_AW_Years_ID, 0)
                FROM AO_Transactions
                WHERE Sys_AW_Transaction_Types_ID = 12
            )
    
    	OPEN Supplier_Tran_Cursor

        	FETCH NEXT FROM Supplier_Tran_Cursor 
        	INTO
                @TranID,
                @Date,
                @ThisMonthID,
            	@ThisYearID
        	
            SET @CNT = @CNT + 1

            IF @ThisMonthID = 0 OR @ThisYearID = 0
                BEGIN
                    IF @CNT = 1
                        BEGIN
                            SET @Month = MONTH(@Date)
                            SET @Year = YEAR(@Date)
                        
                            SELECT @YearID = Slu_AW_Years_ID
                            FROM Slu_AW_Years
                            WHERE [Description] = @Year

                            SET @ThisMonthID = @Month
                            SET @ThisYearID = @YearID

                            UPDATE AO_Transactions
                            SET Slu_AW_Months_ID = @ThisMonthID,
                                Slu_AW_Years_ID = @ThisYearID
                            WHERE AO_Transactions_ID = @TranID

                            PRINT CONVERT(varchar(20), @Year) + '::: '
                        END
                END

        	WHILE @@FETCH_STATUS = 0
            	BEGIN

                    PRINT CONVERT(varchar(20), @CNT) + ':: ' + 
                          CONVERT(varchar(20), @TranID) + ': ' + 
                          CONVERT(varchar(20), @ThisMonthID) + ', ' + 
                          CONVERT(varchar(20), @ThisYearID) + ', ' + 
                          CONVERT(varchar(20), @LastMonthID) + ', ' + 
                          CONVERT(varchar(20), @LastYearID)

                    IF @ThisMonthID = 0 OR @ThisYearID = 0
                        BEGIN
                            SET @ThisMonthID = @LastMonthID
                            SET @ThisYearID = @LastYearID

                            UPDATE AO_Transactions
                            SET Slu_AW_Months_ID = @ThisMonthID,
                                Slu_AW_Years_ID = @ThisYearID
                            WHERE AO_Transactions_ID = @TranID

                        END

                    SET @LastMonthID = @ThisMonthID
                    SET @LastYearID = @ThisYearID
    
                	FETCH NEXT FROM Supplier_Tran_Cursor 
                	INTO
                        @TranID,
                        @Date,
                        @ThisMonthID,
                    	@ThisYearID

                    SET @CNT = @CNT + 1

            	END
    	
    	CLOSE Supplier_Tran_Cursor
    
    	DEALLOCATE Supplier_Tran_Cursor

    END
------------------------------------------------------------------------


    SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description	:sp_AO_GRV_Select_Outstanding_Order_Details
--Purpose       :Fetches Outstanding Order items for an outstanding order
--              :
--Date			:2002/01/13
--Authors		:TB
--MODS          :
--2004.3.5      :29/04/07 - Added Product_Code field and [User] and [Active] JOINS
--V6.3	RL	2017-09-16 - Added product Price_1 to selection
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_GRV_Select_Outstanding_Order_Details]
    (
    	@Orders_ID int
    )

AS

SET NOCOUNT ON

	SELECT OD.AO_Order_Details_ID AS [ID],
        OD.AO_Orders_ID AS [FK ID],
        OD.AP_Products_ID AS [Products ID],
        P.[Description] AS [Product],
        P.Product_Code AS [Code],
        OD.Order_Qty AS [Qty],	
        OD.Free_Qty AS [Free Qty],
        OD.Back_Order_Qty AS [B/O Qty],
        OD.Received_Qty AS [Received Qty],
        OD.Receipt_Date AS [Receipt Date],	
        OD.Unit_Price AS [Unit Price],
        
        OD.Trade_Discount_Formula_ID AS [Trade_Discount_Formula_ID],
        OD.Trade_Discount_Amount AS [Trade Disc],
        OD.Trade_Discount_Percentage AS [Trade Disc Perc],
        OD.Rebate_Formula_ID AS [Rebate_Formula_ID],
        OD.Rebate_Discount_Amount AS [Rebate Disc],
        OD.Rebate_Discount_Percentage AS [Rebate Disc Perc],
        OD.Other_Discount_Formula_ID AS [Other_Discount_Formula_ID],
        OD.Other_Discount_Amount AS [Other Disc],
        OD.Other_Discount_Percentage AS [Other Disc Perc],
        
        OD.Net_Amount AS [Net Amount],
        OD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        TC.[Description] AS [Tax Code],
        OD.Tax_Amount AS [Tax],
        OD.Total_Cost AS [Total Cost],
        OD.Lead_Time AS [Lead Time],	
        OD.Date_Captured AS [Date Captured],
        OD.[User_ID] AS [User ID],
        u.UserName AS [User],
        OD.AW_User_Companies_ID AS [Company],
--        OD.Slu_AW_Active_ID AS [Active]
        a.[Description] AS [Active],
        P.On_Hand AS [On Hand],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) AS [Price 1]
    FROM AO_Order_Details OD
        LEFT JOIN AP_Products P
            ON OD.AP_Products_ID  = P.AP_Products_ID 
        LEFT JOIN Sys_AW_Tax_Codes TC
            ON OD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
        LEFT JOIN AW_Users u
            ON OD.[User_ID]  = u.AW_Users_ID
        LEFT JOIN Slu_AW_Active a
            ON OD.Slu_AW_Active_ID = a.Slu_AW_Active_ID

    WHERE OD.AO_Orders_ID = @Orders_ID AND
         (OD.Order_Qty + OD.Back_Order_Qty) > OD.Received_Qty


SET NOCOUNT ON

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AO_GRV_Select_Outstanding_Orders
--Purpose       :Fetches all outstanding orders for the specified supplier
--Functionality :
--Parameters    :
--Date          :2002/01/16
--Authors       :TB 
--Version       :1.0
--MODS          :
---------------------------------------------------------------------------------

CREATE   Procedure sp_AO_GRV_Select_Outstanding_Orders
    (
    	@SupplierID int = 0,
    	@Company_ID int			
    )

AS

--Outstanding Orders---------------------------------------------------------------------------------
    IF @SupplierID = 0
    	SELECT O.AO_Orders_ID AS [ID],
    		O.Order_Number AS [OrderNo],
    		O.Order_Date AS [Order Date],
    		O.Version AS [Version],
    		O.AW_Remote_Access_ID AS [Branch_Codes_ID],
    		S.Supplier_Name AS [Supplier],
    		O.AO_Suppliers_ID AS [SupplierID],
    		O.Supplier_Rep AS [Supplier Rep],
    		O.Supplier_Type AS [Supplier Type],
    		O.Date_Ordered AS [Date Ordered],
    		O.Confirmation AS [Confirmation],
    		O.Confirmation_Date AS [Confirmation Date],
    		O.Our_Ref AS [Our Ref],
    		O.Supplier_Reference AS [Supplier Ref],
    		O.Invoice_Type AS [Invoice Type],
    		O.Invoice_Total AS [Invoice Total],
    		O.Admin_Fee  AS [Admin Fee],
    		O.Trade_Discount_Total AS [Trade Discount],
    		O.Rebate_Discount_Total AS [Rebate Discount],
    		O.Other_Discount_Total AS [Other Discount],
    		O.Net_Amount AS [Net Amount],
    		O.Tax_Total AS [Tax Total],
    		O.Order_Total AS [Order Total],
    		O.Sys_AO_Delivery_Methods_ID AS [Delivery Method],
    		O.Send_To_Address AS [Send To Address],
    		O.Delivery_Addr1 AS [Street],
    		O.Delivery_Addr2 AS [Suburb],
    		O.Delivery_Addr3 AS [City],
    		O.Postal_Code AS [Post Code],
    		O.Date_Captured AS [Date Captured],
    		O.[User_ID] AS [User ID],
    		O.AW_User_Companies_ID AS [Company],
    		O.Slu_AW_Active_ID AS [Active]
    	FROM AO_Orders O
            LEFT JOIN AO_Suppliers S
                ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
    	WHERE O.Date_Ordered is not null AND
              O.Complete = 0 AND
              O.AW_User_Companies_ID = @Company_ID
    
    ELSE
    IF @SupplierID <> 0
    	SELECT O.AO_Orders_ID AS [ID],
    		O.Order_Number AS [OrderNo],
    		O.Order_Date AS [Order Date],		
    		O.Version AS [Version],
    		O.AW_Remote_Access_ID AS [Branch_Codes_ID],
    		S.Supplier_Name AS [Supplier],
    		O.AO_Suppliers_ID AS [SupplierID],
    		O.Supplier_Rep AS [Supplier Rep],
    		O.Supplier_Type AS [Supplier Type],
    		O.Date_Ordered AS [Date Ordered],
    		O.Confirmation AS [Confirmation],
    		O.Confirmation_Date AS [Confirmation Date],
    		O.Our_Ref AS [Our Ref],
    		O.Supplier_Reference AS [Supplier Ref],
    		O.Invoice_Type AS [Invoice Type],
    		O.Invoice_Total AS [Invoice Total],
    		O.Admin_Fee  AS [Admin Fee],
    		O.Trade_Discount_Total AS [Trade Discount],
    		O.Rebate_Discount_Total AS [Rebate Discount],
    		O.Other_Discount_Total AS [Other Discount],
    		O.Net_Amount AS [Net Amount],
    		O.Tax_Total AS [Tax Total],
    		O.Order_Total AS [Order Total],
    		O.Sys_AO_Delivery_Methods_ID AS [Delivery Method],
    		O.Send_To_Address AS [Send To Address],
    		O.Delivery_Addr1 AS [Street],
    		O.Delivery_Addr2 AS [Suburb],
    		O.Delivery_Addr3 AS [City],
    		O.Postal_Code AS [Post Code],
    		O.Date_Captured AS [Date Captured],
    		O.[User_ID] AS [User ID],
    		O.AW_User_Companies_ID AS [Company],
    		O.Slu_AW_Active_ID AS [Active]
    	FROM AO_Orders O LEFT JOIN AO_Suppliers S
    	ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
    	WHERE O.Date_Ordered is not null AND
    		O.Complete = 0 AND
    		O.AO_Suppliers_ID = @SupplierID AND
    		O.AW_User_Companies_ID = @Company_ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AO_Get_Discount_Category
--Purpose       :
--Functionality :Tables: Lup_AO_Discount_Categories
--Parameters    : 
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------


CREATE           PROCEDURE sp_AO_Get_Discount_Category
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT Lup_AO_Discount_Categories_ID AS [ID],
		[Description] AS [Discount Category],
		Date_Captured AS [Date],
		[User_ID] AS [User],
		Slu_AW_Active_ID AS [Active]
	FROM Lup_AO_Discount_Categories
	WHERE AW_User_Companies_ID = @Company_ID


-- -- MOD by TB but joins cannot update RS ?
-- 	SELECT a.Lup_AO_Discount_Categories_ID AS [ID],
--            a.[Description] AS [Discount Category],
--            a.Date_Captured AS [Date],
--             CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
--                      THEN ISNULL(b.Surname,'')
--                  WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
--                      THEN ISNULL(b.Surname,'')
--                  ELSE ISNULL(b.Surname,'') + ', ' + 
--                       LTRIM(ISNULL(b.FirstName,''))
--                  END AS [User],
--             c.Description AS [Active]
-- 	FROM Lup_AO_Discount_Categories a
-- 		INNER JOIN AW_users b
--             ON a.User_ID = b.AW_Users_ID
--         INNER JOIN Slu_AW_Active c
--             ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
-- 	WHERE AW_User_Companies_ID = @Company_ID





SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Get_Discount_Category_Per_Group
--Purpose       :Returns the Discount Categories for the selected Group
--Functionality :Tables: AO_Discount_Categories_Groups, Lup_AO_Discount_Categories
--Parameters    :
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Get_Discount_Category_Per_Group
    (
    	@GroupID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


	SELECT a.AO_Discount_Categories_Groups_ID AS [ID],
    	   a.Lup_AO_Discount_Groups_ID AS [FK ID],
    	   b.[Description] AS [Discount Category],
    	   a.Discount_Percentage AS [Disc %],
           a.Date_Captured AS [Date],
           a.[User_ID] AS [User],
           a.Slu_AW_Active_ID AS [Active]
	FROM AO_Discount_Categories_Groups a
        INNER JOIN Lup_AO_Discount_Categories b 
	        ON a.Lup_AO_Discount_Categories_ID = b.Lup_AO_Discount_Categories_ID
	WHERE a.Lup_AO_Discount_Groups_ID = @GroupID AND
          a.AW_User_Companies_ID = @Company_ID


-- 	SELECT a.AO_Discount_Categories_Groups_ID AS [ID],
--     	   a.Lup_AO_Discount_Groups_ID AS [FK ID],
--     	   b.[Description] AS [Discount Category],
--     	   a.Discount_Percentage AS [Disc %],    --[Percentage],
--     	   a.Date_Captured AS [Date],              --[Date Captured],
--             CASE WHEN c.Surname IS NULL and c.FirstName IS NULL
--                      THEN ISNULL(c.Surname,'')
--                  WHEN c.Surname IS NOT NULL and c.FirstName IS NULL
--                      THEN ISNULL(c.Surname,'')
--                  ELSE ISNULL(c.Surname,'') + ', ' + 
--                       LTRIM(ISNULL(c.FirstName,''))
--                  END AS [User],
--             d.Description AS [Active]
-- 	FROM AO_Discount_Categories_Groups a
--         INNER JOIN Lup_AO_Discount_Categories b 
-- 	        ON a.Lup_AO_Discount_Categories_ID = b.Lup_AO_Discount_Categories_ID
-- 		INNER JOIN AW_users c
--             ON a.User_ID = c.AW_Users_ID
--         INNER JOIN Slu_AW_Active d
--             ON a.Slu_AW_Active_ID = d.Slu_AW_Active_ID
-- 	WHERE a.Lup_AO_Discount_Groups_ID = @GroupID AND
--           a.AW_User_Companies_ID = @Company_ID



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------------
--Description   :sp_AO_Get_Discount_Groups
--Purpose       :
--Functionality :Tables: Lup_AO_Discount_Groups
--Parameters    :
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
----------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Get_Discount_Groups
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT Lup_AO_Discount_Groups_ID AS [ID],
		[Description] AS [Discount Group],
		Date_Captured AS [Date],
		[User_ID] AS [User],
		Slu_AW_Active_ID AS [Active]
	FROM Lup_AO_Discount_Groups
	WHERE AW_User_Companies_ID = @Company_ID

-- -- MOD by TB but joins cannot update RS ?
-- 	SELECT a.Lup_AO_Discount_Groups_ID AS [ID],
-- 		a.Description AS [Discount Group],
-- 		a.Date_Captured AS [Date],
--         CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
--                  THEN ISNULL(b.Surname,'')
--              WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
--                  THEN ISNULL(b.Surname,'')
--              ELSE ISNULL(b.Surname,'') + ', ' + 
--                   LTRIM(ISNULL(b.FirstName,''))
--              END AS [User],
--         c.Description AS [Active]
-- 	FROM Lup_AO_Discount_Groups a
-- 		INNER JOIN AW_users b
--             ON a.User_ID = b.AW_Users_ID
--         INNER JOIN dbo.Slu_AW_Active c
--             ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
-- 	WHERE AW_User_Companies_ID = @Company_ID



SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--------------------------------------------------------------------------------
--Description   :sp_AO_Get_Group_Per_Discount_Category
--Purpose       :Returns the group Categories for the selected discount
--Functionality :
--Parameters    :
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
--------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Get_Group_Per_Discount_Category
    (
    	@CategoryID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


	SELECT a.AO_Discount_Categories_Groups_ID AS [ID],
           a.Lup_AO_Discount_Categories_ID AS [FK ID],
           b.[Description] AS [Discount Group],
           a.Discount_Percentage AS [Disc %],
           a.Date_Captured AS [Date],
           a.[User_ID] AS [User ID],
           a.Slu_AW_Active_ID AS [Active]
	FROM AO_Discount_Categories_Groups a
        INNER JOIN Lup_AO_Discount_Groups b
            ON b.Lup_AO_Discount_Groups_ID = a.Lup_AO_Discount_Groups_ID
	WHERE a.Lup_AO_Discount_Categories_ID = @CategoryID AND
          a.AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-----------------------------------------------------------------------------
--Description   :sp_AO_Get_Product_Inventory_Status
--Purpose       :Retrieves Order Qty, Orders Pending & Candidates Pending
--Parameters    :
--Date          :16 JUN 2008
--Authors       :TB
--Mods          :
-----------------------------------------------------------------------------

CREATE          Procedure sp_AO_Get_Product_Inventory_Status
    (
        @ProductID int,
        @OnHand decimal(9, 3) OUTPUT,
        @Reserved decimal(9, 3) OUTPUT,
        @OnOrder decimal(9, 3) OUTPUT,
        @OrdersPending decimal(9, 3) OUTPUT,
        @ShopList decimal(9, 3) OUTPUT,
        @LastSaleDate datetime
    )

AS

SET NOCOUNT ON

    SELECT @OnHand = ( SELECT ISNULL(On_Hand, 0)
                       FROM AP_Products
                       WHERE AP_Products_ID = @ProductID ),

           @Reserved = ( SELECT CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(@ProductID)) ),

           @OnOrder = ( SELECT (ISNULL(SUM(od.Order_Qty), 0) +
                                ISNULL(SUM(od.Back_Order_Qty), 0) -
                                ISNULL(SUM(od.Received_Qty), 0))
                        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 = @ProductID ),

           @OrdersPending = ( SELECT ISNULL(SUM(od.Order_Qty), 0) +
                                     ISNULL(SUM(od.Back_Order_Qty), 0)
                              FROM AO_Order_Details od
                                  INNER JOIN AO_Orders o
                                      ON od.AO_Orders_ID = o.AO_Orders_ID
                              WHERE o.Date_Ordered IS NULL AND
                                    od.AP_Products_ID = @ProductID ),

           @ShopList = ( SELECT ISNULL(SUM(oc.Qty), 0)
                         FROM AO_Order_Candidates oc
                         WHERE oc.AP_Products_ID = @ProductID ),

           @LastSaleDate = ( SELECT Last_Sale_Date
                             FROM AP_Products
                             WHERE AP_Products_ID = @ProductID )




SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description	:sp_AO_Get_SupplierID
--Purpose       :Gets AP_Products_ID from Product_Code
--              :
--Date			:2003/10/13
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Get_SupplierID
	(
		@SupplierNo varchar(10),
        @SupplierID int OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @SupplierID = AO_Suppliers_ID
    FROM AO_Suppliers
    WHERE Supplier_Number = @SupplierNo


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Get_Supplier_Account_Balance
--Purpose       :Retrieve the latest Supplier Account Balance
--              :
--Parameters    :
--Date          :2018/04/23
--Authors       :RL
--Version       :6.4
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Get_Supplier_Account_Balance]
    (
    	@CompanyID int,
        @SupplierID int,
    	@Balance money OUTPUT
    )

AS

SET NOCOUNT ON

    SET @Balance = 0

    SELECT @Balance =  ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
    FROM AO_Transactions
    WHERE AO_Suppliers_ID = @SupplierID AND
          ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
         (Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
          Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
          Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
          Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
          Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description	:sp_AO_Get_Supplier_Activity_Count
--Purpose       :Counts table activity for ONE AO_Suppliers_ID
--Date			:2009/03/15
--Authors		:TB
--MODS          :
--2004.5.6      :28/11/11 - Removed reference to DELETED AP_Products_Variable
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Get_Supplier_Activity_Count
	(
		@SupplierID int,
        @CompanyID int,
        @ActiveTables int OUTPUT,
        @ActiveRows int OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @CNT int


    SET @ActiveTables = 0
    SET @ActiveRows = 0
    SET @CNT = 0


    SELECT @CNT = count(*)
    FROM AO_Enterprise_Ageing_Temp
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_GRV
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Order_Candidates
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Order_Candidates_Temp
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Orders
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Remittances_Temp
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Statement_Details
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Statements
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Supplier_Contracts
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Supplier_Product_Discounts
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Transactions
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AO_Transactions_Log
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0

    SELECT @CNT = count(*)
    FROM AP_Products_Suppliers
    WHERE AO_Suppliers_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0


    SELECT @CNT = count(*)
    FROM AP_Products
    WHERE Default_Supplier_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0


--     SELECT @CNT = count(*)
--     FROM AP_Products_Variable
--     WHERE Default_Supplier_ID = @SupplierID AND
--           AW_User_Companies_ID = @CompanyID
-- 
--     IF @CNT > 0
--         BEGIN
--             SET @ActiveTables = @ActiveTables + 1
--             SET @ActiveRows = @ActiveRows + @CNT
--         END
--     SET @CNT = 0


    SELECT @CNT = count(*)
    FROM Lup_AP_Product_Manufacturers
    WHERE Default_Supplier_ID = @SupplierID AND
          AW_User_Companies_ID = @CompanyID

    IF @CNT > 0
        BEGIN
            SET @ActiveTables = @ActiveTables + 1
            SET @ActiveRows = @ActiveRows + @CNT
        END
    SET @CNT = 0





SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description	:sp_AO_Get_Supplier_Apply_Levy
--Purpose       :Gets Supplier Apply Product Levy Setting From @SupplierID
--              :
--Date			:2013-07-08
--Authors		:RL
--Version		:2004.5.9
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Get_Supplier_Apply_Levy]
	(
        @SupplierID int,
        @Apply_Product_Levy bit OUTPUT
	)
AS

SET NOCOUNT ON

    SELECT @Apply_Product_Levy = AW_YesNo_Apply_Product_Levy
    FROM AO_Suppliers
    WHERE AO_Suppliers_ID = @SupplierID

SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description	:sp_AO_Get_Supplier_Tax_Code
--Purpose       :Gets Supplier Tax Code from @SupplierID
--              :
--Date			:2009/05/10
--Authors		:TB
--Version		:
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Get_Supplier_Tax_Code
	(
        @SupplierID int,
        @TaxCodeID tinyint OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @TaxCodeID = Sys_AW_Tax_Codes_ID
    FROM AO_Suppliers
    WHERE AO_Suppliers_ID = @SupplierID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_AO_Candidates_Temp_Import
--Purpose       :Posts Customer Data Import Transactions
--Parameters    :
--Date          :2003/10/08
--Authors       :TB
--Version       :1.0.0
--Mods          :13/10/03 - Replaced @NetworkID (varchar(20))
--              :           with @RemoteID (AW_Remote_Access_ID)
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Insert_AO_Candidates_Temp_Import
    (
        @ProductID int,
        @OrderItem bit,
        @RemoteID int,
        @SupplierID int,
        @Product varchar(50),
        @ProductCode varchar(20),
        @OnHand decimal(9,3),
        @OrderQty decimal(9,3),
        @Selling money,
        @TradeDiscount money,
        @LastCost money,
        @MSL decimal(9,3),
        @MinQty decimal(9,3),
        @MaxQty decimal(9,3),
        @SL decimal(9,3),
        @OSOrderQty decimal(9,3),
        @PendOrderQty decimal(9,3),
        @Reserved decimal(9,3),
        @LastOrderDate datetime,
        @LastSaleDate datetime,
        @Notes varchar(50),
        @DateCaptured datetime,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    IF @LastOrderDate = '1899/12/31'
        BEGIN
            SET @LastOrderDate = NULL
        END

    IF @LastSaleDate = '1899/12/31'
        BEGIN
            SET @LastSaleDate = NULL
        END

    IF @DateCaptured = '1899/12/31'
        BEGIN
            SET @DateCaptured = NULL
        END


    INSERT AO_Order_Candidates_Temp
        (
            AP_Products_ID,
            Order_Item,
            AW_Remote_Access_ID,
            AO_Suppliers_ID,
            Product_Description,
            Product_Code,
            On_Hand,
            Order_Qty,
            Selling,
            Trade_Discount,
            Last_Cost,
            Min_Stock_Level,
            Max_Order_Qty,
            Min_Order_Qty,
            Service_Level,
            Outstanding_Order_Qty,
            Pending_Order_Qty,
            Job_Reserved,
            Last_Order_Date,
            Last_Sale_Date,
            Notes,
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @ProductID,
            @OrderItem,
            @RemoteID,
            @SupplierID,
            @Product,
            @ProductCode,
            @OnHand,
            @OrderQty,
            @Selling,
            @TradeDiscount,
            @LastCost,
            @MSL,
            @MinQty,
            @MaxQty,
            @SL,
            @OSOrderQty,
            @PendOrderQty,
            @Reserved,
            @LastOrderDate,
            @LastSaleDate,
            @Notes,
            @DateCaptured,
            @UserID,
            @CompanyID
        )



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AO_Insert_AO_Transactions
--Purpose       :Supplier Invoice/Credit Note INSERT from GL Control Accounts
--              :    (not Product-based Purchases GL Account)
--Functionality :1. Inserts a Supplier Invoice/Credit Note into AO_Transactions for
--              :    1.1 Stock Receipts (GRV)
--              :    1.2 Supplier Invoices
--              :2. GL Transaction insert for Purchases, Creditors, VAT, Discounts
--              :3. SPLIT GRV to GL Cost-of-Sales Accounts by Product Type
--              :    using chkUseProductPurchasesGL parameter
--Date          :2002/04/03
--Authors       :TB
--Mods          :19/06/02 - Fixed Sys_AB_Transaction_Types_ID insert into GL Tran
--              :            by setting new var @ABTranTypeID
--              :24/06/02 - Double Entry REQUIRES ALL @Trade_Creditors_GL_Acc_ID
--              :             (Invoice and Credit Note) amounts to be REVERSED
--              :24/07/02 - Added parameter @GLAccountID to enable selecting
--              :           any GL Account in Supplier Invoices
--              :14/08/02 - Removed convert Amounts to NEG for Credit Notes.
--              :           ALL amounts changed to NEG in UI.txtInv_GotFocus
--              :16/08/02 - Insert @GLAccountID into AO_Transactions NEW column
--              :               AB_Accounts_ID
--              :28/10/02 - Added insert MonthID and YearsID to AO_Transactions
--              :29/10/02 - Added DEFAULT to Purchases Control if @GLAccountID = 0
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :08/12/03 - Added NEW @Comment field from Supplier Invoices/Refunds
--              :11/12/03 - Added RETURN @New_Suppliers_Invoice_ID to
--              :           accommodate NEW Supplier Multi-Split Transactions 
--              :13/12/03 - Fixed Supplier Invoicing bug caused by length of
--              :           @Invoice_No below defined as varchar(10) s/b (20)
--              :25/07/04 - Added text in 'Comment' field in Stock Receipts UI
--              :           SaveGReceivedV and SaveGReturnedV to distinguish
--              :           between tran source i.e. Supplier Invoice & GRV Invoice
--              :           and replaced @SupplierName with @GLDescription
--2004.2.5      :14/01/06 - Replaced input parameter DECLARE of currency types
--              :           of DECIMAL(14,6) declarations with type MONEY
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--              :04/10/06 - Added GRV Item Purchases SPLIT by PRODUCT TYPE and
--              :           inserts GL Transactions to GL C.O.S. ACCOUNTS
--2004.3.5      :23/06/07 - Initalise @SupplierRef and @Comment to NULL STRING
--              :           and removed their NULL input parameter initialising 
--              :           If NULL then combined GL Description is NULL
--2004.3.8      :27/04/08 - Added INSERT into new AO_Transactions_Log for transactions
--              :           posted to Accounting Period of LAST SUPPLIERS MONTH-END
--              :           or earlier
--              :30/04/08 - Added Update Suppliers Account Balance !!!!
--              :30/04/08 - Extended TRANSACTION Save_Supplier_Invoice to include
--              :           all the GL inserts
--2004.4.3      :08/02/09 - Modified to Split GRV Stock Receipts from post to GL C.O.S.
--              :           accounts to post to GL INVENTORY accounts by Product Type - RM
--2004.4.8      :06/11/09 - Modified to ONLY insert VAT Control GL entry if VAT <> 0
--2004.5.0      :18/02/11 - Added NORMAL Continuous Inventory posting to INVENTORY GL Account !!!!!!
--              :           Was previously determined by 301 Purchases Control Account setting !!!!!
--2004.5.7 RGL  :2012-10-23 - Posted GRV for levy items to GL as setup on the Ap_Products table
--2004.5.9 RGL  :2013-06-19 - Fixed bug. Rebate and Other discounts not written to adjustment GLs as 
--							  setup in supplier catelog. Adjustments value also added to inventory GL
--V6.2 RGL		:2015-06-03 - Added provision for consignment stock transactions
------------------------------------------------------------------------------
--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 --Transaction
            -------------------------------------------------------
        --> 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
            
   --         --V6.2 RL Only update supplier balance if NOT consignment
   --         IF ((@Transaction_Type = 31) Or (@Transaction_Type = 32))
   -- 		BEGIN     
			--	SELECT @Purchases_GL_Acc_ID = AB_Accounts_ID
   --             FROM AB_Control_Accounts
   --             WHERE Control_Number = 702                -- Consignment Inventory                
			--END            
            -------------------------------------------------------


            -------------------------------------------------------
            -- 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()

            --V6.2 RL Only update supplier balance if NOT consignment
            IF ((@Transaction_Type = 8) Or (@Transaction_Type = 9))
    		BEGIN     
			--> NEW 2004.3.8 - UPDATE Supplier Account Balance
        		UPDATE AO_Suppliers
				SET Account_Balance = Account_Balance + @TotalAmount
				WHERE AO_Suppliers_ID = @Suppliers_ID
			END                

            ---------------------------------------------------------------
            --> 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 
				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
    
			--V6.2 RL Only update supplier balance if NOT consignment
			IF ((@Transaction_Type = 8) Or (@Transaction_Type = 9))
    		BEGIN     
    
            --> 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	--Rebate Discount
    	
            --> 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	--Other Discount

    
                -------------------------------------------------------
                -- NEW 2004.4.3 - SPLIT GRV to GL INVENTORY Accounts by Product Type
                -------------------------------------------------------
                IF @SplitCOSTypes = 1
				BEGIN --@SplitCOSTypes = 1
					---------------------------------------------------------------------
					--> 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 --@SplitCOSTypes = 1
                ELSE
				-------------------------------------------------------
				--> The DEFAULT Purchases/Inventory GL entry behaviour
				-------------------------------------------------------
				BEGIN --@SplitCOSTypes = 0
					--5.9 RGL 2013-06-19 Fixed Adjustment GL entries
					--> INSERT Purchases GL entry
					EXEC sp_AB_Insert_GL_Transactions
									@GLDescription,
									@ABTranTypeID,
            						@Purchases_GL_Acc_ID,
									@Invoice_Date,
									@Invoice_No,
									@MonthsID,
									@YearsID,
									@New_Suppliers_Invoice_ID,
            						@Net_Purchase_Price,
									@UserID,
									@CompanyID
						
					DECLARE GRV_Cursor CURSOR FOR
					(
						SELECT p.GL_Purchases_ID,
							   SUM(d.Net_Amount)
						FROM AO_GRV_Details d
							INNER JOIN AO_GRV h
								ON h.AO_GRV_ID = d.AO_GRV_ID
							INNER JOIN AP_Products p
								ON d.AP_Products_ID = p.AP_Products_ID
						WHERE d.AW_User_Companies_ID = @CompanyID AND
							  d.AO_GRV_ID = @AO_GRV_ID AND
							  p.Slu_AW_YesNo_Levy_Item = 1
						Group by p.GL_Purchases_ID      
					)
    
					OPEN GRV_Cursor
    
					FETCH NEXT FROM GRV_Cursor INTO @GLInventoryID,	@GRVAmount
    
					WHILE @@FETCH_STATUS = 0
					BEGIN
						IF @GLInventoryID = 0
							SET @GLInventoryID = @Purchases_GL_Acc_ID
	                              
							--> INSERT Purchases GL entry
						EXEC sp_AB_Insert_GL_Transactions
									@GLDescription,
									@ABTranTypeID,
									@GLInventoryID,
									@Invoice_Date,
									@Invoice_No,
									@MonthsID,
									@YearsID,
									@New_Suppliers_Invoice_ID,
									@GRVAmount,
									@UserID,
									@CompanyID
   
    
						FETCH NEXT FROM GRV_Cursor INTO @GLInventoryID, @GRVAmount
    
					END
    
					CLOSE GRV_Cursor    
					DEALLOCATE GRV_Cursor
--GRV SET Fix                    	END
				END --@SplitCOSTypes = 0
                -------------------------------------------------------
    
    
            --> 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
       
				--> 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 --((@Transaction_Type = 8) Or (@Transaction_Type = 9))

		    --V6.2 RL Consignment GL entrys
            IF ((@Transaction_Type = 31) Or (@Transaction_Type = 32) Or (@Transaction_Type = 34) )
    		BEGIN     
    		
			--> Set Sys_AB_Transaction_Types_ID for GL Trans
				IF @Transaction_Type = 31         --31 = Supplier Consignment Receipt
					SET @ABTranTypeID = 28        --28 = Accounts Consignment - Invoice
				ELSE                             --32 = Supplier Consignment Return
					SET @ABTranTypeID = 29        --29 = Accounts Consignment - Refund
    		    		
    			SELECT @Purchases_GL_Acc_ID = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 701                -- Consignment Inventory
    		
				--> 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,
						@NetAmount,
						@UserID,
						@CompanyID

				SELECT @Trade_Creditors_GL_Acc_ID = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 702                 -- Consignment Trade Creditors Control
        
            --> 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

				SELECT @VAT_GL_Acc_ID = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = '704'    -- Consignment VAT Control

				--> 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 -- ((@Transaction_Type = 31) Or (@Transaction_Type = 32))
			
			
	END --Transaction

    COMMIT TRAN Save_Supplier_Invoice

RETURN @New_Suppliers_Invoice_ID
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_CRV
--Purpose       :Inserts an Consignment Received and Consignment Returned Voucher
--Functionality :
--Parameters    :
--Date          :2015/03/27
--Authors       :TB
--Version       :6.0.2
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_CRV]
    (
    	@Suppliers_ID int,
    	@AW_Transaction_Type int,
    	@Order_ID int = 0,
    	@DateReceived DateTime ,
    	@DelNoteNo varchar(20)= null,
    	@SupplierRef varchar(20) = null,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@TaxTotal Money = 0,
    	@TotalAmount Money = 0,
    	@Return_AO_GRV_ID	int,
    	@User_ID int,
    	@Company_ID int
    	
    )

AS

SET NOCOUNT ON

    DECLARE @GRV_ID int,
    	    @Date datetime,
    		@Consignment_Inventory_GL	int,
    		@Consignment_Creditors_GL	int,
	   		@MonthID tinyint,
    		@Year int,
    		@YearID int,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @RefNo varchar(20),
            @SupplierName varchar(30),
            @Comment	varchar(50)

    BEGIN
    	
    	IF @AW_Transaction_Type = 32    --Goods Returned Note
    		BEGIN
    			SET @TradeDisc = (isnull(@TradeDisc, 0) * -1)
    			SET @RebateDisc = (isnull(@RebateDisc, 0) * -1)
    			SET @OtherDisc = (isnull(@OtherDisc, 0) * -1)
    			SET @NetAmount = (isnull(@NetAmount, 0) * -1)
    			SET @TaxTotal = (isnull(@TaxTotal, 0) * - 1)
    			SET @TotalAmount = (isnull(@TotalAmount, 0) * -1)
    		END
    									
    	SET @Date = CONVERT(datetime, @DateReceived)
    		    		
   	    BEGIN TRAN Save_CRV			
 
    	INSERT INTO AO_GRV
            (
                AO_Suppliers_ID,
        		Sys_AW_Transaction_Types_ID,
        		AO_Orders_ID,
        		Date_Received,
        		Delivery_Note_Number,
        		Supplier_Reference,
        		Trade_Discount_Total,
        		Rebate_Discount_Total,
        		Other_Discount_Total,
        		Net_Amount,
        		Total_Tax_Amount,
        		Total_Amount,
        		[User_ID],
        		AW_User_Companies_ID,
        		AO_GRV_ID_Consignment
            )
    	VALUES
            (
                @Suppliers_ID,
    			@AW_Transaction_Type,
    			@Order_ID,
    			@Date,
    			@DelNoteNo,
    			@SupplierRef,
    			@TradeDisc ,
    			@RebateDisc ,
    			@OtherDisc ,
    			@NetAmount,
    			@TaxTotal,
    			@TotalAmount,
    			@User_ID,
    			@Company_ID,
    			@Return_AO_GRV_ID
            )
    	
    	SELECT @GRV_ID = SCOPE_IDENTITY() 

		--SELECT @Consignment_Inventory_GL = AB_Accounts_ID
		--FROM AB_Control_Accounts
		--WHERE Control_Number = 701
      
		--SELECT @Consignment_Creditors_GL = AB_Accounts_ID
		--FROM AB_Control_Accounts
		--WHERE Control_Number = 702
            
  --  -------------------------------------------------------------------------------
  --  --> UPDATE SUPPLIER TRANSACTIONS
  --  -------------------------------------------------------------------------------

		--SELECT @SupplierName = LEFT(Supplier_Name, 30)
		--FROM AO_Suppliers
		--WHERE AO_Suppliers_ID = @Suppliers_ID
	
		--IF @AW_Transaction_Type = 31
		--	SET @Comment = 'CRV ' + CONVERT(Varchar(10), @GRV_ID)
		
		--IF @AW_Transaction_Type = 32
		--	SET @Comment = 'CRN ' + CONVERT(Varchar(10), @GRV_ID)
	
		--SET @Narration = LEFT(RTRIM(LTRIM(@SupplierName)), 25) + ' - ' + LEFT(@Comment, 20)

		--SET @MonthID = DATEPART(mm, @Date)
		--SET @Year = DATEPART(yy, @Date)

		--SELECT @YearID = Slu_AW_Years_ID
		--FROM Slu_AW_Years
		--WHERE [Description] = CONVERT(varchar(10), @Year)
	
		--IF @MonthID = 0 OR @YearID = 0
		--BEGIN
		--	SELECT	@MonthID = Slu_AW_Months_ID,
		--			@YearID = Slu_AW_Years_ID
		--	FROM AW_User_Companies
		--	WHERE AW_User_Companies_ID = @Company_ID
		--END

		--BEGIN	
        
  --      -------------------------------------------------------------------------------
  --      --> INSERT a GL Transaction for the SELECTED GL Account
  --      -------------------------------------------------------------------------------
  --  	EXEC sp_AB_Insert_GL_Transactions
  --              @Narration,
  --              15, --@GLTranTypeID, General Journal
  --              @Consignment_Inventory_GL,
  --              @Date,
  --              @RefNo,
  --              @MonthID,
  --              @YearID,
  --              @GRV_ID,
  --              @TotalAmount,
  --              @User_ID,
  --              @Company_ID
    
    
  --      -------------------------------------------------------------------------------
  --      --> Seen from the perspective of the SELECTED GL Account,
  --      -->     reverse the SIGN for the double-entry to the Creditors Control
  --      -------------------------------------------------------------------------------
  --      SET @TotalAmount = -@TotalAmount
  --      -------------------------------------------------------------------------------
    
    
  --      -------------------------------------------------------------------------------
  --      --> INSERT CREDITORS CONTROL
  --      -------------------------------------------------------------------------------
    	
  --      --> INSERT a GL Transaction for the Trade Creditors Control Account
  --      EXEC sp_AB_Insert_GL_Transactions
  --              @Narration,
  --              15, --@GLTranTypeID, General Journal
  --              @Consignment_Creditors_GL,
  --              @Date,
  --              @RefNo,
  --              @MonthID,
  --              @YearID,
  --              @GRV_ID,
  --              @TotalAmount,
  --              @User_ID,
  --              @Company_ID

		--IF @RebateDisc <> 0
		--BEGIN
		
		--	IF @AW_Transaction_Type = 31
		--		SET @Comment = 'CRV Rebate Disc' + CONVERT(Varchar(10), @GRV_ID)
			
		--	IF @AW_Transaction_Type = 32
		--		SET @Comment = 'CRN Rebate Disc' + CONVERT(Varchar(10), @GRV_ID)


		--		--> INSERT a GL Transaction for the Trade Creditors Control Account - Rebate Discount
		--		EXEC sp_AB_Insert_GL_Transactions
		--				@Narration,
		--				15, --@GLTranTypeID, General Journal
		--				@Consignment_Creditors_GL,
		--				@Date,
		--				@RefNo,
		--				@MonthID,
		--				@YearID,
		--				@GRV_ID,
		--				@RebateDisc,
		--				@User_ID,
		--				@Company_ID
		--END

		--IF @OtherDisc <> 0
		--BEGIN
		
		--	IF @AW_Transaction_Type = 31
		--		SET @Comment = 'CRV Rebate Disc' + CONVERT(Varchar(10), @GRV_ID)
			
		--	IF @AW_Transaction_Type = 32
		--		SET @Comment = 'CRN Rebate Disc' + CONVERT(Varchar(10), @GRV_ID)


		--		--> INSERT a GL Transaction for the Trade Creditors Control Account - Other Discount
		--		EXEC sp_AB_Insert_GL_Transactions
		--				@Narration,
		--				15, --@GLTranTypeID, General Journal
		--				@Consignment_Creditors_GL,
		--				@Date,
		--				@RefNo,
		--				@MonthID,
		--				@YearID,
		--				@GRV_ID,
		--				@OtherDisc,
		--				@User_ID,
		--				@Company_ID
		--END

	--END

	COMMIT TRAN Save_CRV
    
	RETURN @GRV_ID
    
    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_CRV_Return
--Purpose       :Inserts a Consignment Returned Voucher Details
--Functionality :
--Parameters    :
--Date          :2002/02/13
--Authors       :TB
--MODS          :14/08/02 - Fixed converting sign of @Unit_Last_Cost to negative
--              :           causing a positive @NetAmount being created
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :05/06/03 - Added calculate and update AVERAGE COST in AP_Products
--2004.3.8      :30/05/08 - Reworked AVERAGE COST calculation BEFORE negative conversions
--2004.4.0      :08/08/08 - Removed setting @New_Average_Cost = 0 if On_Hand now 0
--              :           in NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
--2004.4.5      :03/08/09 - Increased @Qty and @Prev_On_Hand from decimal(9,3) to decimal(12,3)
--              :03/08/09 - Added SET @New_Average_Cost = @Prev_Average_Cost to RETAIN
--              :           PREVIOUS Average_Cost if @New_On_Hand = 0. Because @New_Average_Cost
--              :           was then NEVER SET if @New_On_Hand = 0 this could potentially update
--              :           AP_Products with a NULL Average_Cost value
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--V6.2 RL	2015-11-29	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_CRV_Return]
    (		
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(12,3),
    	@Unit_Last_Cost money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@AO_GRV_Details_ID_Consignment	int,
    	@UserID int,
    	@CompanyID int    	
    )

AS
	
	DECLARE @Prev_On_Hand Decimal(12,3),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
            @Prev_LastCostTotal money,
            @Prev_AvgCostTotal money,
            @New_LastCostTotal money,
            @New_AvgCostTotal money,
            @New_On_Hand Decimal(9,3),
            @COS_Adjust money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @GRNValue money,
            
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
        	@User_Name varchar(40),
        	@AdjustmentType tinyint,
        	@Note varchar(70),
        	@ProductRef varchar(30),
        	@ProdCode varchar(20)

    BEGIN

    --    SET @GRNValue = ISNULL(@Qty, 0) * ISNULL(@Unit_Last_Cost, 0)

        ------------------------------------------------------------------------
        --> NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
        ------------------------------------------------------------------------
    	SELECT --@Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
               --@Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
      		   --@Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   --@Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   --@Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
        	   @ProdCode = ISNULL(Product_Code, '')
    	FROM AP_Products
    	WHERE AP_Products_ID = @AP_Products_ID

		SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @AP_Products_ID) + ')'

        --SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
        --SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

        --SET @New_LastCostTotal = @Prev_LastCostTotal - @GRNValue
        --SET @New_AvgCostTotal = @Prev_AvgCostTotal - @GRNValue


        SET @New_On_Hand = @Prev_On_Hand - @Qty

        --IF @New_On_Hand <> 0
        --    BEGIN
        --        -- Calculate NEW Average_Cost
        --        SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
        --   END
        --ELSE
        --    BEGIN
        --        -- Retain OLD Average_Cost
        --        SET @New_Average_Cost = @Prev_Average_Cost
        --    END
    ------------------------------------------------------------------------


    	SET @Qty = (ISNULL(@Qty, 0) * -1)
    	SET @TradeDisc = (ISNULL(@TradeDisc, 0) * - 1)
    	SET @RebateDisc = (ISNULL(@RebateDisc, 0) * -1)
    	SET @OtherDisc = (ISNULL(@OtherDisc, 0) * -1)
    	SET @NetAmount = (ISNULL(@NetAmount, 0) * -1)
    	SET @TaxAmount = (ISNULL(@TaxAmount, 0) * -1)
    	SET @TotalCost = (ISNULL(@TotalCost, 0) * -1)


		INSERT INTO AO_GRV_Details
            (
                AO_GRV_ID,
                AP_Products_ID,
                Qty,
                Unit_Price,
                Trade_Discount_Amount,	
                Rebate_Discount_Amount,
                Other_Discount_Amount,
                Net_Amount,
                Sys_AW_Tax_Codes_ID,
                Tax_Amount,
                Total_Cost,
                [User_ID],
                AW_User_Companies_ID,
                AO_GRV_Details_ID_Consignment
            )

		VALUES
            (
                @AO_GRV_ID,
                @AP_Products_ID,
                @Qty,
                @Unit_Last_Cost,
                @TradeDisc,
                @RebateDisc,
                @OtherDisc,
                @NetAmount,
                @Tax_Code_ID,
                @TaxAmount,
                @TotalCost,
                @UserID,
                @CompanyID,
                @AO_GRV_Details_ID_Consignment
            )

		UPDATE AO_GRV_Details
		SET Qty_Returned = ISNULL(Qty_Returned,0) + (ISNULL(@Qty, 0) * -1),
			Qty_Left = Qty - ISNULL(Qty_Returned,0) - (ISNULL(@Qty, 0) * -1) - ISNULL(Qty_Sold,0)
		WHERE AO_GRV_Details_ID = @AO_GRV_Details_ID_Consignment

        --> NEW 30/05/08: INCLUDE UPDATE LAST COST
		UPDATE AP_Products 
		SET --Last_Cost = @Unit_Last_Cost,
            --Average_Cost = @New_Average_Cost,
            On_Hand = @New_On_Hand,
            [User_ID] = @UserID  
		WHERE AP_Products_ID = @AP_Products_ID
    
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SELECT @Oppisite_Qty = @Quantity * -1
			
			EXEC sp_AP_Products_Bins_Update_Insert 
			@AP_Products_ID,--@ProductID int,
			1,--@ProductBinID int,
			@Qty,--@Qty decimal(9,3)
			'CRN',--@Source varchar(10),
			0,--@Batch_No
			@UserID,--@UserID int,
			@CompanyID--@CompanyID int			    	
		END	
    
		--Select @Prev_Last_Cost As '@Prev_Last_Cost', @Unit_Last_Cost As '@Unit_Last_Cost'
		
        -- NEW v6.0 RL - Insert details into AP_Inventory_Adjustments table
		--IF @Prev_Last_Cost <> @Unit_Last_Cost
		--	BEGIN
                --> Assign the Adjustment Type
    --            SET @AdjustmentType = 7    --Goods Returned

				--SELECT @User_Name = ISNULL(FirstName, '')
				--FROM AW_Users
				--WHERE AW_Users_ID = @UserID

    --            IF LTRIM(RTRIM(@Note)) = ''
    --                BEGIN
    --                   SET @Note = 'Goods Return Adjustment by '
    --                END

				--SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


    --            --> Stock Reval/Deval Adjustment for Last_Cost changes
    --        	INSERT INTO AP_Inventory_Adjustments
    --                (
    --        			AP_Products_ID,
    --                    Sys_AP_Adjustment_Types_ID,
    --        			Previous_Last_Cost,
    --                    Previous_Average_Cost,
    --        			Previous_On_Hand,
    --        			Previous_Job_Reserved,
    --        			Previous_Sales_Order_Reserved,
    --        			Previous_Quote_Reserved,
    --        			New_Last_Cost,
    --                    New_Average_Cost,
    --        			New_On_Hand,
    --        			New_Job_Reserved,
    --        			New_Sales_Order_Reserved,
    --        			New_Quote_Reserved,
    --        			Note,
    --        			Date_Captured,
    --        			[User_ID],
    --        			AW_User_Companies_ID
    --                )
    --        	VALUES
    --                (
    --                    @AP_Products_ID,
    --                    @AdjustmentType,
    --        			@Prev_Last_Cost,
    --                    @Prev_Average_Cost,
    --        			@Prev_On_Hand ,
    --        		    @Prev_Job_Reserved,
    --        			@Prev_Sales_Order_Reserved,
    --        		    @Prev_Quote_Reserved,
    --        			@Unit_Last_Cost,
    --                    @New_Average_Cost,
    --        			@New_On_Hand,
    --        			@Prev_Job_Reserved ,
    --        			@Prev_Sales_Order_Reserved,
    --        			@Prev_Quote_Reserved,
    --        			@Note,
    --        			getdate(),
    --        			@UserID,
    --        			@CompanyID
    --                )

    --     --   END
    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Discount_Categories_Groups
--Purpose       :Cartesian Product Insert - uses CROSS JOIN
--              :for a newly added Lup_AO_Discount_Categories record into
--              :AO_Discount_Categories_Groups
--Functionality :Tables: Lup_AO_Discount_Groups, Lup_AO_Discount_Categories
--Parameters    :
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE  sp_AO_Insert_Discount_Categories_Groups
    (
        @CategoryOrGroupID smallint,
        @CompanyID int,
        @UserID int,
        @Option bit
    )

AS

SET NOCOUNT ON

    DECLARE @cnt int

    IF @Option = 0    --A LUP_AO_Discount_GROUPS_ID has been inserted
        BEGIN
            SELECT @cnt = COUNT(DISTINCT Lup_AO_Discount_Categories_ID)
            FROM Lup_AO_Discount_Categories
        
            IF @cnt > 0    -- Some Lup_AO_Discount_Categories exist
                BEGIN
                	INSERT AO_Discount_Categories_Groups
                        (
                            Lup_AO_Discount_Categories_ID,
                            Lup_AO_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                        SELECT b.Lup_AO_Discount_Categories_ID,
                               a.Lup_AO_Discount_Groups_ID,
                               0,
                               getdate(),
                               @UserID,
                               @CompanyID,
                               1            -- Enabled
                    FROM Lup_AO_Discount_Groups a
                         CROSS JOIN Lup_AO_Discount_Categories b
                    WHERE a.Lup_AO_Discount_Groups_ID = @CategoryOrGroupID
                END
            ELSE        -- Create at least one Lup_AO_Discount_Categories
                BEGIN
                    INSERT Lup_AO_Discount_Categories
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                        SELECT '<None>',
                               getdate(),
                               @UserID,
                               @CompanyID,
                               1            -- Enabled
        
                    INSERT AO_Discount_Categories_Groups
                        (
                            Lup_AO_Discount_Categories_ID,
                            Lup_AO_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                        SELECT b.Lup_AO_Discount_Categories_ID,
                               a.Lup_AO_Discount_Groups_ID,
                               0,
                               getdate(),
                               @UserID,
                               @CompanyID,
                               1            -- Enabled
                    FROM Lup_AO_Discount_Groups a
                         CROSS JOIN Lup_AO_Discount_Categories b
                    WHERE a.Lup_AO_Discount_Groups_ID = @CategoryOrGroupID
                END       
        END
    ELSE
    IF @Option = 1    --A Lup_AO_Discount_Categories_ID has been inserted
        BEGIN
            SELECT @cnt = COUNT(DISTINCT Lup_AO_Discount_Groups_ID)
            FROM Lup_AO_Discount_Groups
        
            IF @cnt > 0    -- Some Lup_AO_Discount_Groups exist
                BEGIN
                	INSERT AO_Discount_Categories_Groups
                        (
                            Lup_AO_Discount_Categories_ID,
                            Lup_AO_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                        SELECT a.Lup_AO_Discount_Categories_ID,
                               b.Lup_AO_Discount_Groups_ID,
                               0,
                               getdate(),
                               @UserID,
                               @CompanyID,
                               1            -- Enabled
                    FROM Lup_AO_Discount_Categories a
                         CROSS JOIN Lup_AO_Discount_Groups b
                    WHERE a.Lup_AO_Discount_Categories_ID = @CategoryOrGroupID
        
                END
            ELSE        -- Create at least one Lup_AO_Discount_Categories
                BEGIN
                    INSERT Lup_AO_Discount_Groups
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                        SELECT '<None>',
                               getdate(),
                               @UserID,
                               @CompanyID,
                               1            -- Enabled
        
                	INSERT AO_Discount_Categories_Groups    --there were 25
                        (
                            Lup_AO_Discount_Categories_ID,
                            Lup_AO_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                        SELECT a.Lup_AO_Discount_Categories_ID,
                               b.Lup_AO_Discount_Groups_ID,
                               0,
                               getdate(),
                               @UserID,
                               @CompanyID,
                               1            -- Enabled
                    FROM Lup_AO_Discount_Categories a
                         CROSS JOIN Lup_AO_Discount_Groups b
                    WHERE a.Lup_AO_Discount_Categories_ID = @CategoryOrGroupID
        
                END       
        END 

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Discount_Groups
--Purpose       :Inserts a newly added Lup_AO_Discount_Groups record into
--              :Lup_AO_Discount_Groups
--Functionality :Tables: Lup_AO_Discount_Groups
--Parameters    :
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE          PROCEDURE  sp_AO_Insert_Discount_Groups
    (
        @Description varchar(50),
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    INSERT Lup_AO_Discount_Groups
        (
            [Description],
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT @Description,
           getdate(),
           @UserID,
           @CompanyID,
           1            -- Enabled

    RETURN scope_identity()

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






















-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Enterprise_Supplier_Ageing
--Purpose       :INSERT Enterprise Supplier Ageing
--Date          :2008/10/27
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                         PROCEDURE sp_AO_Insert_Enterprise_Supplier_Ageing
	(
        @SourceDB varchar(100),
        @FilterDesc varchar(50),
        @Supplier varchar(50),
        @SuppNo varchar(20),
        @Balance money,
        @Current money,
        @Days30 money,
        @Days60 money,
        @Days90 money,
        @Days120 money,
        @Days150 money,
        @Days180 money
	)

AS

SET NOCOUNT ON

        INSERT AO_Enterprise_Supplier_Ageing
            (
                SourceDB,
                Filter,
                Supplier,
                SuppNo,
                Balance,
                Days0,
                Days30,
                Days60,
                Days90,
                Days120,
                Days150,
                Days180
            )
        VALUES
            (
                @SourceDB,
                @FilterDesc,
                @Supplier,
                @SuppNo,
                @Balance,
                @Current,
                @Days30,
                @Days60,
                @Days90,
                @Days120,
                @Days150,
                @Days180
            )


SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_AO_Insert_First_Supplier
--Purpose       :Inserts an empty Supplier into the Supplier Catalog
--Date          :2008/06/22
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Insert_First_Supplier
    (
        @UserID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

    INSERT AO_Suppliers
        (
            Supplier_Name,
            [User_ID],
            AW_User_Companies_ID
        )

    VALUES
        (
            'Enter Supplier Name',
            @UserID,
            @CompanyID
        )


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_GRV
--Purpose       :Inserts an Goods Received and Goods Returned Voucher
--Functionality :
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--Version       :1.0.0
--MODS          :14/03/05 - Changed input parameter @DelNoteNo size from 10 to 20
--2015.6.2	RL	2015-04-16	:Added @AO_GRV_ID_Consignment parameter for lining Consignment GRV
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_GRV]
    (
    	@Suppliers_ID int,
    	@AW_Transaction_Type int,
    	@Order_ID int = 0,
    	@DateReceived DateTime ,
    	@DelNoteNo varchar(20)= null,
    	@SupplierRef varchar(20) = null,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@TaxTotal Money = 0,
    	@TotalAmount Money = 0,
    	@AO_GRV_ID_Consignment varchar(20),
    	@User_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @GRV_ID int,
    	    @Date datetime

    BEGIN
    	
    	IF @AW_Transaction_Type = 20    --Goods Returned Note
    		BEGIN
    			SET @TradeDisc = (isnull(@TradeDisc, 0) * -1)
    			SET @RebateDisc = (isnull(@RebateDisc, 0) * -1)
    			SET @OtherDisc = (isnull(@OtherDisc, 0) * -1)
    			SET @NetAmount = (isnull(@NetAmount, 0) * -1)
    			SET @TaxTotal = (isnull(@TaxTotal, 0) * - 1)
    			SET @TotalAmount = (isnull(@TotalAmount, 0) * -1)
    		END
    									
    	SET @Date = CONVERT(datetime, @DateReceived)
    				
    	INSERT INTO AO_GRV
            (
                AO_Suppliers_ID,
        		Sys_AW_Transaction_Types_ID,
        		AO_Orders_ID,
        		Date_Received,
        		Delivery_Note_Number,
        		Supplier_Reference,
        		Trade_Discount_Total,
        		Rebate_Discount_Total,
        		Other_Discount_Total,
        		Net_Amount,
        		Total_Tax_Amount,
        		Total_Amount,
        		[User_ID],
        		AW_User_Companies_ID,
        		AO_GRV_ID_Consignment
            )
    	VALUES
            (
                @Suppliers_ID,
    			@AW_Transaction_Type,
    			@Order_ID,
    			@Date,
    			@DelNoteNo,
    			@SupplierRef,
    			@TradeDisc ,
    			@RebateDisc ,
    			@OtherDisc ,
    			@NetAmount,
    			@TaxTotal,
    			@TotalAmount,
    			@User_ID,
    			@Company_ID,
    			@AO_GRV_ID_Consignment
            )
    	
    	SELECT @GRV_ID = SCOPE_IDENTITY() 
    
    	RETURN @GRV_ID
    
    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_GRV_Return
--Purpose       :Inserts a Goods Returned Voucher Details
--Functionality :
--Parameters    :
--Date          :2002/02/13
--Authors       :TB
--MODS          :14/08/02 - Fixed converting sign of @Unit_Last_Cost to negative
--              :           causing a positive @NetAmount being created
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :05/06/03 - Added calculate and update AVERAGE COST in AP_Products
--2004.3.8      :30/05/08 - Reworked AVERAGE COST calculation BEFORE negative conversions
--2004.4.0      :08/08/08 - Removed setting @New_Average_Cost = 0 if On_Hand now 0
--              :           in NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
--2004.4.5      :03/08/09 - Increased @Qty and @Prev_On_Hand from decimal(9,3) to decimal(12,3)
--              :03/08/09 - Added SET @New_Average_Cost = @Prev_Average_Cost to RETAIN
--              :           PREVIOUS Average_Cost if @New_On_Hand = 0. Because @New_Average_Cost
--              :           was then NEVER SET if @New_On_Hand = 0 this could potentially update
--              :           AP_Products with a NULL Average_Cost value
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--V6.2 RL	2016-06-26	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Insert_GRV_Return]
    (		
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(12,3),
    	@Unit_Last_Cost money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@UserID int,
    	@CompanyID int
    )

AS
	
	DECLARE @Prev_On_Hand Decimal(12,3),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
            @Prev_LastCostTotal money,
            @Prev_AvgCostTotal money,
            @New_LastCostTotal money,
            @New_AvgCostTotal money,
            @New_On_Hand Decimal(9,3),
            @COS_Adjust money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @GRNValue money,
            
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
        	@User_Name varchar(40),
        	@AdjustmentType tinyint,
        	@Note varchar(70),
        	@ProductRef varchar(30),
        	@ProdCode varchar(20),
        	@OppositeQty decimal(9,3)

    BEGIN

        SET @GRNValue = ISNULL(@Qty, 0) * ISNULL(@Unit_Last_Cost, 0)

        ------------------------------------------------------------------------
        --> NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
        ------------------------------------------------------------------------
    	SELECT @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
               @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
      		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
        	   @ProdCode = ISNULL(Product_Code, '')
    	FROM AP_Products
    	WHERE AP_Products_ID = @AP_Products_ID

		SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @AP_Products_ID) + ')'

        SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
        SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

        SET @New_LastCostTotal = @Prev_LastCostTotal - @GRNValue
        SET @New_AvgCostTotal = @Prev_AvgCostTotal - @GRNValue


        SET @New_On_Hand = @Prev_On_Hand - @Qty

        IF @New_On_Hand <> 0
            BEGIN
                -- Calculate NEW Average_Cost
                SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
            END
        ELSE
            BEGIN
                -- Retain OLD Average_Cost
                SET @New_Average_Cost = @Prev_Average_Cost
            END
    ------------------------------------------------------------------------


    	SET @Qty = (ISNULL(@Qty, 0) * -1)
    	SET @TradeDisc = (ISNULL(@TradeDisc, 0) * - 1)
    	SET @RebateDisc = (ISNULL(@RebateDisc, 0) * -1)
    	SET @OtherDisc = (ISNULL(@OtherDisc, 0) * -1)
    	SET @NetAmount = (ISNULL(@NetAmount, 0) * -1)
    	SET @TaxAmount = (ISNULL(@TaxAmount, 0) * -1)
    	SET @TotalCost = (ISNULL(@TotalCost, 0) * -1)


		INSERT INTO AO_GRV_Details
            (
                AO_GRV_ID,
                AP_Products_ID,
                Qty,
                Unit_Price,
                Trade_Discount_Amount,	
                Rebate_Discount_Amount,
                Other_Discount_Amount,
                Net_Amount,
                Sys_AW_Tax_Codes_ID,
                Tax_Amount,
                Total_Cost,
                [User_ID],
                AW_User_Companies_ID
            )

		VALUES
            (
                @AO_GRV_ID,
                @AP_Products_ID,
                @Qty,
                @Unit_Last_Cost,
                @TradeDisc,
                @RebateDisc,
                @OtherDisc,
                @NetAmount,
                @Tax_Code_ID,
                @TaxAmount,
                @TotalCost,
                @UserID,
                @CompanyID
            )


        --> NEW 30/05/08: INCLUDE UPDATE LAST COST
		UPDATE AP_Products 
		SET Last_Cost = @Unit_Last_Cost,
            Average_Cost = @New_Average_Cost,
            On_Hand = @New_On_Hand,
            [User_ID] = @UserID  
		WHERE AP_Products_ID = @AP_Products_ID
 
		--Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SET @OppositeQty = @Qty * -1
			EXEC sp_AP_Products_Bins_Update_Insert 
				@AP_Products_ID,	--@ProductID int,
				1,					--@ProductBinID int,
    			@Qty,				--@Qty decimal(9,3)
    			'GRN',				--@Source varchar(10),
    			0,					--@Batch_No
    			@UserID,			--@UserID int,
    			@CompanyID			--@CompanyID int
		END	
    
		--Select @Prev_Last_Cost As '@Prev_Last_Cost', @Unit_Last_Cost As '@Unit_Last_Cost'
		
        -- NEW v6.0 RL - Insert details into AP_Inventory_Adjustments table
		--IF @Prev_Last_Cost <> @Unit_Last_Cost
		--	BEGIN
                --> Assign the Adjustment Type
                SET @AdjustmentType = 7    --Goods Returned

				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID

                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                       SET @Note = 'Goods Return Adjustment by '
                    END

				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID,
        				Lup_AP_Product_Bins_ID            			
                    )
            	VALUES
                    (
                        @AP_Products_ID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    @Prev_Job_Reserved,
            			@Prev_Sales_Order_Reserved,
            		    @Prev_Quote_Reserved,
            			@Unit_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			@Prev_Job_Reserved ,
            			@Prev_Sales_Order_Reserved,
            			@Prev_Quote_Reserved,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID,
            			1 --Defaulted to 1
                    )

         --   END
    
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Multi_Split_GL_Transactions
--Purpose       :Inserts Multi-Split Supplier Transactions 
--Functionality :Updates Allocation Split GL Accounts here
--Date          :2003/12/11
--Authors       :TB
--MODS          :
--2004.5.2      :11/07/11 - Fixed @SupplierName = LEFT(Supplier_Name, 30) !!!!
--2015.6.3 RGL  :2017/09/11 - Added Comment to GL Description
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_Multi_Split_GL_Transactions]
    (
        @AO_Header_ID int,
        @AB_Accounts_ID int,
    	@Tax_Method tinyint,
    	@Amount money,
    	@Tax_Code tinyint,
    	@Tax_Amount money,
    	@Net_Amount money,
    	@Comments varchar(50),
    	@GL_Description varchar(50) = '',
    	@User_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @Description varchar(200),
            @Suppliers_ID int,
            @SupplierName varchar(30),
            @TranType_ID smallint,
            @Ref_No varchar(20),
            @Document_Date datetime,
            @Months_ID tinyint,
            @Years_ID int,
            @ABTranTypeID tinyint
    
	BEGIN TRANSACTION

    --> Get The Supplier TRANSACTION details of this Transaction
		SELECT @Suppliers_ID = AO_Suppliers_ID,
               @TranType_ID = Sys_AW_Transaction_Types_ID,
               @Document_Date = Document_Date,
               @Months_ID = Slu_AW_Months_ID,
               @Years_ID = Slu_AW_Years_ID,
               @Ref_No = Document_Number
		FROM AO_Transactions
		WHERE AO_Transactions_ID = @AO_Header_ID

		SELECT @SupplierName = LEFT(Supplier_Name, 30)
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID = @Suppliers_ID

        SET @Description = RTRIM(LTRIM(@SupplierName)) + ' - ' + RTRIM(LTRIM(@GL_Description)) + ' - ' + RTRIM(LTRIM(ISNULL(@Comments,'')))
        SET @Description = LEFT(@Description, 50)


    --> Set Sys_AB_Transaction_Types_ID for GL Trans
        IF @TranType_ID = 9     --9 = Supplier Refund
            SET @ABTranTypeID = 6        --6 = Accounts Payable - Refund
        ELSE                         --8 = Supplier Invoice
            SET @ABTranTypeID = 5        --5 = Accounts Payable - Invoice


		EXEC sp_AB_Insert_GL_Transactions
                @Description,
                @ABTranTypeID,	
                @AB_Accounts_ID,
                @Document_Date,
                @Ref_No,
                @Months_ID,
                @Years_ID,
                @AO_Header_ID,
                @Net_Amount,
                @User_ID,
                @Company_ID	


	COMMIT TRAN
	

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Multi_Split_Supplier_Transactions
--Purpose       :Inserts a Supplier Invoice/Credit Note from BOTH
--              :Supplier Multi-Split Transactions
--Functionality :Updates GL Trade Creditors and Gl VAT Control here
--Date          :2003/12/11
--Authors       :TB
--Version       :1.0.0
--Mods          :05/07/05 - Fixed Supplier Invoicing bug caused by length of
--2004.2.4      :           @Invoice_No below defined as varchar(10) s/b (20)
--2004.2.5      :14/01/06 - Replaced in DECLARE all amount type DECIMAL(14,6) variable
--              :           declarations with type MONEY !!!!
--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 !!!!
--2004.5.2      :11/07/11 - Fixed @SupplierName = LEFT(Supplier_Name, 30) !!!!
------------------------------------------------------------------------------

CREATE               Procedure sp_AO_Insert_Multi_Split_Supplier_Transactions
    (
    	@Suppliers_ID int,
    	@SupplierRef varchar(20) = null,
    	@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) = null
    )

AS

SET NOCOUNT ON

    DECLARE @Description varchar(50),
            @SupplierName varchar(30),
            @New_Suppliers_Invoice_ID int,
            @Trade_Creditors_GL_Acc_ID int,	
            @Purchases_GL_Acc_ID int,
            @VAT_GL_Acc_ID int,
            @VAT_Contol_Amount money,
            @Trade_Creditors_Amount money,
            @Net_Purchase_Price money,
            @Rebate_Disc_Amount money,
            @Other_Discount_Amount money,
            @ABTranTypeID tinyint,

            --> 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)


    ---------------------------------------------------------------
    --> 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 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

            SELECT @VAT_GL_Acc_ID = AB_Accounts_ID
            FROM AB_Control_Accounts            WHERE Control_Number = 401    -- VAT Control

            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 @SupplierName = LEFT(Supplier_Name, 30)
    		FROM AO_Suppliers 
    		WHERE AO_Suppliers_ID = @Suppliers_ID

            SET @Description = RTRIM(LTRIM(@SupplierName)) + ' - ' + RTRIM(LTRIM(@Comment))
            SET @Description = LEFT(@Description, 50)


			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


    --> 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
                    @Description,
                    @ABTranTypeID,
		            @Trade_Creditors_GL_Acc_ID,
                    @Invoice_Date,        --NEW
                    @Invoice_No,          --NEW
                    @MonthsID,
                    @YearsID,
                    @New_Suppliers_Invoice_ID,
		            @Trade_Creditors_Amount,
                    @UserID,
                    @CompanyID

        --> VAT  Control
            IF @VAT_Contol_Amount <> 0
        		BEGIN
        			EXEC sp_AB_Insert_GL_Transactions
                            @Description,
                            @ABTranTypeID,
        					@VAT_GL_Acc_ID,
                            @Invoice_Date,        --NEW
                            @Invoice_No,          --NEW
                            @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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_OR_Update_CRV_Detail
--Purpose       :Inserts Consignemnt CRV Detail and Updates On_Hand
--Functionality :
--Parameters    :
--Date          :2015/03/27
--Authors       :TB
--Version       :6.0.2
--V6.3	RL		:2017-04-21 :Added check to fill back orders
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_OR_Update_CRV_Detail]
    (	
    	@AO_Order_Details_ID int = 0,
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(9,3),
    	@Unit_Last_Cost money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE @Prev_Last_Cost money,
            @Prev_On_Hand Decimal(9,3),
    		@Prev_Job_Reserved decimal(9,3),
    		@Prev_Sales_Order_Reserved decimal(9,3),
    		@Prev_Quote_Reserved decimal(9,3),
            @New_Last_Cost money,
            @New_On_Hand Decimal(9,3),
    		@Orders_ID Int,
    		@Received_Qty Decimal(19,3),
    		@Count1 int,
    		@Count2 int,
    		@Net_Purchase_Price money,
    		@Note varchar(70),
    		@User_Name varchar(40),
        --> GL variables for Supplier GL Detail
    		@Use_Rebate_Disc_GL_Acc Bit,
    		@Use_Other_Disc_GL_Acc Bit,
    		@Rebate_Disc_GL_Acc int,
    		@Other_Disc_GL_Acc int,
    		@Purchases_Contol_Acc_ID int,
    		@Suppliers_ID int,
			@chkSOAutoReplenishBO_GRV	varchar(10)

    BEGIN
    	BEGIN
    		INSERT INTO AO_GRV_Details
                (
                    AO_GRV_ID,
        			AP_Products_ID,
        			Qty,
        			Unit_Price,
        			Trade_Discount_Amount,	
        			Rebate_Discount_Amount,
        			Other_Discount_Amount,
        			Net_Amount,
        			Sys_AW_Tax_Codes_ID,
        			Tax_Amount,
        			Total_Cost,
        			[User_ID],
        			AW_User_Companies_ID,
        			Qty_Returned,
        			Qty_Sold,
        			Qty_Left
                )
    		VALUES
                (
                    @AO_GRV_ID ,
        			@AP_Products_ID ,
        			@Qty ,
        			@Unit_Last_Cost ,
        			@TradeDisc ,
        			@RebateDisc ,
        			@OtherDisc ,
        			@NetAmount ,
        			@Tax_Code_ID ,
        			@TaxAmount ,
        			@TotalCost ,
        			@UserID ,
        			@CompanyID,
        			0,
        			0,
        			@Qty
                )
    	END
    	
    	BEGIN	
            SELECT @Prev_On_Hand = ISNULL(On_Hand, 0) ,
                   @Prev_Last_Cost = ISNULL(Last_Cost, 0) ,
                   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0) ,
                   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0) ,
                   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0)
    		FROM AP_Products
    		WHERE AP_Products_ID = @AP_Products_ID
    
    		SET @New_On_Hand = @Prev_On_Hand + @Qty    --New On_Hand Qty
      
      
--> CALCULATE NEW LAST COST ----------------------------------------------

            SET @Net_Purchase_Price = ISNULL(@Unit_Last_Cost, 0) * ISNULL(@Qty, 1)
      
		UPDATE AP_Products
        SET On_Hand = @Prev_On_Hand + @Qty,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @AP_Products_ID      
		
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SELECT @Oppisite_Qty = @Quantity * -1
			
			EXEC sp_AP_Products_Bins_Update_Insert 
			@AP_Products_ID,--@ProductID int,
			1,--@ProductBinID int,
			@Qty,--@Qty decimal(9,3)
			'CRV',--@Source varchar(10),
			0,--@Batch_No
			@UserID,--@UserID int,
			@CompanyID--@CompanyID int			    	
		END	
		
      
		END
            
    		--BEGIN
    		--	SELECT @Suppliers_ID = AO_Suppliers_ID
    		--	FROM AO_GRV
    		--	WHERE AO_GRV_ID = @AO_GRV_ID
    		
    		--	SELECT  @Use_Rebate_Disc_GL_Acc = Use_Rebate_Discount_Control_Acc,
    		--			@Use_Other_Disc_GL_Acc = Use_Other_Discount_Control_Acc,
    		--			@Rebate_Disc_GL_Acc = AB_Rebate_Discount_Account_ID,
    		--			@Other_Disc_GL_Acc = AB_Other_Discounts_Account_ID
    		--	FROM AO_Suppliers 
    		--	WHERE AO_Suppliers_ID = @Suppliers_ID
    	
    		--	SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    		--	FROM AB_Control_Accounts
    		--	WHERE Control_Number = 301    --Purchases
    		--END


        --> Update Purchase with Net Acquisition Cost
--            IF @Use_Rebate_Disc_GL_Acc = 1    -- 1 = YES
--				BEGIN
--					IF @Rebate_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
--                        --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
--                        SET @Net_Purchase_Price = @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
--					ELSE
--                        --> Last_Cost = UnitPrice - (Trade)
--                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@TradeDisc, 0)
--				END

--        --> @Use_Rebate_Disc_GL_Acc = 0    -- 0 = NO
--			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
--                SET @Net_Purchase_Price =  @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
    
--			IF @Use_Other_Disc_GL_Acc = 1    -- 1 = YES
--				BEGIN
--					IF @Other_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
--                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)
--				END

--        --> @Use_Other_Disc_GL_Acc = 0    -- 0 = NO
--			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate + Other) = Net Acquisition Cost
--				SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)

--------------------------------------------------------------------------
--        --> New Last_Cost
--            SET @New_Last_Cost = ROUND(@Net_Purchase_Price / ISNULL(@Qty, 1), 2)
--------------------------------------------------------------------------
--        --> Updates Last_Cost & Inventory Adjustment for Reval/Deval

--            SET @Note = 'Consignment Received by '

--			EXEC sp_AP_Update_Inventory_Details
--                    @AO_GRV_ID,
--                    @AP_Products_ID,
--					@New_Last_Cost,
--					@New_On_Hand,
--					@Prev_Job_Reserved,
--					@Prev_Sales_Order_Reserved,
--					@Prev_Quote_Reserved,
--					@Note,
--					@UserID ,
--					@CompanyID
--------------------------------------------------------------------------

    	--END
    	
    	
    	
    	
    	IF @AO_Order_Details_ID <> 0 
    		BEGIN
    
    			SELECT @Received_Qty = ISNULL(Received_Qty,0),
    				@Orders_ID = AO_Orders_ID	
    			FROM AO_Order_Details 
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    			
    			SET @Received_Qty =  @Received_Qty + @Qty			 
    		
    			UPDATE AO_Order_Details
    			SET Receipt_Date = GetDate(),
    				Received_Qty = @Received_Qty
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    
            --> CERTIFY ORDER as COMPLETE if items received in full
    			SELECT @Count1 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE AO_Orders_ID = @Orders_ID
    			
    			SELECT @Count2 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE Received_Qty  >= (Order_Qty + Back_Order_Qty) AND
                      AO_Orders_ID = @Orders_ID
    			
    			IF @Count2 = @Count1
    				BEGIN
    					UPDATE AO_Orders
    					SET Complete = 1 
    					WHERE AO_Orders_ID = @Orders_ID 
    				END
    		END		
			
		SELECT @chkSOAutoReplenishBO_GRV = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkSOAutoReplenishBO_GRV'
		
		IF @chkSOAutoReplenishBO_GRV = '1'
		BEGIN	
    		--V6.3 RL 2017/04/21 Check if sales orders have back orders	
    		EXEC sp_AO_Update_Sales_Orders @AO_GRV_ID, @AP_Products_ID, @New_On_Hand, @CompanyID	
    	END
				
    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_OR_Update_GRV_Detail
--Purpose       :Inserts GRV Detail and Updates Inventory Last_Cost, On_Hand, and
--              :        REVAL/DEVAL Stock Adjustment in sp_AP_Update_Inventory_Details
--Functionality :
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--Version       :1.0.0
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Fixed this: On_Hand was only updated
--                              if @Prev_Last_Cost <> @New_Last_Cost
--              :21/05/02 - Moved the Reval/Deval Adjustment to
--              :               sp_AP_Update_Inventory_Details
--              :04/06/02 - Added text to @Note before sp_AP_Update_Inventory_Details
--              :               is called
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :           and renamed @Current* variables to @Prev*
--              :18/10/03 - Added @GRV_ID as new input parameter to
--              :           sp_AP_Update_Inventory_Details get the GRV
--              :           Delivery_Note_Number as GLTran RefNo
--              :19/10/03 - Added ROUND(@New_Last_Cost, 2)
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.5.8	RL	:2013-02-04 - Changed AO_Order_Details.Received_Qty From Decimal(9,3) to Decimal(19,3)
--							Tirepoint uses the GRVs to invoice out the KM traveled on there call outs 
--V6.2	RL		:2015-04-16	- Returned AO_GRV_Details_ID to be used for Consignment stock tracking
--V6.2	RL		:2015-04-16	:Added @AO_GRV_ID_Consignment parameter for linking Consignment GRV
--V6.2	RL		:2015-12-01	:Product Bin qty changes
--V6.3	RL		:2017-04-21 :Added check to fill back orders
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_OR_Update_GRV_Detail]
    (	
    	@AO_Order_Details_ID int = 0,
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(9,3),
    	@Unit_Last_Cost money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@AO_GRV_Details_ID_Consignment varchar(20),
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE @Prev_Last_Cost money,
            @Prev_On_Hand Decimal(9,3),
    		@Prev_Job_Reserved decimal(9,3),
    		@Prev_Sales_Order_Reserved decimal(9,3),
    		@Prev_Quote_Reserved decimal(9,3),
            @New_Last_Cost money,
            @New_On_Hand Decimal(9,3),
    		@Orders_ID Int,
    		@Received_Qty Decimal(19,3),
    		@Count1 int,
    		@Count2 int,
    		@Net_Purchase_Price money,
    		@Note varchar(70),
    		@User_Name varchar(40),
        --> GL variables for Supplier GL Detail
    		@Use_Rebate_Disc_GL_Acc Bit,
    		@Use_Other_Disc_GL_Acc Bit,
    		@Rebate_Disc_GL_Acc int,
    		@Other_Disc_GL_Acc int,
    		@Purchases_Contol_Acc_ID int,
    		@Suppliers_ID int,
    		@AO_GRV_Details_ID int,
            @ConsignmentStock    decimal(9,3),
    		@IsConsignment	int,
    		
			@ProductsQty				decimal(9,3),			
			@ProductConsignmentStockQty		decimal(9,3),
			@chkSOAutoReplenishBO_GRV	varchar(10)

    BEGIN
    	BEGIN
    		INSERT INTO AO_GRV_Details
                (
                    AO_GRV_ID,
        			AP_Products_ID,
        			Qty,
        			Unit_Price,
        			Trade_Discount_Amount,	
        			Rebate_Discount_Amount,
        			Other_Discount_Amount,
        			Net_Amount,
        			Sys_AW_Tax_Codes_ID,
        			Tax_Amount,
        			Total_Cost,        			
        			[User_ID],
        			AW_User_Companies_ID,
        			AO_GRV_Details_ID_Consignment
                )
    		VALUES
                (
                    @AO_GRV_ID ,
        			@AP_Products_ID ,
        			@Qty ,
        			@Unit_Last_Cost ,
        			@TradeDisc ,
        			@RebateDisc ,
        			@OtherDisc ,
        			@NetAmount ,
        			@Tax_Code_ID ,
        			@TaxAmount ,
        			@TotalCost ,
        			@UserID ,
        			@CompanyID,
        			@AO_GRV_Details_ID_Consignment
                )
    	END
    	    	
    	SELECT @AO_GRV_Details_ID = SCOPE_IDENTITY() 
    	
    	BEGIN	
            SELECT @Prev_On_Hand = ISNULL(On_Hand, 0) ,
                   @Prev_Last_Cost = ISNULL(Last_Cost, 0) ,
                   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0) ,
                   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0) ,
                   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0)
    		FROM AP_Products
    		WHERE AP_Products_ID = @AP_Products_ID

    		--RL V6.2 2016-05-01 Consignment stock must not be added to average cost calculation
    		--Consignment stock is not GRV'd stock
    		--SET @ConsignmentStock = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(@AP_Products_ID),0)
			--SET @Prev_On_Hand = @Prev_On_Hand - @ConsignmentStock

--Insert Into Temp_Debug Values('32 - @Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand)) 
--Insert Into Temp_Debug Values('32 - @Prev_Last_Cost',Convert(Varchar(100),@Prev_Last_Cost)) 

--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@AP_Products_ID)
--Insert Into Temp_Debug Values('(32 Begin)28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
--Insert Into Temp_Debug Values('(32 Begin)28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	

  
    		SET @New_On_Hand = @Prev_On_Hand + @Qty    --New On_Hand Qty
    		
--Insert Into Temp_Debug Values('32 @New_On_Hand',Convert(Varchar(100),@New_On_Hand))
            
    		BEGIN
    			SELECT @Suppliers_ID = AO_Suppliers_ID
    			FROM AO_GRV
    			WHERE AO_GRV_ID = @AO_GRV_ID
    		
    			SELECT  @Use_Rebate_Disc_GL_Acc = Use_Rebate_Discount_Control_Acc,
    					@Use_Other_Disc_GL_Acc = Use_Other_Discount_Control_Acc,
    					@Rebate_Disc_GL_Acc = AB_Rebate_Discount_Account_ID,
    					@Other_Disc_GL_Acc = AB_Other_Discounts_Account_ID
    			FROM AO_Suppliers 
    			WHERE AO_Suppliers_ID = @Suppliers_ID
    	
    			SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    			FROM AB_Control_Accounts
    			WHERE Control_Number = 301    --Purchases
    		END

--> CALCULATE NEW LAST COST ----------------------------------------------

--Insert Into Temp_Debug Values('32 - @Qty',Convert(Varchar(100),ISNULL(@Qty,0)))

            SET @Net_Purchase_Price = ISNULL(@Unit_Last_Cost, 0) * ISNULL(@Qty, 1)

        --> Update Purchase with Net Acquisition Cost
            IF @Use_Rebate_Disc_GL_Acc = 1    -- 1 = YES
				BEGIN
					IF @Rebate_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
                        --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
                        SET @Net_Purchase_Price = @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
					ELSE
                        --> Last_Cost = UnitPrice - (Trade)
                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@TradeDisc, 0)
				END

        --> @Use_Rebate_Disc_GL_Acc = 0    -- 0 = NO
			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
                SET @Net_Purchase_Price =  @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
    
			IF @Use_Other_Disc_GL_Acc = 1    -- 1 = YES
				BEGIN
					IF @Other_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)
				END

        --> @Use_Other_Disc_GL_Acc = 0    -- 0 = NO
			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate + Other) = Net Acquisition Cost
				SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)

------------------------------------------------------------------------
        --> New Last_Cost
            SET @New_Last_Cost = ROUND(@Net_Purchase_Price / ISNULL(@Qty, 1), 2)
------------------------------------------------------------------------
        --> Updates Last_Cost & Inventory Adjustment for Reval/Deval

            SET @Note = 'Goods Received by '
--Insert Into Temp_Debug Values('Cons ID ',Convert(Varchar(100),ISNULL(@AO_GRV_Details_ID_Consignment,0)))

			SET @IsConsignment = 0
			IF EXISTS
			(
				SELECT 1
				FROM AO_GRV
				WHERE AO_GRV_ID = @AO_GRV_ID
				AND SYS_AW_Transaction_Types_ID in (31,32,33,34,35)
			)
			BEGIN
				SET @IsConsignment = 1
			END
--Insert Into Temp_Debug Values('32 @IsConsignment',Convert(Varchar(100),ISNULL(@IsConsignment,0)))			
--Insert Into Temp_Debug Values('32 @New_Last_Cost',Convert(Varchar(100),ISNULL(@New_Last_Cost,0)))			
--Insert Into Temp_Debug Values('32 @New_On_Hand',Convert(Varchar(100),ISNULL(@New_On_Hand,0)))			
			IF @IsConsignment = 1
			BEGIN
				SET @Note = 'Consignment Returned - No Affect On Average Cost!!!!'
			END
			
			EXEC sp_AP_Update_Inventory_Details
                    @AO_GRV_ID,
                    @AP_Products_ID,
					@New_Last_Cost,
					@New_On_Hand,
					@Prev_Job_Reserved,
					@Prev_Sales_Order_Reserved,
					@Prev_Quote_Reserved,
					@Note,
					@UserID ,
					@CompanyID
------------------------------------------------------------------------

    	END
    	
    	IF @AO_Order_Details_ID <> 0 
    		BEGIN
    
    			SELECT @Received_Qty = ISNULL(Received_Qty,0),
    				@Orders_ID = AO_Orders_ID	
    			FROM AO_Order_Details 
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    			
    			SET @Received_Qty =  @Received_Qty + @Qty			 
    		
    			UPDATE AO_Order_Details
    			SET Receipt_Date = GetDate(),
    				Received_Qty = @Received_Qty
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    
            --> CERTIFY ORDER as COMPLETE if items received in full
    			SELECT @Count1 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE AO_Orders_ID = @Orders_ID
    			
    			SELECT @Count2 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE Received_Qty  >= (Order_Qty + Back_Order_Qty) AND
                      AO_Orders_ID = @Orders_ID
    			
    			IF @Count2 = @Count1
    				BEGIN
    					UPDATE AO_Orders
    					SET Complete = 1 
    					WHERE AO_Orders_ID = @Orders_ID 
    				END
    		END	

		SELECT @chkSOAutoReplenishBO_GRV = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkSOAutoReplenishBO_GRV'

--Select @chkSOAutoReplenishBO_GRV As '@chkSOAutoReplenishBO_GRV'	
	
		IF @chkSOAutoReplenishBO_GRV = '1'
		BEGIN	
    		--V6.3 RL 2017/04/21 Check if sales orders have back orders	
    		EXEC sp_AO_Update_Sales_Orders @AO_GRV_ID, @AP_Products_ID, @New_On_Hand, @CompanyID	
    	END
			
    	RETURN @AO_GRV_Details_ID			
    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











--EXEC sp_AO_Insert_OR_Update_Order_Details 0, 7, 1584, 1, 1011, 0, 0, 5,
--                                          1, 0, 0,
--                                          1, 0, 0,
--                                          1, 0, 0,
--                                          5257.2, 1, 736.01, 5993.21, 20, 1
-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_OR_Update_Order_Details
--Purpose       :Insert into Order Details from Supplier Orders
--Date          :2001/12/22
--Authors       :TB
--MODS          :22/09/04 - Increased decimal precision from (6,3) to (9,3) for
--              :           all the *_Qty input parameter fields
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Insert_OR_Update_Order_Details

    (
    	@Order_Detail_ID int = 0,
    	@Order_ID int,
    	@Products_ID int ,
    	@LeadTime Smallint,
    	@Order_Qty decimal(9,3),
    	@Free_Qty decimal(9,3),
    	@BO_Qty decimal(9,3),
    	@Unit_Price money,
    	@Trade_Disc_Formula smallint,
    	@Trade_Disc_Amount money,
    	@Trade_Disc_Perc decimal(19,4),
    	@Rebate_Disc_Formula_ID smallint,
    	@Rebate_Disc_Amount money,
    	@Rebate_Disc_Perc decimal(19,4),
    	@Other_Disc_Formula smallint,
    	@Other_Disc_Amount money,
    	@Other_Disc_Perc decimal(19,4),
    	@Net_Amount money,
    	@Tax_Code_ID int,
    	@Tax_Amount money,
    	@Total_Cost money,
    	@User_ID int,
    	@Company_ID int 
    )

AS

SET NOCOUNT ON

    BEGIN 
    	IF @Order_Detail_ID = 0 
    		BEGIN
    			INSERT INTO AO_Order_Details
                    (
                        AO_Orders_ID, 
                        AP_Products_ID,
                        Lead_Time,
                        Order_Qty,
                        Free_Qty,
                        Back_Order_Qty,
                        Unit_Price,
                        Trade_Discount_Formula_ID,
                        Trade_Discount_Amount,
                        Trade_Discount_Percentage,
                        Rebate_Formula_ID,
                        Rebate_Discount_Amount,
                        Rebate_Discount_Percentage,
                        Other_Discount_Formula_ID,
                        Other_Discount_Amount,
                        Other_Discount_Percentage,
                        Net_Amount,
                        Sys_AW_Tax_Codes_ID,
                        Tax_Amount,
                        Total_Cost,
                        Date_Captured,
                        [User_ID],
                        AW_User_Companies_ID
                    )
    			VALUES
                    (
                        @Order_ID ,
                        @Products_ID  ,
                        @LeadTime ,
                        @Order_Qty ,
                        @Free_Qty ,
                        @BO_Qty ,
                        @Unit_Price ,
                        @Trade_Disc_Formula ,
                        @Trade_Disc_Amount ,
                        @Trade_Disc_Perc,
                        @Rebate_Disc_Formula_ID ,
                        @Rebate_Disc_Amount ,
                        @Rebate_Disc_Perc,
                        @Other_Disc_Formula ,
                        @Other_Disc_Amount ,
                        @Other_Disc_Perc,
                        @Net_Amount ,
                        @Tax_Code_ID ,
                        @Tax_Amount ,
                        @Total_Cost ,
                        GETDATE(),
                        @User_ID ,
                        @Company_ID
                    )
    		END 
    	ELSE 
    	IF @Order_Detail_ID <> 0 
    		BEGIN
    			UPDATE AO_Order_Details
    			SET Lead_Time = @LeadTime,
    				Order_Qty = @Order_Qty,
    				Free_Qty = @Free_Qty,
    				Back_Order_Qty = @BO_Qty,
    				Unit_Price = @Unit_Price,
    				Trade_Discount_Formula_ID = @Trade_Disc_Formula	,
    				Trade_Discount_Amount = @Trade_Disc_Amount,
    				Trade_Discount_Percentage = @Trade_Disc_Perc,
    				Rebate_Formula_ID = @Rebate_Disc_Formula_ID,
    				Rebate_Discount_Amount = @Rebate_Disc_Amount,
    				Rebate_Discount_Percentage = @Rebate_Disc_Perc,
    				Other_Discount_Formula_ID = @Other_Disc_Formula,
    				Other_Discount_Amount = @Other_Disc_Amount,
    				Other_Discount_Percentage = @Other_Disc_Perc,
    				Net_Amount = @Net_Amount,
    				Sys_AW_Tax_Codes_ID = @Tax_Code_ID,
    				Tax_Amount = @Tax_Amount,
    				Total_Cost = @Total_Cost,
    				[User_ID] = @User_ID,
    				AW_User_Companies_ID = @Company_ID
    			WHERE AO_Order_Details_ID = @Order_Detail_ID				
    		END
    END












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_OR_Update_Orders
--Purpose       :Insert a record in orders
--              :If @Existing_Order_ID = 0 then it is a new order and an INSERT will Occur
--Date          :2003/10/10
--Authors       :TB
--Version       :1.0.0
--MODS          :06/11/03 - Replaced Lup_AW_Branch_Codes with AW_Remote_Access
--2004.3.2      :03/09/06 - Added @Del_SendTo input parameter
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Insert_OR_Update_Orders
    (
        @Existing_Order_ID int ,
        @Order_No varchar(20) ,
        @Order_Date datetime,
        @Branch_Codes_ID int,
        @Suppliers_ID int ,
        @Supplier_Rep varchar(30),
        @Supplier_Type varchar(10),
        @Our_Ref varchar(20),
        @Supplier_Ref varchar(20),
        @Trade_Disc money,
        @Rebate_Disc money,
        @Other_Disc money,
        @Net_Amount money,
        @Tax_Total money,
        @Order_Total money,
        @Del_SendTo varchar(40) ,
        @Del_Address1 varchar(40) ,
        @Del_Address2 varchar(40) ,
        @Del_Address3 varchar(40) ,
        @Del_PostCode varchar(10),
        @User_ID int,
        @Company_ID int,
        @Order bit 
    )

AS

    DECLARE	@Orders_ID int,
    	@LastNumber decimal(7,0),
    	@Return int


    ---------------------------------------------------------------------------------------
    --     This Part is executed if the @Existing_Order_ID = 0 (meaning it is a new Order).
    --     I check if the @Order_No = The (last number + 1) used in the Sys_AW_Transaction_Numbers
    --     IF not the same Then use the @Order_No parameter and the Last Number in the AW_Transaction_Types
    --     Table will not be incremented
    ---------------------------------------------------------------------------------------
    BEGIN 
    	IF @Existing_Order_ID = 0
    		BEGIN			
    			INSERT AO_Orders
                    (
                        Order_Number,
                        Order_Date,		
                        AW_Remote_Access_ID,
                        AO_Suppliers_ID,
                        Supplier_Rep,
                        Supplier_Type,
                        Our_Ref,
                        Supplier_Reference,
                        Trade_Discount_Total,
                        Rebate_Discount_Total,
                        Other_Discount_Total,
                        Net_Amount,
                        Tax_Total,
                        Order_Total,
                        Sys_AO_Delivery_Methods_ID,
                        Send_To_Address,
                        Delivery_Addr1,
                        Delivery_Addr2,
                        Delivery_Addr3,
                        Postal_Code,
                        Date_Captured,
                        [User_ID],
                        AW_User_Companies_ID
                    )
    			VALUES
                    (
                        @Order_No,
                        @Order_Date,
                        @Branch_Codes_ID,
                        @Suppliers_ID,
                        @Supplier_Rep,
                        @Supplier_Type,
                        @Our_Ref,
                        @Supplier_Ref,
                        @Trade_Disc,
                        @Rebate_Disc,
                        @Other_Disc,
                        @Net_Amount,
                        @Tax_Total,
                        @Order_Total,
                        3,				-- 3 = Print (Delivery Method)
                        @Del_SendTo,
                        @Del_Address1,
                        @Del_Address2,
                        @Del_Address3,
                        @Del_PostCode,
                        getdate(),
                        @User_ID,
                        @Company_ID
                    )
    		
    			SELECT @Orders_ID =  Scope_Identity() 
    			SET @Return = @Orders_ID
    
    			SELECT @LastNumber = n.Last_Number
				FROM Sys_AW_Transaction_Types t
                    JOIN Sys_AW_Transaction_Numbers n
					    ON n.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
				WHERE t.Sys_AW_Transaction_Types_ID = 14 AND 
					  n.AW_User_Companies_ID = @Company_ID	

    			IF @Order_No = (@LastNumber + 1)
    				BEGIN
    					UPDATE Sys_AW_Transaction_Numbers 
    					SET Last_Number = @Order_No
    					WHERE AW_User_Companies_ID = @Company_ID AND
    						  Sys_AW_Transaction_Types_ID = 14	
    				END
    
    			IF @Order = 1 
    				BEGIN 
    					UPDATE AO_Orders
    					SET Date_Ordered  = getdate()
    					WHERE AO_Orders_ID = @Orders_ID
    				END
    		END 

    ---------------------------------------------------------------------------------------
    --    This Part will update the Orders Table if the order is an existing order
    ---------------------------------------------------------------------------------------
    	ELSE
    	IF @Existing_Order_ID <> 0
    		BEGIN
    			UPDATE 	AO_Orders
    				SET AW_Remote_Access_ID  = @Branch_Codes_ID,
        				Supplier_Rep = @Supplier_Rep,
        				Supplier_Type = @Supplier_Type,
        				Our_Ref = @Our_Ref,
        				Supplier_Reference = @Supplier_Ref,
        				Trade_Discount_Total = @Trade_Disc,
        				Rebate_Discount_Total = @Rebate_Disc,
        				Other_Discount_Total = @Other_Disc,
        				Net_Amount = @Net_Amount,
        				Tax_Total = @Tax_Total,
        				Order_Total = @Order_Total,
                        Send_To_Address = @Del_SendTo,
        				Delivery_Addr1 = @Del_Address1,
        				Delivery_Addr2 = @Del_Address2,
        				Delivery_Addr3 = @Del_Address3,
        				Postal_Code = @Del_PostCode,
        				[User_ID] = @User_ID
    			WHERE AO_Orders_ID = @Existing_Order_ID AND
    				  AO_Suppliers_ID = @Suppliers_ID AND
    				  AW_User_Companies_ID = @Company_ID
    			
    			IF @Order = 1
    				BEGIN
    					UPDATE AO_Orders
    					SET Date_Ordered  = getdate()
    					WHERE AO_Orders_ID = @Existing_Order_ID
    				END
    	
    			SET @Return = @Existing_Order_ID
    		END 
    END

RETURN @Return











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Order_Candidates
--Purpose       :
--Date          :13 JAN 2002
--Authors       :TB
--Version       :1.0.0
--MODS          :13/10/03 - Added @RemoteID input parameter
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Insert_Order_Candidates
    (
        @ProductID int,
        @SuppliersID int = 0,
        @Qty decimal(9,3),
        @Last_Cost money,
        @Notes varchar(50)= null,
        @Reviews int ,
        @Originator int,
        @User_ID int,
        @CompanyID int,
        @RemoteID int
    )
AS

SET NOCOUNT ON


    INSERT AO_Order_Candidates
        (
            AP_Products_ID,
            AO_Suppliers_ID, 
            Qty,
            Last_Cost,
            Notes,
            Reviews,
            Originator,
            AW_Remote_Access_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
        )
    
    VALUES
        (
            @ProductID,
            @SuppliersID,
            @Qty,
            @Last_Cost,
            @Notes,
            @Reviews,
            @Originator,
            @RemoteID,
            Getdate(),
            @User_ID,
            @CompanyID
)


    RETURN @@IDENTITY












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Order_Candidates_Temp
--Purpose       :Inventory Manager temp table
--Date          :27 SEP 2003
--Authors       :TB
--Version       :1.0.0
--MODS          :30/09/03 - Added 'Network_Identity_Number' input parameter
--              :02/10/03 - Added discount formulae
--              :13/10/03 - Replaced Network_Identity_Number with AW_Remote_Access_ID
--2004.3.7      :22/11/07 - Added using Standard_Cost as Unit_Price if 
--              :           chkProcureStdCostPricing parameter = '1'
--              :23/11/07 - Added selecting CURRENT effective Selling Price from AP_Products
--              :           and CALCULATE Discount Percentage using Std/Last cost
--              :24/11/07 - Added Select CURRENT SELLING if @Unit_Price = 0
--2004.4.8      :29/04/10 - Changed ALL Joins in INSERT to LEFT JOIN and commented
--              :           redundant join with AP_Products_Suppliers
--              :29/04/10 - Added validate Date_Orders for NULL value with CASE statement
--              :29/04/10 - Added @ReturnValue
--              :29/04/10 - Fixed DIVIDE BY ZERO error with CASE in Trade_Discount calculation
-------------------------------------------------------------------------------

CREATE                       PROCEDURE sp_AO_Insert_Order_Candidates_Temp
    (
       	@ProductID int,
       	@SupplierID int,
    	@Qty decimal(9,3),
       	@Notes varchar(50),
       	@UserID int,
       	@CompanyID int,
        @RemoteID int
    )

AS

SET NOCOUNT ON

    DECLARE @Unit_Price money,
            @DiscPerc money,
            @UseStdCost varchar(250),
            @ReturnValue int


    SET @ReturnValue = 0

    -------------------------------------------------------
    --> Get Use Product Standard Cost in Procurement Manager Unit Pricing parameter
    -------------------------------------------------------
    SELECT @UseStdCost = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'CheckBox' AND
          Control_Name = 'chkProcureStdCostPricing' AND
          Control_Index = 0 AND
          AW_User_Companies_ID = @CompanyID


    IF @UseStdCost = '1'
        BEGIN
        	SELECT @Unit_Price = ISNULL(Standard_Cost, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @ProductID AND
        		  AW_User_Companies_ID = @CompanyID

            IF @Unit_Price = 0
                BEGIN
                	SELECT @Unit_Price = ISNULL(Last_Cost, 0)
                	FROM AP_Products
                	WHERE AP_Products_ID = @ProductID AND
                		  AW_User_Companies_ID = @CompanyID
                END
        END
    ELSE
        BEGIN
        	SELECT @Unit_Price = ISNULL(Last_Cost, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @ProductID AND
        		  AW_User_Companies_ID = @CompanyID
        END


    IF @Unit_Price = 0
        BEGIN
            SELECT @Unit_Price = ISNULL(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()), 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @ProductID AND
        		  AW_User_Companies_ID = @CompanyID
        END
    -------------------------------------------------------

    BEGIN
        INSERT AO_Order_Candidates_Temp
            (
                AP_Products_ID,
                AO_Suppliers_ID,
                Product_Description,
                Product_Code,
                Order_Item,
                On_Hand,
                Order_Qty,
                Selling,
                Trade_Discount,
                Last_Cost,
                Outstanding_Order_Qty,
                Pending_Order_Qty,
                Last_Order_Date,
                Last_Sale_Date,
                Service_Level,
                Min_Stock_Level,
                Max_Order_Qty,
                Min_Order_Qty,
                Sales_Order_Reserved,
                Job_Reserved,
                Notes,
                AW_Remote_Access_ID,
                [User_ID],
                AW_User_Companies_ID
            )
        SELECT
            @ProductID,
            @SupplierID,
            a.[Description],
            a.Product_Code,
            0,
            ISNULL(a.On_Hand, 0),
            @Qty,
            ISNULL(dbo.GetEffectivePrice(a.Price1_Effective_Date, a.Price1_Price1, a.Price2_Effective_Date, a.Price2_Price1, getdate()), 0),

            CASE WHEN ISNULL(dbo.GetEffectivePrice(a.Price1_Effective_Date, a.Price1_Price1, a.Price2_Effective_Date, a.Price2_Price1, getdate()), 0) <> 0
                 THEN ROUND((ISNULL(dbo.GetEffectivePrice(a.Price1_Effective_Date, a.Price1_Price1, a.Price2_Effective_Date, a.Price2_Price1, getdate()), 0) - ISNULL(@Unit_Price, 0)) / ISNULL(dbo.GetEffectivePrice(a.Price1_Effective_Date, a.Price1_Price1, a.Price2_Effective_Date, a.Price2_Price1, getdate()), 0) * 100, 2)
                 ELSE 0
                 END,

            @Unit_Price,
        --> On Order
            ISNULL((SELECT
                CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                     THEN 0
                     ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                     END
                FROM AO_Order_Details od
                    LEFT 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 = @ProductID), 0),
        --> Pending Orders
            ISNULL((SELECT
                CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                     THEN 0
                     ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty))
                     END
                FROM AO_Order_Details od
                    LEFT JOIN AO_Orders o
                        ON od.AO_Orders_ID = o.AO_Orders_ID
                WHERE o.Date_Ordered IS NULL AND
                      od.AP_Products_ID = @ProductID), 0),
        --> Last Order Date
            (SELECT TOP 1
                CASE WHEN Date_Ordered IS NULL
                     THEN NULL
                     ELSE Date_Ordered
                     END
                FROM AO_Order_Details od
                    LEFT JOIN AO_Orders o
                        ON od.AO_Orders_ID = o.AO_Orders_ID
                WHERE o.Date_Ordered IS NOT NULL AND
                      od.AP_Products_ID = @ProductID
                ORDER BY Date_Ordered DESC),

            a.Last_Sale_Date,
            a.Service_Level,
            ISNULL(a.Min_Stock_Level, 0),
            ISNULL(a.Max_Order_Qty, 0),
            ISNULL(a.Min_Order_Qty, 0),
            ISNULL(a.Sales_Order_Reserved, 0),
            ISNULL(a.Job_Reserved, 0),
            @Notes,
            @RemoteID,
            @UserID,
            @CompanyID
        FROM AP_Products a
            LEFT JOIN AO_Suppliers b
                ON b.AO_Suppliers_ID = @SupplierID
    --      INNER JOIN AP_Products_Suppliers c
    --          ON c.AP_Products_ID = @ProductID AND
    --             c.AO_Suppliers_ID = @SupplierID
        WHERE a.AP_Products_ID = @ProductID AND
              a.AW_User_Companies_ID = @CompanyID



        SELECT @ReturnValue = Scope_Identity()
    END


RETURN @ReturnValue



SET NOCOUNT OFF






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




--------------------------------------------------------------------------------
--Description   :sp_AO_Make_Procurement_Orders_1
--Purpose       :Fetch DISTINCT Node/Supplier to create Procurement Order
--Date          :2003/11/08
--Authors       :TB
--Version       :1.0.0
--MODS		    :
--------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Make_Procurement_Orders_1
    (
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT DISTINCT AW_Remote_Access_ID,
                    AO_Suppliers_ID
    FROM AO_Order_Candidates_Temp
    WHERE AW_User_Companies_ID = @CompanyID AND
          Order_Item = 1
    ORDER BY AW_Remote_Access_ID, AO_Suppliers_ID


SET NOCOUNT OFF




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--------------------------------------------------------------------------------
--Description   :sp_AO_Make_Procurement_Orders_2
--Purpose       :ALTER  Procurement Order for each Node/Supplier
--              :    in AO_Order_Candidates_Temp
--Date          :2003/11/08
--Authors       :TB
--MODS		    :
--2004.5.2      :11/07/11 - Fixed Supplier_Name field length to new size 40 !!!!
--------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Make_Procurement_Orders_2
    (
    	@RemoteAccessID int,
        @SupplierID int,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @OrderCandidatesTempID int,
            @OrderItem bit,
            @DeliveryName varchar(50),
            @DeliveryAddress1 varchar(40),
            @DeliveryAddress2 varchar(40),
            @DeliveryAddress3 varchar(40),
            @DeliveryPost_Code varchar(10),
            @SupplierName varchar(40),
            @OurRef varchar(10),
            @SupplierRef varchar(10),
            @DeliveryMethodsID int,
            @PostBox varchar(20),
            @PostOffice varchar(30),
            @PostCode varchar(10),
            @SupplierFax varchar(12),
            @OrdersURL varchar(100),
            @SupplierTelephone varchar(12),
            @TaxNumber varchar(16),
            @ProductID int,
            @ProductCode varchar(20),
            @ProductDescription varchar(50),
            @ManufacturerCode varchar(20),
            @ManufacturerDescription varchar(50),
            @OrderQty decimal(9,3),
            @Selling money,
            @TradeDiscPerc money,
            @UnitPrice money,
            @TotalCost money,
            @Notes varchar(50),
            @DateCaptured datetime,
            @OriginatorFlag int,
            @SupplierFlag int,
            @TaxRate decimal(5,2),
            @TaxCodeID tinyint,
            @VATAmount money,
            @TradeDiscAmount money,
            @TotalAmount money,
            @TotalVATAmount money,
            @TotalTradeDiscAmount money,
            @OrderAmount money,
            @TotalOrderAmount money,
            @ProcurementDate datetime,
            @LastNumber int,
            @Order_No int,
            @NewOrderID int,
            @ReturnCode int


--> Initialize counters
    SET @ReturnCode = 0            --0 = Unsuccessful
    SET @TotalAmount = 0
    SET @TotalVATAmount = 0
    SET @TotalTradeDiscAmount = 0
    SET @TotalOrderAmount = 0
    SET @NewOrderID = 0
    SET @ProcurementDate = getdate()

--> Initialize the ENTITY CHANGE breakpoint flags
    SET @OriginatorFlag = -1
    SET @SupplierFlag = -1

--> Get the STANDARD VAT rate
    SELECT @TaxRate = Tax_Rate,
           @TaxCodeID = Sys_AW_Tax_Codes_ID
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @TaxRate = 0 OR @TaxRate IS NULL
        SET @TaxRate = 14

    SET @TaxRate = @TaxRate / 100

	BEGIN TRANSACTION

    	DECLARE Procure_Cursor CURSOR FOR
                SELECT
                    a.AO_Order_Candidates_Temp_ID,
                    a.Order_Item,
                    a.AW_Remote_Access_ID,
                    d.Delivery_Name,
                    d.Delivery_Address1,
                    d.Delivery_Address2,
                    d.Delivery_Address3,
                    d.Delivery_Post_Code,
                    a.AO_Suppliers_ID,
                    b.Supplier_Name,
                    b.Supplier_Number, 
                    b.Old_Code, 
                    b.Sys_AO_Delivery_Methods_ID,
                    b.Post_Box,
                    b.Post_Office,
                    b.Post_Code,
                    b.Supplier_Fax,
                    b.Orders_URL,
                    b.Supplier_Telephone,
                    b.Supplier_Fax,
                    b.Tax_Number,
                    a.AP_Products_ID,
                    a.Product_Code,
                    a.Product_Description,
                    c.Manufacturer_Code,
                    c.Manufacturer_Description,
                    a.Order_Qty,
                    a.Selling,
                    a.Trade_Discount,
                    a.Cost,
                    a.Total_Cost,
                    a.Notes,
                    a.Date_Captured,
                    a.[User_ID]
                FROM AO_Order_Candidates_Temp a
                    LEFT JOIN AO_Suppliers b
                        ON a.AO_Suppliers_ID = b.AO_Suppliers_ID
                    LEFT JOIN AP_Products c
                        ON a.AP_Products_ID = c.AP_Products_ID
                    LEFT JOIN AW_Remote_Access d
                        ON a.AW_Remote_Access_ID = d.AW_Remote_Access_ID
                WHERE a.AW_User_Companies_ID = @CompanyID AND
                      a.AW_Remote_Access_ID = @RemoteAccessID AND
                      a.AO_Suppliers_ID = @SupplierID AND
                      a.Order_Item = 1
                ORDER BY a.AW_Remote_Access_ID, a.AO_Suppliers_ID, a.AP_Products_ID
        
    	OPEN Procure_Cursor
    
        	FETCH NEXT FROM Procure_Cursor 
        	INTO
                @OrderCandidatesTempID,
                @OrderItem,
                @RemoteAccessID,
                @DeliveryName,
                @DeliveryAddress1,
                @DeliveryAddress2,
                @DeliveryAddress3,
                @DeliveryPost_Code,
                @SupplierID,
                @SupplierName,
                @OurRef,
                @SupplierRef,
                @DeliveryMethodsID,
                @PostBox,
                @PostOffice,
                @PostCode,
                @SupplierFax,
                @OrdersURL,
                @SupplierTelephone,
                @SupplierFax,
                @TaxNumber,
                @ProductID,
                @ProductCode,
                @ProductDescription,
                @ManufacturerCode,
                @ManufacturerDescription,
                @OrderQty,
                @Selling,
                @TradeDiscPerc,
                @UnitPrice,
                @TotalCost,
                @Notes,
                @DateCaptured,
                @UserID
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
                IF @NewOrderID = 0    ----> Create a NEW ORDER HEADER record
            		BEGIN
            			SELECT @LastNumber = Last_Number
        				FROM Sys_AW_Transaction_Numbers
    					WHERE AW_User_Companies_ID = @CompanyID AND
    						  Sys_AW_Transaction_Types_ID = 14	
    
            			SET @Order_No = (@LastNumber + 1)
    
    					UPDATE Sys_AW_Transaction_Numbers 
    					SET Last_Number = @Order_No
    					WHERE AW_User_Companies_ID = @CompanyID AND
    						  Sys_AW_Transaction_Types_ID = 14	
            
            			INSERT AO_Orders
                            (
                                Order_Number,
                                Order_Date,		
                                AW_Remote_Access_ID,
                                AO_Suppliers_ID,
                                Date_Ordered,
                                Our_Ref,
                                Supplier_Reference,
                                Sys_AO_Delivery_Methods_ID,
                                Send_To_Address,
                                Delivery_Addr1,
                                Delivery_Addr2,
                                Delivery_Addr3,
                                Postal_Code,
                                Date_Captured,
                                [User_ID],
                                AW_User_Companies_ID
                            )
            			VALUES
                            (
                                CONVERT(varchar(20), @Order_No),
                                @ProcurementDate,
                                @RemoteAccessID,
                                @SupplierID,
                                @ProcurementDate,
                                @OurRef,
                                @SupplierRef,
                                @DeliveryMethodsID,
                                @DeliveryName,
                                @DeliveryAddress1,
                                @DeliveryAddress2,
                                @DeliveryAddress3,
                                @DeliveryPost_Code,
                                @ProcurementDate,
                                @UserID,
                                @CompanyID
                            )
    
            			SELECT @NewOrderID = Scope_Identity() 
    
            		END


                SET @VATAmount = ROUND(@TotalCost * @TaxRate, 2)
                SET @TradeDiscAmount = ROUND((@Selling * @OrderQty) - @TotalCost, 2)
                SET @OrderAmount = @TotalCost + @VATAmount

    
    			INSERT INTO AO_Order_Details
                    (
                        AO_Orders_ID, 
                        AP_Products_ID,
                        Order_Qty,
                        Unit_Price,
                        Trade_Discount_Amount,
                        Trade_Discount_Percentage,
                        Net_Amount,
                        Tax_Amount,
                        Total_Cost,
                        Sys_AW_Tax_Codes_ID,
                        Date_Captured,
                        [User_ID],
                        AW_User_Companies_ID
                    )
    			VALUES
                    (
                        @NewOrderID,
                        @ProductID ,
                        @OrderQty,
                        @UnitPrice,
                        @TradeDiscAmount,
                        @TradeDiscPerc,
                        @TotalCost,
                        @VATAmount,
                        @OrderAmount,
                        @TaxCodeID,
                        @ProcurementDate,
                        @UserID,
                        @CompanyID
                    )
    
                SET @TotalAmount = @TotalAmount + @TotalCost
                SET @TotalVATAmount = @TotalVATAmount + @VATAmount
                SET @TotalTradeDiscAmount = @TotalTradeDiscAmount + @TradeDiscAmount
                SET @TotalOrderAmount = @TotalOrderAmount + @OrderAmount

                --> Set the ENTITY CHANGE flags
                SET @OriginatorFlag = @RemoteAccessID
                SET @SupplierFlag = @SupplierID


            	FETCH NEXT FROM Procure_Cursor 
            	INTO
                    @OrderCandidatesTempID,
                    @OrderItem,
                    @RemoteAccessID,
                    @DeliveryName,
                    @DeliveryAddress1,
                    @DeliveryAddress2,
                    @DeliveryAddress3,
                    @DeliveryPost_Code,
                    @SupplierID,
                    @SupplierName,
                    @OurRef,
                    @SupplierRef,
                    @DeliveryMethodsID,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @SupplierFax,
                    @OrdersURL,
                    @SupplierTelephone,
                    @SupplierFax,
                    @TaxNumber,
                    @ProductID,
                    @ProductCode,
                    @ProductDescription,
                    @ManufacturerCode,
                    @ManufacturerDescription,
                    @OrderQty,
                    @Selling,
                    @TradeDiscPerc,
                    @UnitPrice,
                    @TotalCost,
                    @Notes,
                    @DateCaptured,
                    @UserID
    
        	END


    --> Update the ORDER HEADER of the LAST ORDER (not done when cursor exits)
        IF @NewOrderID <> 0            --IF a Order Header has been created
            BEGIN
                UPDATE AO_Orders       --Update its aggregated totals from details
                SET Trade_Discount_Total = @TotalTradeDiscAmount,
                    Net_Amount = @TotalAmount,
                    Tax_Total = @TotalVATAmount,
                    Order_Total = @TotalOrderAmount
                WHERE AO_Orders_ID = @NewOrderID

                SET @TotalAmount = 0
                SET @TotalVATAmount = 0
                SET @TotalTradeDiscAmount = 0
                SET @TotalOrderAmount = 0
            END

    	CLOSE Procure_Cursor
    
    	DEALLOCATE Procure_Cursor


    --> Delete the items
--         DELETE AO_Order_Candidates_Temp
--         WHERE AW_User_Companies_ID = @CompanyID AND
--               AW_Remote_Access_ID = @RemoteAccessID AND
--               AO_Suppliers_ID = @SupplierID AND
--               Order_Item = 1


        SET @ReturnCode = @NewOrderID


    COMMIT TRANSACTION



RETURN @ReturnCode








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Payment_Unallocate
--Purpose       :CURSOR - Reverses Supplier Payment Allocations for a specific Payment
--Functionality :UPDATE AO_Transactions - Reset the SOURCE (Invoice, ORIGINAL) transaction to its pre-payment ALLOCATION state
--				:UPDATE AO_Transactions - Reset the DESTINATION (Payment, ORIGINAL) transaction to its pre-payment ALLOCATION state
--              :UPDATE AO_Suppliers    - Add back the payment to the Suppliers Account Balance
--              :DELETE AO_Transactions_Transactions
--Date          :2016-03-14
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Payment_Unallocate]
    (
        @PaymentTranID int,
    	@UserID int,
        @CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @Linked_AO_Transactions_ID			Int,
			@Payment_Amount						Decimal(18,2),
			@Allocated_Amount					Decimal(18,2),
			@Amount								Decimal(18,2),
			@ReturnCode							Int,
			@AO_Transactions_Transactions_ID	Int,
			@AllocationFound					Int,
			@NEW_PaymentTranID					Int,
			@Transactions_Type_ID				Int,
			@Rev_JRN							Int,
			@Temp_PaymentTranID					Int

	DECLARE @Temp_Table TABLE
	(
		AO_Transactions_Transactions_ID	Int,
		Source_ID						Int,
		Destination_ID					Int,
		Amount							Decimal(18,2)
	)
	
	SELECT @ReturnCode = 0
	SELECT @AllocationFound = 0
	SELECT @Rev_JRN = 0

	--Check if allocated amount is same as payment amount
	SELECT	@Payment_Amount = Payment_Amount,
			@Transactions_Type_ID = Sys_AW_Transaction_Types_ID
	FROM AO_Transactions
	WHERE AO_Transactions_ID = @PaymentTranID


		IF @Payment_Amount < 0
		BEGIN
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0
			)
			BEGIN	
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Source_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0
			
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Destination_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @Temp_PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
			ELSE			
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0
			)
			BEGIN
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Destination_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0
			
				
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Source_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @Temp_PaymentTranID
			END
			ELSE			
			BEGIN
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Destination_AO_Transactions_ID, Source_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
			
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Source_AO_Transactions_ID, Destination_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
		END
		ELSE
		BEGIN
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0
			)
			BEGIN
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Source_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0				
				
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Destination_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @Temp_PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
			ELSE			
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0
			)
			BEGIN
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Destination_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0		
				
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Source_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @Temp_PaymentTranID
			END
			ELSE			
			BEGIN
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Destination_AO_Transactions_ID, Source_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
			
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Source_AO_Transactions_ID, Destination_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
		END		
		IF EXISTS
		(
			SELECT 1
			FROM @Temp_Table
			WHERE Source_ID = 0
		)
		BEGIN
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM @Temp_Table
			WHERE Destination_ID <> @PaymentTranID
			
			SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2
		END
		ELSE
		BEGIN
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM @Temp_Table
		
			SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2		
		END

	IF @ReturnCode = 0
	BEGIN
			DECLARE GetData CURSOR
			FOR
			SELECT AO_Transactions_Transactions_ID, Destination_ID, Amount
			FROM @Temp_Table 

		OPEN GetData

		FETCH NEXT FROM GetData INTO @AO_Transactions_Transactions_ID, @Linked_AO_Transactions_ID, @Amount
		WHILE @@Fetch_Status = 0
		BEGIN
			SELECT @AllocationFound = 1
			SELECT @ReturnCode = 1
			
				IF @Rev_JRN = 1
				BEGIN
					UPDATE AO_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AO_Transactions_ID = @Linked_AO_Transactions_ID			
				END
				ELSE
				BEGIN
					IF @Payment_Amount <> 0
					BEGIN
						UPDATE AO_Transactions
						SET Payment_Amount = Payment_Amount - @Payment_Amount
						WHERE AO_Transactions_ID = @PaymentTranID
						
						SELECT @Payment_Amount = 0
					END

					UPDATE AO_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AO_Transactions_ID = @Linked_AO_Transactions_ID				
				END
			
			DELETE AO_Transactions_Transactions			
			WHERE AO_Transactions_Transactions_ID = @AO_Transactions_Transactions_ID	
		
			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AO_Transactions_ID,0) = 0
				
			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = @Linked_AO_Transactions_ID
			AND ISNULL(Destination_AO_Transactions_ID,0) = 0

			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = 0
			AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID

			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = 0
			AND ISNULL(Destination_AO_Transactions_ID,0) = @Linked_AO_Transactions_ID		
		
		FETCH NEXT FROM GetData INTO @AO_Transactions_Transactions_ID, @Linked_AO_Transactions_ID, @Amount
		END
		CLOSE GetData
		DEALLOCATE GetData
	END

	IF @ReturnCode = 1
	BEGIN
		DELETE AO_Transactions_Transactions
		WHERE ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
	END

--1 Success
--0 Error
--2 Allocation Amount not same as payment Amount
SET NOCOUNT OFF
RETURN @ReturnCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Product_Bin_Consignment_CHK
--Purpose       :Check to see if a GRV or CRV on a product does not push the 
--				 Consignment or Bin into a negative
--Date          :2015-12-01
--Authors       :RL
--Version       :6.2
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Product_Bin_Consignment_CHK]
    (	
    	@AP_Products_ID int,
    	@Qty decimal(9,3),
    	@BinCHK tinyint,
    	@ConsignmentCHK tinyint,
    	@ReturnMsg varchar(8000) Output
    )
AS

SET NOCOUNT ON

	DECLARE @On_Hand Decimal(9,3),
            @Bin_On_Hand Decimal(9,3),
            @Consignment_Stock Decimal(9,3),            
            @Product_Code varchar(20),
            @Product_Description varchar(50),
            @Available_To_Return Decimal(9,3),
            @BinEnabled varchar(10)

	SET @ReturnMsg = ''
	SET @On_Hand = 0
	SET @Bin_On_Hand = 0
	SET @Consignment_Stock = 0
	
	SELECT  @Product_Code = ISNULL(Product_Code,''),
			@Product_Description = ISNULL([Description],''),
			@On_Hand = On_Hand
	FROM AP_Products
	WHERE AP_Products_ID = @AP_Products_ID
	
	IF @BinCHK = 1
	BEGIN
	
		SET @BinEnabled = '0'
		SELECT @BinEnabled = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkEnableProductBins'
		AND Control_Index = 0
	
		IF @BinEnabled = '1'
		BEGIN
			SET @Bin_On_Hand = 0
			
			SELECT @Bin_On_Hand = On_Hand
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @AP_Products_ID
			AND Lup_AP_Product_Bins_ID = 1
			
			IF @Qty > @Bin_On_Hand
			BEGIN  --
				Select @ReturnMsg = @ReturnMsg + 'Product ' + @Product_Code + ' - ' + @Product_Description + ' exceeds default bin quantity of ' + '' + CONVERT(varchar(10),@Bin_On_Hand) + '' + '
'
			END
		END
	END

	IF @ConsignmentCHK = 1
	BEGIN
		SET @Consignment_Stock = 0
		SELECT @Consignment_Stock = dbo.fn_AP_Get_Consignment_Stock_Qty(@AP_Products_ID)

		IF @Consignment_Stock > 0
		BEGIN
	
			SELECT @Available_To_Return = @On_Hand - @Consignment_Stock
			IF @Consignment_Stock <> 0
			BEGIN
				IF @Available_To_Return < @Qty
				BEGIN
					Select @ReturnMsg = @ReturnMsg + 'Product ' + @Product_Code + ' - ' + @Product_Description + ' is atempting to return consignment stock.
On Hand - ' + '' + CONVERT(varchar(10),@On_Hand) + '' + ' Consignment Stock ' + '' + CONVERT(varchar(10),@Consignment_Stock) + '' + ' Available to return ' + '' + CONVERT(varchar(10),@Available_To_Return) + '' + '
'
				END
			END	
		END
	END
	
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE   Procedure sp_AO_Replenishment_Test

AS

SET NOCOUNT ON

    SELECT
        a.AP_Products_ID as [ID],
        a.Description as [Description],
        b.Supplier_Name as [Supplier],
        a.On_Hand as [On Hand],

--> On Order
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                 END
            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 = a.AP_Products_ID) as [On Order],
--> Pending Orders
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty))
                 END
            FROM AO_Order_Details od INNER JOIN AO_Orders o
                ON od.AO_Orders_ID = o.AO_Orders_ID
            WHERE o.Date_Ordered is null AND
                  od.AP_Products_ID = a.AP_Products_ID) AS [Pend/O],
--> Pending Candidates
        (SELECT
            CASE WHEN (SUM(oc.Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(oc.Qty))
                 END
            FROM AO_Order_Candidates oc
            WHERE oc.AP_Products_ID = a.AP_Products_ID) AS [Pend/C],

        a.Min_Order_Qty as [Min],
        a.Max_Order_Qty as [Max],
        a.Job_Reserved + a.Sales_Order_Reserved as [Res],
        c.Notes
        FROM AP_Products a
            INNER JOIN AO_Suppliers b
                ON a.Default_Supplier_ID = b.AO_Suppliers_ID
            INNER JOIN AO_Order_Candidates c
                ON a.AP_Products_ID = c.AP_Products_ID

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Replenishment_Test1
--Purpose       :Get List of Products to ORDER from existing ORDER CANDIDATES
--              :
--Parameters    :
--Date          :2003/09/03
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Replenishment_Test1

AS

SET NOCOUNT ON

    SELECT
        a.AP_Products_ID as [ID],
        a.Description as [Description],
        b.Supplier_Name as [Supplier],
        a.On_Hand as [On Hand],

--> On Order
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                 END
            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 = a.AP_Products_ID) as [On Order],
--> Pending Orders
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty))
                 END
            FROM AO_Order_Details od INNER JOIN AO_Orders o
                ON od.AO_Orders_ID = o.AO_Orders_ID
            WHERE o.Date_Ordered is null AND
                  od.AP_Products_ID = a.AP_Products_ID) AS [Pend/O],
--> Pending Candidates
        (SELECT
            CASE WHEN (SUM(oc.Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(oc.Qty))
                 END
            FROM AO_Order_Candidates oc
            WHERE oc.AP_Products_ID = a.AP_Products_ID) AS [Pend/C],

        a.Min_Order_Qty as [Min],
        a.Max_Order_Qty as [Max],
        a.Job_Reserved + a.Sales_Order_Reserved as [Res],
        c.Notes
        FROM AP_Products a
            INNER JOIN AO_Suppliers b
                ON a.Default_Supplier_ID = b.AO_Suppliers_ID
            INNER JOIN AO_Order_Candidates c
                ON a.AP_Products_ID = c.AP_Products_ID

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








--exec sp_AO_Replenishment_Test2 1, '2003/01/01 00:00:01', '2003/08/01 23:59:59'

-------------------------------------------------------------------------------
--Description   :sp_AO_Replenishment_Test2
--Purpose       :Get List of Products to ORDER from PRODUCTS WITH SALES
--              :
--Parameters    :
--Date          :2003/09/03
--Authors       :TB
--Version       :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Replenishment_Test2
    (
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime
    )
AS

SET NOCOUNT ON

    SELECT
        a.AP_Products_ID as [ID],
        a.Description as [Description],
        b.Supplier_Name as [Supplier],
        ISNULL(a.On_Hand, 0) as [On Hand],

--> On Order
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                 END
            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 = a.AP_Products_ID) as [On Order],
--> Pending Orders
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty))
                 END
            FROM AO_Order_Details od
                INNER JOIN AO_Orders o
                    ON od.AO_Orders_ID = o.AO_Orders_ID
            WHERE o.Date_Ordered is null AND
                  od.AP_Products_ID = a.AP_Products_ID) AS [Pend/O],
--> Pending Candidates
        (SELECT
            CASE WHEN (SUM(oc.Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(oc.Qty))
                 END
            FROM AO_Order_Candidates oc
            WHERE oc.AP_Products_ID = a.AP_Products_ID) AS [Pend/C],

        ISNULL(a.Min_Order_Qty, 0) as [Min],
        ISNULL(a.Max_Order_Qty, 0) as [Max],
        ISNULL(a.Job_Reserved, 0) + ISNULL(a.Sales_Order_Reserved, 0) as [Res]
        FROM AP_Products a
            INNER JOIN AO_Suppliers b
                ON a.Default_Supplier_ID = b.AO_Suppliers_ID
--             INNER JOIN AO_Order_Candidates c
--                 ON a.AP_Products_ID = c.AP_Products_ID
        WHERE a.AW_User_Companies_ID = @CompanyID AND
             (AP_Products_ID in
                (
                    SELECT DISTINCT AP_Products_ID
                    FROM AS_Transaction_Details
                    WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1
                 ) OR
               a.On_Hand <> 0 OR
               a.Min_Stock_Level <> 0 OR
               a.Min_Order_Qty <> 0 OR
               a.Max_Order_Qty <> 0 OR
               dbo.fn_AO_Product_Has_Orders(a.AP_Products_ID) = 1 ) AND
               a.Slu_AW_Active_ID = 1
        ORDER BY [Description]




-----------------------------------------------------

--         SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
--     
--         IF @Option0 = 1    --Has Sales
--             BEGIN
--                 SET @sql = @sql + '   AND AP_Products_ID in '
--                 SET @sql = @sql + '     ( SELECT DISTINCT AP_Products_ID '
--                 SET @sql = @sql + '       FROM AS_Transaction_Details '
--                 SET @sql = @sql + '       WHERE dbo.fn_AS_Product_Has_Sales(' + CONVERT(varchar(10), @CompanyID) + ', ''' + CONVERT(varchar(30), @StartDate) + ''', ''' + CONVERT(varchar(30), @EndDate) + ''') = 1 ) '
--             END
--     
--         IF @Option1 = 1    --Has On_Hand
--             SET @sql = @sql + '    OR p.On_Hand <> 0 '
--     
--         IF @Option2 = 1    --Has Min_Stock_Level <> 0
--             SET @sql = @sql + '    OR p.Min_Stock_Level <> 0 '
--     
--         IF @Option3 = 1    --Has Min_Order_Qty <> 0
--             SET @sql = @sql + '    OR p.Min_Order_Qty <> 0 '
--     
--         IF @Option4 = 1    --Has Max_Order_Qty <> 0
--             SET @sql = @sql + '    OR p.Max_Order_Qty <> 0 '
--     
--         IF @Option5 = 1    --Has_Orders
--             SET @sql = @sql + '    OR dbo.fn_AO_Product_Has_Orders(p.AP_Products_ID) = 1 '
--     
--         IF @Option6 = 1    --IS Active
--             SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '














SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AO_Reverse_Payment
--Purpose       :CURSOR - Reverses a Supplier Payment in Supplier Ledger only
--Functionality :INSERT PAYMENT REVERSAL Transaction in AO Transactions
--              :UPDATE AO_Transactions - Reset the SOURCE (ORIGINAL) transaction to its pre-payment state
--              :UPDATE AO_Suppliers    - Add back the payment to the Suppliers Account Balance
--              :DELETE AO_Transactions_Transactions
--              :DELETE AO_Transaction_Payments
--Date          :2004/12/17
--Authors       :TB
--MODS          :19/12/04 - Added DISTINCT to select only unique rows in Payment_Cursor
--              :           to avoid causing RUNAWAY inserts in GL Transaction reversal
--2004.2.7      :02/04/06 - Reworked to ADD a REVERSAL PAYMENT transaction in AO_Transactions and
--              :           use its AO_Transactions_ID as the reference for the GL Reversal Trans
--              :           Removed redundant input parameters @DocNumber & @TranRefNo
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AO_Reverse_Payment
    (
        @PaymentTranID int,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @SupplierID int,
            @TranTranID int,
            @SourceTranID int,
            @DestinationTranID int,
            @SourceTotal money,
            @SourcePayment money,
            @Allocated money,
            @DateCaptured datetime,
            @To_Be_Paid_Amount money,
            @To_Be_Paid bit,
            @Remit_Balance money,
            @ReturnCode int,

            @GLAccountID int,
            @TranTypeID tinyint,
            @TranRefNo varchar(20),
            @DocNumber varchar(20),
            @DocDate datetime,
            @Month tinyint,
            @Year int,
            @GRVID int,
            @Total_Amount money,
            @Payment_Amount money,
            @Settlement_Disc money,
            @ReversalTranID int


    SET @ReturnCode = 0        -- 0 = FAIL, @ReversalTranID = SUCCEED 


    -----------------------------------------------------------
    BEGIN TRAN Reverse_Payment_Tran
    -----------------------------------------------------------


        BEGIN


        -----------------------------------------------------------
        -- Get TARGET Payment Transaction in AO Transactions
        -----------------------------------------------------------
            SELECT
                @SupplierID = AO_Suppliers_ID,
                @GLAccountID = AB_Accounts_ID,
                @TranTypeID = Sys_AW_Transaction_Types_ID,
                @TranRefNo = Supplier_Reference,
                @DocNumber = Document_Number,
                @DocDate = Document_Date,
                @Month = Slu_AW_Months_ID,
                @Year = Slu_AW_Years_ID,
                @GRVID = AO_GRV_ID,
                @Total_Amount = Total_Amount,
                @Payment_Amount = Payment_Amount,
                @Settlement_Disc = Settlement_Discount
            FROM AO_Transactions
            WHERE AO_Transactions_ID = @PaymentTranID AND
                  AW_User_Companies_ID = @CompanyID


        -----------------------------------------------------------
        -- Inserts Payment REVERSAL Transaction in AO Transactions
        -----------------------------------------------------------

    		INSERT INTO AO_Transactions
    			(	
                    AO_Suppliers_ID,
                    AB_Accounts_ID,
                    Sys_AW_Transaction_Types_ID,
                    Supplier_Reference,
                    Document_Number,
                    Document_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    AO_GRV_ID,
                    Comment,
                    Total_Amount,
                    Payment_Amount,
                    Settlement_Discount,
                    [User_ID],
                    Date_Captured,
                    AW_User_Companies_ID
                )
    		VALUES
                (
                    @SupplierID,
                    @GLAccountID,
                    @TranTypeID,
                    LEFT('REVERSAL of ' + RTRIM(LTRIM(@TranRefNo)), 20),
                    @DocNumber,
                    @DocDate,
                    @Month,
                    @Year,
                    @GRVID,
                    LEFT('REVERSAL of ' + RTRIM(LTRIM(@TranRefNo)), 20),
                   (@Total_Amount * -1),
                   (@Payment_Amount * -1),
                   (@Settlement_Disc * -1),
                    @UserID,
                    getdate(),
                    @CompanyID
                )


    		SELECT @ReversalTranID = Scope_Identity()



        -----------------------------------------------------------
        --> Define a CURSOR for Supplier Payment Tran
        -----------------------------------------------------------
        	DECLARE Payment_Cursor CURSOR FOR
                (
                    SELECT DISTINCT
                            st.AW_User_Companies_ID,
                            t.AO_Suppliers_ID,
                            t.Document_Date,
                            st.AO_Transactions_Transactions_ID,
                            st.Source_AO_Transactions_ID,
                            st.Destination_AO_Transactions_ID,        --[DestinationTranID]
                            (
                               SELECT ISNULL(Total_Amount, 0)
                               FROM AO_Transactions
                               WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID
                            ),
                            (
                               SELECT ISNULL(Payment_Amount, 0)
                               FROM AO_Transactions
                               WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID
                            ),
                            st.Amount,
                            st.Date_Captured
                    FROM AO_Transactions_Transactions st
                        LEFT JOIN AO_Transactions t
                            ON st.Destination_AO_Transactions_ID = t.AO_Transactions_ID
                    WHERE st.AW_User_Companies_ID = @CompanyID AND
                          st.Tran_Ref_No = @TranRefNo AND
                         (st.Tran_Ref_No <> '' OR
                          st.Tran_Ref_No IS NULL)
                )
        
        	OPEN Payment_Cursor
        
            	FETCH NEXT FROM Payment_Cursor 
            	INTO
                    @CompanyID,
                    @SupplierID,
                    @DocDate,
                    @TranTranID,
                    @SourceTranID,
                    @DestinationTranID,
                    @SourceTotal,
                    @SourcePayment,
                    @Allocated,
                    @DateCaptured
            	
            	WHILE @@FETCH_STATUS = 0
            	BEGIN
    
    
                    -----------------------------------------------------------
                    --Reset the SOURCE (ORIGINAL) transaction to its pre-payment state
                    -----------------------------------------------------------
                    UPDATE AO_Transactions
                    SET Payment_Amount = Payment_Amount + @Allocated,
                        To_Be_Paid = 1,
                        To_Be_Paid_Amount = @Allocated,
                        Remittance_Balance = Total_Amount + (Payment_Amount + @Allocated)
                    WHERE AO_Transactions_ID = @SourceTranID
                    -----------------------------------------------------------
    
                    -----------------------------------------------------------
                    --Add back the payment to the Suppliers Account Balance
                    -----------------------------------------------------------
                	UPDATE AO_Suppliers
                    SET Account_Balance = Account_Balance + (@Allocated * -1)
                    WHERE AO_Suppliers_ID = @SupplierID
                    -----------------------------------------------------------
    
    
                	FETCH NEXT FROM Payment_Cursor 
                	INTO
                        @CompanyID,
                        @SupplierID,
                        @DocDate,
                        @TranTranID,
                        @SourceTranID,
                        @DestinationTranID,
                        @SourceTotal,
                        @SourcePayment,
                        @Allocated,
                        @DateCaptured
        
            	END
        	
        	CLOSE Payment_Cursor
        
        	DEALLOCATE Payment_Cursor
    
    
            DELETE
            FROM AO_Transactions_Transactions
            WHERE Tran_Ref_No = @TranRefNo AND
                  AW_User_Companies_ID = @CompanyID
    
    
            DELETE
            FROM AO_Transaction_Payments
            WHERE Tran_Ref_No = @TranRefNo AND
                  AW_User_Companies_ID = @CompanyID
    
    
--             DELETE
--             FROM AO_Transactions
--             WHERE Supplier_Reference = @TranRefNo AND
--                   Document_Number = @DocNumber AND
--                   AW_User_Companies_ID = @CompanyID


            SET @ReturnCode = @ReversalTranID


        END


    -----------------------------------------------------------
    COMMIT TRAN Reverse_Payment_Tran
    -----------------------------------------------------------


    RETURN @ReturnCode



SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AO_Reverse_Payment_Cashbook_TranID
--Purpose       :Select CASHBOOK TranID of Supplier Payment
--Funtionality  :
--Date          :2004/12/17
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Reverse_Payment_Cashbook_TranID
    (
        @TranDocNo varchar(20),
        @PayDate datetime,
        @CompanyID int,
        @CBTranID int OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @CBTranID = AB_Cash_Book_Transactions_ID
    FROM AB_Cash_Book_Transactions
    WHERE Transaction_Date = @PayDate AND
          Reference_No = @TranDocNo AND
          Sys_AB_Transaction_Types_ID = 9 AND
          AW_User_Companies_ID = @CompanyID




SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AO_Reverse_Payment_Component_Count
--Purpose       :Select COUNT of Supplier Payment Source Transactions components
--Funtionality  :
--Date          :2004/12/16
--Authors       :TB
--MODS          :
--V6.2	RL	2015-04-30	:Allow payment to be reveresed even if it has not been allocated.
--						 I can't see why you would not allow this ?????????
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Reverse_Payment_Component_Count]
    (
        @TranRefNo varchar(20),
        @CompanyID int,
        @TranCount int OUTPUT
    )

AS

SET NOCOUNT ON


    --SELECT @TranCount = count(*)

    --FROM AO_Transactions_Transactions st
    --    LEFT JOIN AO_Transactions t
    --        ON st.Destination_AO_Transactions_ID = t.AO_Transactions_ID
    --    LEFT JOIN AO_Suppliers s
    --        ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
    --    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
    --        ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    
    --WHERE st.AW_User_Companies_ID = @CompanyID AND
    --      st.Tran_Ref_No = @TranRefNo AND
    --     (st.Tran_Ref_No <> '' OR
    --      st.Tran_Ref_No IS NULL)

	SELECT @TranCount = 1

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Reverse_Payment_GL_Transactions
--Purpose       :Reverses ALL Supplier Payment GL inserts
--Functionality :ONLY narration and amount of the ORGINAL GL Tran is changed
--Date          :2004/12/17
--Authors       :TB
--MODS          :19/12/04 - Added DISTINCT to select only unique rows in GL_Cursor
--              :           to avoid causing RUNAWAY inserts in GL Transaction reversal
--2004.2.7      :02/04/06 - Reworked to INSERT the new REVERSAL PAYMENT @ReversalTranID
--              :           in AO_Transactions as AB_Transaction_Ref in the GL Reversal Trans
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AO_Reverse_Payment_GL_Transactions
    (
        @PaymentID int,
        @ReversalTranID int,
        @TranRefNo varchar(20),
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Description varchar(50),
            @Narration varchar(50),
            @TranTypeID tinyint,
            @GLAccountID int,
            @GLTranDate datetime,
            @SourceRef varchar(20),
            @MonthID int,
            @YearID int,
            @SourceTranID int,
            @Amount money,
            @ReverseAmount money,
            @ReturnCode int


    SET @ReturnCode = 0        -- 0 = FAIL, 1 = SUCCEED 


    -----------------------------------------------------------
    BEGIN TRAN GL_Tran
    -----------------------------------------------------------


        BEGIN

            -----------------------------------------------------------
            --> Define a CURSOR for Supplier Payment GL Transactions
            -----------------------------------------------------------
            -- NB NB: DISTINCT in SELECT below is VITAL otherwise
            --        RUNAWAY GL Transaction inserts are made to DB
            -----------------------------------------------------------
        	DECLARE GL_Cursor CURSOR FOR
                (
                    SELECT DISTINCT
                                Description,
                                Sys_AB_Transaction_Types_ID,
                                AB_Accounts_ID,
                                AB_Transaction_Date,
                                AB_Source_Ref,
                                Slu_AW_Months_ID,
                                Slu_AW_Years_ID,
                                AB_Transaction_Ref,
                                AB_Transaction_Amount
                    FROM AB_GL_Transactions
                    WHERE AB_Source_Ref = @TranRefNo AND
                          AB_Transaction_Ref = @PaymentID AND
                          AW_User_Companies_ID = @CompanyID
                )
        
        	OPEN GL_Cursor
        
            	FETCH NEXT FROM GL_Cursor 
            	INTO
                    @Description,
                    @TranTypeID,
                    @GLAccountID,
                    @GLTranDate,
                    @SourceRef,
                    @MonthID,
                    @YearID,
                    @SourceTranID,
                    @Amount
            	
            	WHILE @@FETCH_STATUS = 0
            	BEGIN
    
    
                    SET @ReverseAmount = -@Amount

                    SET @Narration = 'REVERSAL: Ref No ' + ISNULL(@SourceRef, '') + ' - ' + ISNULL(@Description, '')
                    SET @Narration = LEFT(@Narration, 50)


                	INSERT INTO AB_GL_Transactions
                        (
                            [Description],
                			Sys_AB_Transaction_Types_ID,
                			AB_Accounts_ID,
                			AB_Transaction_Date,
                            AB_Source_Ref,
                			Slu_AW_Months_ID,
                			Slu_AW_Years_ID,
                			AB_Transaction_Ref,
                			AB_Transaction_Amount,
                			[User_ID],
                			AW_User_Companies_ID
                        )
                	VALUES
                        (
                            @Narration,
                			@TranTypeID,
                			@GLAccountID,
                			@GLTranDate,
                            @SourceRef,
                			@MonthID,
                			@YearID,
--                			@SourceTranID,
                			@ReversalTranID,
                			@ReverseAmount,
                			@UserID,
                			@CompanyID
                        )


                	UPDATE AB_Accounts 
                	SET AB_Account_Balance = ISNULL(AB_Account_Balance, 0) + ISNULL(@ReverseAmount, 0)
                	WHERE AB_Accounts_ID = @GLAccountID


                	FETCH NEXT FROM GL_Cursor 
                	INTO
                        @Description,
                        @TranTypeID,
                        @GLAccountID,
                        @GLTranDate,
                        @SourceRef,
                        @MonthID,
                        @YearID,
                        @SourceTranID,
                        @Amount
        
            	END
        	
        	CLOSE GL_Cursor
        
        	DEALLOCATE GL_Cursor


            SET @ReturnCode = 1


        END


    -----------------------------------------------------------
    COMMIT TRAN GL_Tran
    -----------------------------------------------------------


    RETURN @ReturnCode










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AO_Sales_Order_Filled_CHK
--Purpose       :Check if GRV will replinish Sales Order Back Order
--Returns       :
--Date          :2017-05-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Sales_Order_Filled_CHK]
	(
		@AP_ProductsID int,
		@Qty decimal(9,3),
        @CompanyID int,
		@Sales_Order_Filled tinyint OUTPUT
	)
AS

	SET @Sales_Order_Filled = 0
	
	IF EXISTS
	(
		SELECT 1
		FROM AS_Transactions h
			INNER JOIN AS_Transaction_Details d
				ON h.AS_Transactions_ID = d.AS_Transactions_ID
		WHERE d.AP_Products_ID = @AP_ProductsID
		AND h.AW_User_Companies_ID = @CompanyID
		AND h.Slu_AW_Active_ID = 1
		AND d.Back_Order <> 0
		AND h.Sys_AW_Transaction_Types_ID = 16
	)
	BEGIN
		SET @Sales_Order_Filled = 1
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Branch_Codes
--Purpose       :Returns a lup of all the suppliers in Order_Candidates 
--Date          :2002/01/17
--Authors       :TB
--Version       :1.0.0
--MODS          :06/11/03 - Replaced Lup_AW_Branch_Codes with AW_Remote_Access
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Branch_Codes
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

--     SELECT Lup_AW_Branch_Codes_ID AS [Branch_Codes_ID],
--     	[Description] AS [BranchCodes]
--     FROM Lup_AW_Branch_Codes
--     WHERE AW_User_Companies_ID = @Company_ID

    SELECT AW_Remote_Access_ID AS [Branch_Codes_ID],
           NodeName AS [BranchCodes]
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @Company_ID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AO_Select_CRV
--Functionality :Consingment Receipts  
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--MODS			:08/09/04 - Removed GRV History Search date conversion to float
--2004.4.5      :30/05/09 - Added field [GRV No] to display in Stock Receipts History
--V6.3	RL		:2017/09/19 :Added Order By Date_Received descending
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_CRV]
    (
    	@Option tinyint,
    	@CompanyID int,
    	@FromDate datetime = NULL,
    	@ToDate datetime = NULL ,
    	@SupplierID int = NULL
    )

AS

SET NOCOUNT ON

BEGIN

	IF @Option = 0        -- 0 = All CRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [CRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE Sys_AW_Transaction_Types_ID = 31 AND  --31 = CRV
              AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received Desc

	ELSE
	IF @Option = 1        -- 1 = Only Uninvoiced GRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [CRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE  Sys_AW_Transaction_Types_ID = 31 AND  --19 = GRV
			AO_GRV_ID NOT IN
                       (SELECT AO_GRV_ID
                        FROM AO_Purchase_Transactions) AND
			AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received Desc

	IF @Option = 2        -- 2 = CRV History
		SELECT AO_GRV_ID AS [ID],
			AO_Suppliers_ID AS [SupplierID],
			AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [CRV No],
			Date_Received AS [Date Received],
			Delivery_Note_Number AS [Delivery Note],
			Supplier_Reference AS [Supplier Reference],
			Trade_Discount_Total AS [Trade Disc],
			Rebate_Discount_Total AS [Rebate Disc],
			Other_Discount_Total AS [Other Disc],
			Net_Amount AS [Net Amount],
			Total_Tax_Amount AS [Tax Total],
			Total_Amount AS [Total]
		FROM AO_GRV
        WHERE Date_Received >= @FromDate AND
              Date_Received <= @ToDate AND
              AO_Suppliers_ID = @SupplierID AND
              AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID IN (31,32)
		ORDER BY Date_Received Desc


END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AO_Select_CRV_Details
--Functionality :Returns CRV details for one CRV 
--Parameters    :
--Date          :2015-04-14
--Authors       :RL
--Version       :6.2
--MODS			:
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_CRV_Details]
    (
    	@GRV_ID int ,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        a.AO_GRV_Details_ID AS [ID],
        a.AO_GRV_ID AS [FK ID],
        a.AP_Products_ID AS [ProductsID],
        p.[Description] AS [Product],
        p.Product_Code AS [Code],
        a.Qty AS [Qty],
		a.Qty_Returned AS [Qty Returned],
		a.Qty_Sold AS [Qty Sold],	
		a.Qty_Left AS [Qty Left],	       
        a.Unit_Price AS [Unit Price],
        a.Trade_Discount_Amount AS [Trade Disc],
        a.Rebate_Discount_Amount AS [Rebate Disc],
        a.Other_Discount_Amount AS [Other Disc],
        a.Net_Amount AS [Net Amount],
        a.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        tc.[Description] AS [Tax Code],
        a.Tax_Amount AS [Tax Amount],
        a.Total_Cost AS [Total Cost]
    FROM AO_GRV_Details a
        LEFT JOIN AP_Products p
            ON a.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
    WHERE a.AO_GRV_ID = @GRV_ID AND
          a.AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Candidates_Product_Count
--Purpose       :Counts Products in AO_Order_Candidates
--Date          :2003/10/01
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Candidates_Product_Count
    (
        @CompanyID int,
        @Products int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Products = COUNT(DISTINCT AO_Order_Candidates_ID)
    FROM AO_Order_Candidates
    WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Candidates_Supplier_Count
--Purpose       :Counts suppliers in AO_Order_Candidates
--Date          :2003/09/28
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Candidates_Supplier_Count
    (
        @CompanyID int,
        @Suppliers int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Suppliers = COUNT(DISTINCT AO_Suppliers_ID)
    FROM AO_Order_Candidates
    WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Candidates_Temp_Product_Count
--Purpose       :Counts Products in AO_Order_Candidates_Temp
--Date          :2003/10/01
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Candidates_Temp_Product_Count
    (
        @CompanyID int,
        @Products int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Products = COUNT(DISTINCT AO_Order_Candidates_Temp_ID)
    FROM AO_Order_Candidates_Temp
    WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Candidates_Temp_Supplier_Count
--Purpose       :Counts suppliers in AO_Order_Candidates_Temp
--Date          :2003/09/28
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Candidates_Temp_Supplier_Count
    (
        @CompanyID int,
        @Suppliers int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Suppliers = COUNT(DISTINCT AO_Suppliers_ID)
    FROM AO_Order_Candidates_Temp
    WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Company_Details_For_PO
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/03/25
--Authors       :TB
--Version       :1.0.0
--              :10/10/03 - Modified input parameter names
--              :27/09/04 - Added selective Billing Delivery Addresses from Remote Access
--              :           or Company Catalog dependant upon value of Remote Access
--              :           Billing_Name or Delivery_Name value
--2004.3.2      :03/09/06 - Added [Del Name] and [Del PostCode] fields
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AO_Select_Company_Details_For_PO
    (
        @UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @RemoteAccessID int,
    		@Billing_Name varchar(50),
    		@Billing_Address1 varchar(40),
    		@Billing_Address2 varchar(40),
    		@Billing_Address3 varchar(40),
    		@Billing_Post_Code varchar(10),
    		@Billing_TelNo varchar(16),
    		@Billing_FaxNo varchar(16),
    		@Billing_VATNo varchar(16),
    		@Billing_RegNo varchar(16),
    		@Delivery_Name varchar(50),
    		@Delivery_Address1 varchar(40),
    		@Delivery_Address2 varchar(40),
    		@Delivery_Address3 varchar(40),
    		@Delivery_Post_Code varchar(10)


    SELECT TOP 1 @RemoteAccessID = ISNULL(AW_Remote_Access_ID, 0)
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          Default_Connection = 1


    SELECT @Billing_Name = ISNULL(Billing_Name, ''),
           @Billing_Address1 = ISNULL(Billing_Address1, ''),
           @Billing_Address2 = ISNULL(Billing_Address2, ''),
           @Billing_Address3 = ISNULL(Billing_Address3, ''),
           @Billing_Post_Code = ISNULL(Billing_Post_Code, ''),
           @Billing_TelNo = ISNULL(Billing_TelNo, ''),
           @Billing_FaxNo = ISNULL(Billing_FaxNo, ''),
           @Billing_VATNo = ISNULL(Billing_VATNo, ''),
           @Billing_RegNo = ISNULL(Billing_RegNo, ''),
           @Delivery_Name = ISNULL(Delivery_Name, ''),
           @Delivery_Address1 = ISNULL(Delivery_Address1, ''),
           @Delivery_Address2 = ISNULL(Delivery_Address2, ''),
           @Delivery_Address3 = ISNULL(Delivery_Address3, ''),
           @Delivery_Post_Code = ISNULL(Delivery_Post_Code, '')
    FROM AW_Remote_Access
    WHERE AW_Remote_Access_ID = @RemoteAccessID


	SELECT
        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_Name
             ELSE a.Company_Trading_Name
        END AS [Company],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_Address1
             ELSE a.Company_Addr1
        END AS [Address1],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_Address2
             ELSE a.Company_Addr2
        END AS [Address2],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_Address3
             ELSE a.Company_City
        END AS [City],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_Post_Code
             ELSE a.Company_Post_Code
        END	AS [Post Code],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_TelNo
             ELSE a.Tel_No
        END AS [Tel No],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_FaxNo
             ELSE a.Fax_No
        END AS [Fax No],

        CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
             THEN @Billing_VATNo
             ELSE a.TAX_Number
        END AS [Tax Number],

        ISNULL(a.E_Mail, '') AS [E Mail],
        ISNULL(b.[Description], '') AS [Country],

        CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
             THEN @Delivery_Name
             ELSE a.Company_Trading_Name
        END AS [Del Name],

        CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
             THEN @Delivery_Address1
             ELSE a.Delivery_Addr1
        END AS [Del Address1],

        CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
             THEN @Delivery_Address2
             ELSE a.Delivery_Addr2
        END AS [Del Address2],

        CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
             THEN @Delivery_Address3
             ELSE a.Delivery_Addr3
        END AS [Del Address3],

        CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
             THEN @Delivery_Post_Code
             ELSE a.Company_Post_Code
        END	AS [Del PostCode],

        ISNULL(FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
	FROM AW_User_Companies a
        LEFT JOIN Slu_AW_Countries b
		    ON a.Slu_AW_Countries_ID = b.Slu_AW_Countries_ID
        LEFT JOIN AW_Users u
            ON u.AW_Users_ID = @UserID
	WHERE a.AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF
	









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Default_Settlement_Discount
--Purpose       :Selects Default Supplier Settlement Discount Percentage
--Date          :2003/12/16
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Select_Default_Settlement_Discount
    (
        @SupplierID int,
        @SettDiscPerc decimal(7, 2) OUTPUT
    )

AS

SET NOCOUNT ON

        SELECT @SettDiscPerc = ISNULL(Default_Settlement_Discount, 0)
        FROM AO_Suppliers
        WHERE AO_Suppliers_ID = @SupplierID


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




--------------------------------------------------------------------------
--Description   :sp_AO_Select_Delivery_Methods
--Purpose       :Returns a lup of all the Delivery methods
--Functionality :
--Parameters    :	
--Date          :2002/01/21
--Authors       :TB 
--Version       :1.0.0
--------------------------------------------------------------------------

CREATE            Procedure sp_AO_Select_Delivery_Methods

AS

SELECT Sys_AW_Delivery_Methods_ID AS [ID],
	[Description] AS [Delivery Method] 
FROM Sys_AW_Delivery_Methods




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Discount_Categories_As_PickList
--Purpose       :
--Functionality :Tables: Lup_AO_Discount_Categories
--Parameters    :
--Date          :2002/02/07
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Select_Discount_Categories_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AO_Discount_Categories_ID AS [ID],
          [Description] as [Discount Category] 
	FROM Lup_AO_Discount_Categories
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Discount_Groups_As_PickList
--Purpose       :
--Functionality :Tables: Lup_AO_Discount_Groups
--Parameters    :
--Date          :2003/10/03
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Discount_Groups_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AO_Discount_Groups_ID AS [ID],
		   [Description] as [Discount Groups] 
	FROM Lup_AO_Discount_Groups
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















--sp_AO_Select_Enterprise_Supplier_Ageing 1
-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Enterprise_Supplier_Ageing
--Purpose       :FILTER Enterprise Supplier Age Analysis
--Date          :2008/10/27
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AO_Select_Enterprise_Supplier_Ageing
	(
        @Sort tinyint
	)
   
AS

SET NOCOUNT ON

	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AO_Enterprise_Ageing_Temp '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Supplier_Number] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Supplier_Name] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--exec sp_AO_Select_Export_Order_Candidates_Temp 1

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Export_Order_Candidates_Temp
--Purpose       :Select Order Candidates Temp to export
--Date          :2003/10/07
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AO_Select_Export_Order_Candidates_Temp
    (
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT
        a.AP_Products_ID AS [ProductID],
        a.Order_Item AS [Order],
        ISNULL(b.Supplier_Name, '') AS [Supplier],
        ISNULL(b.Supplier_Number, '') AS [Supplier No],
        ISNULL(a.Product_Description, '') AS [Product],
        ISNULL(a.Product_Code, '') AS [Code],
        ISNULL(a.On_Hand, 0) AS [On Hand],
        ISNULL(a.Order_Qty, 0) AS [To Order],
        ISNULL(a.Selling, 0) AS [Selling],
        ISNULL(a.Trade_Discount, 0) AS [Disc %],
        ISNULL(a.Cost, 0) AS [Cost],
        ISNULL(a.Last_Cost, 0) AS [Last Cost],
        ISNULL(a.Total_Cost, 0) AS [Total Cost],
        ISNULL(a.Min_Stock_Level, 0) AS [MSL],
        ISNULL(a.Min_Order_Qty, 0) AS [Min],
        ISNULL(a.Max_Order_Qty, 0) AS [Max],
        ISNULL(a.Service_Level, 0) AS [SL],
        ISNULL(a.Outstanding_Order_Qty, 0) AS [O/S Ords],
        ISNULL(a.Pending_Order_Qty, 0) AS [Pend Ords],
        ISNULL(a.Sales_Order_Reserved, 0) + ISNULL(a.Job_Reserved, 0) AS [Res],
        ISNULL(CONVERT(CHAR(10), a.Last_Order_Date, 121), '') AS [Last Order],
        ISNULL(CONVERT(CHAR(10), a.Last_Sale_Date, 121), '') AS [Last Sale],
        ISNULL(a.Notes, '') AS [Notes],
        a.Date_Captured AS [Captured]
    FROM AO_Order_Candidates_Temp a
        LEFT JOIN AO_Suppliers b
            ON a.AO_Suppliers_ID = b.AO_Suppliers_ID
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          a.Order_Item = 1
    ORDER BY b.Supplier_Name, ISNULL(a.Product_Description, '')




SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Filtered_Products
--Purpose       :Stock Receipts Product Search
--Date          :2002/04/16
--Authors       :TB
--Mods          :16/05/02 - Removed top 100 in SELECT
--              :18/04/02 - A Single Criteria search did not include
--              :           a search on Product_Code
--              :28/04/02 - Fixed @Criteria3, @criteria2, @criteria1 filters
--              :07/07/03 - Added filter to EXCLUDE all Non-Stock items
--              :06/03/05 - Added FETCH only ACTIVE products
--              :14/05/05 - Added [Purchases Account] for Product-Assigned GL Accounts
--2004.3.7      :22/11/07 - Added [Std. Cost], [Std. Disc1], [Std. Disc2] using
--              :           Standard Cost as default purchase price
--2004.4.8      :28/03/10 - Added WILDCARD Pattern Matching using _ (underscore) character
--              :           in Normal Search (@SearchType = 0) for the 3 @Filter(n)
--              :03/08/10 - Fixed to EXCLUDE NON-ACTIVE products bypassed by WILDCARD Pattern Matching
--        ****  :02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section and reworked script
--        ****  :02/09/10 - REMOVED WILDCARD search
--RL			:2013-07-15 - Added Alternate_Code1, Alternate_Code2 and Keyword to search fields
--V6.0	RL		:2014-10-28 - Reworked Job, Quote Reserved
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Filtered_Products]
    (
       @CompanyID int,
       @FilterType int = -1,
       @FilterValue int = -1,
       @Criteria1 varchar(50) = '',
       @Criteria2 varchar(50) = '',
       @Criteria3 varchar(50) = ''
    )

AS

SET NOCOUNT ON


    DECLARE @Criteria varchar(4000), 
            @SQL varchar(8000),
            @Wildcard varchar(50),
            @wc1 varchar(50),
            @wc2 varchar(50)



    SET @Criteria = ''
    SET @Wildcard = ''
    SET @wc1 = ''
    SET @wc2 = ''

--     --> WILDCARD Pattern Matching using _ (underscore) character
--     IF LTRIM(RTRIM(@Criteria1)) <> '' AND ISNUMERIC(@Criteria1) > 0
--         BEGIN
--             SET @wc1 = REPLACE(LTRIM(RTRIM(@Criteria1)), '/', '')
--             SET @wc2 = REPLACE(@wc1, '-', '')
--             IF LEN(@wc2) >= 5 AND ISNUMERIC(LEFT(@wc2, 3)) > 0
--                 BEGIN
--                     SET @Wildcard = 
--                         CASE LEN(@wc2)
--                              WHEN 5 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2)
--                              WHEN 6 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 1)
--                              WHEN 7 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '_' + RIGHT(@wc2, 2)
--                              WHEN 8 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '__' + RIGHT(@wc2, 2)
--                         END    
--                     SET @Wildcard = '''%' + @Wildcard + '%'''
--                 END
--         END

    SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + 
                    ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 ' +        --> EXCLUDE Non-Stock items (07/07/03)
                    ' AND p.Slu_AW_Active_ID = 1 '                     --> INCLUDE only ACTIVE products (06/03/05)

    IF @Criteria3 <> ''
        BEGIN
            SET @Criteria3 = '''%' +  @Criteria3 + '%'''
        END

    IF @Criteria2 <> ''
        BEGIN
            SET @Criteria2 = '''%' +  @Criteria2 + '%'''
        END

    IF @Criteria1 <> ''
        BEGIN
            SET @Criteria1 = '''%' +  @Criteria1 + '%'''
        END


    IF @Criteria3 <> ''
        BEGIN
            SET @Criteria = @Criteria +
                            ' AND ((p.Description Like ' + @Criteria3 + ' and p.Description Like ' + @Criteria2 + ' and p.Description Like ' + @Criteria1 + ') OR
                                  (p.Product_Code Like ' + @Criteria3 + ' and p.Product_Code Like ' + @Criteria2 + ' and p.Product_Code Like ' + @Criteria1 + ' ) OR
                                  
                                  (p.Alternate_Code1 Like ' + @Criteria3 + ' and p.Alternate_Code1 Like ' + @Criteria2 + ' and p.Alternate_Code1 Like ' + @Criteria1 + ' ) OR
                                  (p.Alternate_Code2 Like ' + @Criteria3 + ' and p.Alternate_Code2 Like ' + @Criteria2 + ' and p.Alternate_Code2 Like ' + @Criteria1 + ' ) OR
                                  (p.Keywords Like ' + @Criteria3 + ' and p.Keywords Like ' + @Criteria2 + ' and p.Keywords Like ' + @Criteria1 + ' )) '
                                  
        END
    ELSE
    IF @Criteria2 <> ''
        BEGIN
            SET @Criteria = @Criteria +
                            ' AND ((p.Description Like ' + @Criteria2 + ' and p.Description Like ' + @Criteria1 + ') OR
                                  (p.Product_Code Like ' + @Criteria2 + ' and p.Product_Code Like ' + @Criteria1 + ' ) OR
                                  
                                  (p.Alternate_Code1 Like ' + @Criteria2 + ' and p.Alternate_Code1 Like ' + @Criteria1 + ' ) OR
                                  (p.Alternate_Code2 Like ' + @Criteria2 + ' and p.Alternate_Code2 Like ' + @Criteria1 + ' ) OR
                                  (p.Keywords Like ' + @Criteria2 + ' and p.Keywords Like ' + @Criteria1 + ' )) '
        END
    ELSE
    IF @Criteria1 <> ''        --02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section
        BEGIN
--             IF @Wildcard <> ''
--                 BEGIN
--                     SET @Criteria = @Criteria + ' AND (p.Description Like ' + @Criteria1 + ' OR p.Product_Code Like ' + @Criteria1 + ' OR p.Description Like ' + @Wildcard + ' OR p.Product_Code Like ' + @Wildcard + ' )'
--                 END
--             ELSE
--                 BEGIN
                    SET @Criteria = @Criteria + ' AND ((p.Description Like ' + @Criteria1 + ' OR p.Product_Code Like ' + @Criteria1 + ' OR
													p.Alternate_Code1 Like ' + @Criteria1 + ' OR p.Alternate_Code2 Like ' + @Criteria1 + ' Or
													p.Keywords Like ' + @Criteria1 + '))'
--                 END
        END


    SET @SQL = ' SELECT '
    SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
    SET @SQL = @SQL + ' p.Description, '
    SET @SQL = @SQL + ' p.Product_Code AS [Code], '
    SET @SQL = @SQL + ' p.On_Hand AS [Qty on Hand], '

    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) AS [Price 1], '
    SET @SQL = @SQL + ' p.Standard_Cost AS [Std. Cost], '
    SET @SQL = @SQL + ' p.Standard_Disc1 AS [Std. Disc1], '
    SET @SQL = @SQL + ' p.Standard_Disc2 AS [Std. Disc2], '
    SET @SQL = @SQL + ' p.Last_Cost AS [Last Cost], '
    SET @SQL = @SQL + ' p.Average_Cost AS [Avg Cost], ' 

    SET @SQL = @SQL + ' dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost) AS [GP %], '
    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()) AS [Price 2], '
    SET @SQL = @SQL + ' p.Pack_Size AS [Qty], '
    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) AS [Price], '
    SET @SQL = @SQL + ' p.Print_Description AS [Print], ' 
    SET @SQL = @SQL + ' p.SKU_Code AS [Other Code], ' 
    SET @SQL = @SQL + ' p.Measure, ' 
    SET @SQL = @SQL + ' uof.Description AS [Unit], ' 
    SET @SQL = @SQL + ' p.Manufacturer_Code AS [Manuf Code], ' 
    SET @SQL = @SQL + ' p.Manufacturer_Description AS [Manuf Description], ' 
    SET @SQL = @SQL + ' pt.Description AS [ProductType], ' 
    SET @SQL = @SQL + ' pg.Description AS [Group], ' 
    SET @SQL = @SQL + ' pd.Description AS Department, ' 
    SET @SQL = @SQL + ' pl.Description AS Location, ' 
    SET @SQL = @SQL + ' p.Alternate_Code1 AS [Alt Code1], ' 
    SET @SQL = @SQL + ' p.Alternate_Code2 AS [Alt Code2], ' 
    SET @SQL = @SQL + ' p.Supercession, ' 
    SET @SQL = @SQL + ' p.Pack_Volume AS [Pack Volume], ' 
    SET @SQL = @SQL + ' mc.Description AS [Mass Code], ' 
    SET @SQL = @SQL + ' p.Pack_Mass AS [Pack Mass], ' 
    SET @SQL = @SQL + ' p.Strength, ' 
    SET @SQL = @SQL + ' p.Min_Stock_Level AS [Min Stock Level], ' 
    SET @SQL = @SQL + ' p.Last_Sale_Date AS [Last Sale Date], ' 
    SET @SQL = @SQL + ' p.Service_Level AS [Service Level], ' 
    SET @SQL = @SQL + ' p.Max_Order_Qty AS [Max Order Qty], ' 
    SET @SQL = @SQL + ' p.Min_Order_Qty AS [Min Order Qty], ' 
    SET @SQL = @SQL + ' p.Serial_Number AS [Serial No], ' 
    SET @SQL = @SQL + ' p.Sys_AW_Tax_Codes_ID AS [Tax_Code_ID], '
    SET @SQL = @SQL + ' CONVERT(decimal(18, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) AS [Job Reserved], '
    SET @SQL = @SQL + ' CONVERT(decimal(18, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) AS [Quote Reserved], '
    SET @SQL = @SQL + ' p.Date_Captured AS [Date], ' 
    SET @SQL = @SQL + ' p.User_ID AS [UserID], ' 
    SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID] '

    SET @SQL = @SQL + ' FROM AP_Products p '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Mass_Codes mc            ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Locations pl     ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Departments pd   ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Types pt         ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Groups pg        ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Slu_AP_Units_Of_Measure uof     ON p.Slu_AP_Units_Of_Measure_ID = uof.Slu_AP_Units_Of_Measure_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Manufacturers pm ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '


    SET @SQL = @SQL + @Criteria


 	IF @FilterType = 1    --> Suppliers
        SET @SQL = @SQL + ' AND p.AP_Products_ID in (SELECT AP_Products_ID FROM AP_Products_Suppliers WHERE AO_Suppliers_ID = ' + Convert(Varchar(10), @FilterValue) + ') '
	ELSE 
	IF @FilterType = 2    --> Manufacturer
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Manufacturers_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 3    --> Type
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Types_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 4    --> Group
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Groups_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 5    --> Department
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Departments_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 6    --> Location
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Locations_ID = ' + Convert(Varchar(10), @FilterValue) 


    EXEC (@SQL)
    --Select @SQL

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Select_FirstLast_Transaction_Date
--Purpose       :Select FIRST or LAST Supplier Transaction Date
--Date          :2007/02/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Select_FirstLast_Transaction_Date
	(
    	@CompanyID int,
        @Option tinyint,
        @TranDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @Year varchar(4),
            @Month varchar(2),
            @Day varchar(2),
            @Hour varchar(2),
            @Minute varchar(2),
            @Second varchar(2),
            @Date varchar(10),
            @Time varchar(8),
            @DateCaptured datetime,
            @FullDateTime varchar(30)


--> Get the FIRST Supplier Transaction Date
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 @TranDate = Document_Date,
                         @DateCaptured = Date_Captured
            FROM AO_Transactions
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Document_Date ASC
        END

    ELSE

--> Get the LAST Supplier Transaction Date
    IF @Option = 1
        BEGIN
            SELECT TOP 1 @TranDate = Document_Date,
                         @DateCaptured = Date_Captured
            FROM AO_Transactions
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Document_Date DESC
        END


    IF @TranDate IS NOT NULL
        BEGIN
            SELECT @Year = CONVERT(varchar(4), DATEPART(yy, @TranDate)),
                   @Month = CONVERT(varchar(2), DATEPART(mm, @TranDate)),
                   @Day = CONVERT(varchar(2), DATEPART(dd, @TranDate)),
                   @Hour = CONVERT(varchar(2), DATEPART(hh, @TranDate)),
                   @Minute = CONVERT(varchar(2), DATEPART(mi, @TranDate)),
                   @Second = CONVERT(varchar(2), DATEPART(ss, @TranDate))
        
        
            ------------------------------------------------------------
            --> Format the DATE
            ------------------------------------------------------------
            IF LEN(RTRIM(LTRIM(@Month))) = 1
                SET @Month = '0' + @Month
        
            IF LEN(RTRIM(LTRIM(@Day))) = 1
                set @Day = '0' + @Day
        
            SET @Date = @Year + '/' + @Month + '/' + @Day
        
        
            ------------------------------------------------------------
            --> Format the TIME
            ------------------------------------------------------------
            IF RTRIM(LTRIM(@Hour)) = ''
                BEGIN

                    SELECT @Hour = CONVERT(varchar(2), DATEPART(hh, @DateCaptured)),
                           @Minute = CONVERT(varchar(2), DATEPART(mi, @DateCaptured)),
                           @Second = CONVERT(varchar(2), DATEPART(ss, @DateCaptured))

                    IF LEN(RTRIM(LTRIM(@Hour))) = 1
                        SET @Hour = '0' + @Hour

                    IF LEN(RTRIM(LTRIM(@Minute))) = 1
                        set @Minute = '0' + @Minute

                    IF LEN(RTRIM(LTRIM(@Second))) = 1
                        set @Second = '0' + @Second
                END
            ELSE
                BEGIN
                    IF LEN(RTRIM(LTRIM(@Hour))) = 1
                        SET @Hour = '0' + @Hour

                    IF LEN(RTRIM(LTRIM(@Minute))) = 1
                        set @Minute = '0' + @Minute

                    IF LEN(RTRIM(LTRIM(@Second))) = 1
                        set @Second = '0' + @Second
                END



            SET @Time = @Hour + ':' + @Minute + ':' + @Second
        END


    SET @FullDateTime = @Date + ' ' + @Time
    SET @TranDate = CONVERT(datetime, @FullDateTime)



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   :sp_AO_Select_Formulas
--Purpose       :Returns a lup of all the Formulas 
--Functionality :
--Parameters    :	
--Date          : 2001/04/23
--Authors       : Charl 
--Version       : 1.0.0

CREATE  PROCEDURE sp_AO_Select_Formulas
(
	@Company_ID int
)
AS

SELECT AW_Formulas_ID AS [ID],
	[Description] AS [FormulaName],
	Formula AS [Formula]
FROM AW_Formulas
WHERE AW_User_Companies_ID = @Company_ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV
--Functionality :Stock Receipts  
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--MODS			:08/09/04 - Removed GRV History Search date conversion to float
--2004.4.5      :30/05/09 - Added field [GRV No] to display in Stock Receipts History
--V6.3	RL		:2017/09/19 :Added Order By Date_Received descending
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_GRV]
    (
    	@Option tinyint,
    	@CompanyID int,
    	@FromDate datetime = NULL,
    	@ToDate datetime = NULL ,
    	@SupplierID int = NULL
    )

AS

SET NOCOUNT ON

BEGIN

	IF @Option = 0        -- 0 = All GRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [GRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE Sys_AW_Transaction_Types_ID = 19 AND  --19 = GRV
              AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received DESC

	ELSE
	IF @Option = 1        -- 1 = Only Uninvoiced GRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [GRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE  Sys_AW_Transaction_Types_ID = 19 AND  --19 = GRV
			AO_GRV_ID NOT IN
                       (SELECT AO_GRV_ID
                        FROM AO_Purchase_Transactions) AND
			AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received DESC

	IF @Option = 2        -- 2 = GRV History
		SELECT AO_GRV_ID AS [ID],
			AO_Suppliers_ID AS [SupplierID],
			AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [GRV No],
			Date_Received AS [Date Received],
			Delivery_Note_Number AS [Delivery Note],
			Supplier_Reference AS [Supplier Reference],
			Trade_Discount_Total AS [Trade Disc],
			Rebate_Discount_Total AS [Rebate Disc],
			Other_Discount_Total AS [Other Disc],
			Net_Amount AS [Net Amount],
			Total_Tax_Amount AS [Tax Total],
			Total_Amount AS [Total]
		FROM AO_GRV
        WHERE Date_Received >= @FromDate AND
              Date_Received <= @ToDate AND
              AO_Suppliers_ID = @SupplierID AND
              AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID IN (19,20)
		ORDER BY Date_Received DESC


END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








----------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV_Details
--Functionality :Returns GRV details for one GRV 
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--Version       :1.0.0
--MODS			:
--2004.2.2      :08/05/05 - Added Product Code as [Code] field
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_GRV_Details
    (
    	@GRV_ID int ,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        a.AO_GRV_Details_ID AS [ID],
        a.AO_GRV_ID AS [FK ID],
        a.AP_Products_ID AS [ProductsID],
        p.[Description] AS [Product],
        p.Product_Code AS [Code],
        a.Qty AS [Qty],
        a.Unit_Price AS [Unit Price],
        a.Trade_Discount_Amount AS [Trade Disc],
        a.Rebate_Discount_Amount AS [Rebate Disc],
        a.Other_Discount_Amount AS [Other Disc],
        a.Net_Amount AS [Net Amount],
        a.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        tc.[Description] AS [Tax Code],
        a.Tax_Amount AS [Tax Amount],
        a.Total_Cost AS [Total Cost]
    FROM AO_GRV_Details a
        LEFT JOIN AP_Products p
            ON a.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
    WHERE a.AO_GRV_ID = @GRV_ID AND
          a.AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









----------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV_Details_From_Date
--Functionality :Fetch GRV/Product/Supplier details from a date
--Parameters    :
--Date          :2009/06/03
--Authors       :TB
--MODS			:
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AO_Select_GRV_Details_From_Date
    (
    	@CompanyID int,
        @FromDate datetime
    )

AS

SET NOCOUNT ON

	SELECT d.AO_GRV_Details_ID AS [ID],
           d.AO_GRV_ID AS [GRVID],
           p.AP_Products_ID AS [ProductID],
           p.Product_Code AS [Product Code],
           p.Description AS [Description],
           h.AO_Suppliers_ID AS [SupplierID],
           s.Supplier_Name AS [Supplier],
           s.Supplier_Number AS [Supplier No],
           h.Delivery_Note_Number AS [Del Note No],
           h.Supplier_Reference AS [Ref No],
           d.Qty AS [Qty],
           d.Unit_Price AS [Unit Price],
           h.Date_Captured AS [Captured]
    FROM AO_GRV_Details d
        LEFT JOIN AO_GRV h
            ON h.AO_GRV_ID = d.AO_GRV_ID
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AO_Suppliers s
            ON s.AO_Suppliers_ID = h.AO_Suppliers_ID
    WHERE d.AW_User_Companies_ID = @CompanyID AND
          h.Date_Captured >= @FromDate AND
         (h.Sys_AW_Transaction_Types_ID = 19 OR
          h.Sys_AW_Transaction_Types_ID = 20)
    ORDER BY d.AO_GRV_ID



SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV_Lups
--Functionality :Returns a lup  
--Parameters    :
--Date          :2002/01/27
--Authors       :TB
--Version       :1.0.0
--MODS          :24/07/02 - Added selecting options 8=GL Accounts List and
--              :           9=Purchases Control Account for Supplier Invoices
--              :14/08/02 - Seperated SELECT of Uninvoiced Goods RETURNED V's
--              :           from Uninvoiced Goods RECEIVED V's
--              :           Sys_AW_Transaction_Types_ID = 19/20
--              :23/09/02 - Inserted check if Slu_AW_Active_ID = 1
--              :           to SELECT ONLY Active Suppliers
--              :           This sp used in Supplier Invoicing & Stock Receipts
--              :28/10/02 - Added Transaction Type 6 (Settlement) and 12 = (Payment)
--              :           to Option = 7
--              :07/07/03 - Added 'Purchases - Consumables' Control Account as
--              :           Option 11 to set default GL account for Supplier Invoices
--              :08/12/03 - Added Option 12 Transaction Types - Multi-Split Invoices
--              :13/12/03 - Added Option 13, 13, 15, 16 for Multi-Split Invoices
--              :30/09/04 - Removed NOT selecting when AB_Accounts_ID = 1 in Option 13
--2004.5.1      :10/06/11 - Modified Option 8, 13 to only select ACTIVE GL Accounts
--RL V6.2 2015-04-10	:Added option 17 and 18 for Consignment stock
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_GRV_Lups]
    (
    	@Option tinyint,
    	@CompanyID int = 0
    )

AS

SET NOCOUNT ON

    --> Supplier List
	IF @Option = 0
		SELECT AO_Suppliers_ID AS [ID],
               Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
		ORDER BY Supplier_Name ASC

    --> Suppliers with Outstanding Orders
	ELSE  
	IF @Option = 1
		SELECT AO_Suppliers_ID AS [ID],
               Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT AO_Suppliers_ID 
                                  FROM AO_Orders 
                                  WHERE Date_Ordered IS NOT NULL AND
                                        Complete = 0) AND
              AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC

    --> Uninvoiced Goods RECEIVED Vouchers
	ELSE 
	IF @Option = 2
		SELECT AO_Suppliers_ID AS [ID],
               Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT DISTINCT AO_Suppliers_ID 
                                  FROM AO_GRV
                                  WHERE Sys_AW_Transaction_Types_ID = 19 AND
                                        AO_GRV_ID NOT IN (SELECT AO_GRV_ID 
                                                          FROM AO_Transactions 
                                                          WHERE AO_GRV_ID is NOT NULL)) AND
			  AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC

    --> Tax Codes
	ELSE 
	IF @Option = 3
		SELECT Sys_AW_Tax_Codes_ID AS [ID],
			[Description] AS [Description],
			Tax_Rate AS [Rate]
		FROM Sys_AW_Tax_Codes

    --> Months
	ELSE
	IF @Option = 4
		SELECT Slu_AW_Months_ID AS [ID],
			[Description] AS [Months]
		FROM Slu_AW_Months

    --> Years
	ELSE 
	IF @Option = 5
		SELECT Slu_AW_Years_ID AS [ID],
			[Description] AS [Years]
		FROM Slu_AW_Years

    --> Suppliers With Received GRV's
	ELSE  
	IF @Option = 6
		SELECT AO_Suppliers_ID AS [ID],
			Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT AO_Suppliers_ID 
									FROM AO_GRV
									WHERE Sys_AW_Transaction_Types_ID = 19 ) AND
			  AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC

    --> Supplier Transaction Types 
	ELSE 
	IF @Option = 7
		SELECT Sys_AW_Transaction_Types_ID AS [ID],
			[Description] AS [Transaction_Types]
		FROM Sys_AW_Transaction_Types
		WHERE Sys_AW_Transaction_Types_ID = 6 OR
              Sys_AW_Transaction_Types_ID = 8 OR
			  Sys_AW_Transaction_Types_ID = 9 OR
			  Sys_AW_Transaction_Types_ID = 10 OR
			  Sys_AW_Transaction_Types_ID = 12 
        ORDER BY [Description]

    --> GL Accounts List
	ELSE 
	IF @Option = 8
		SELECT AB_Accounts_ID AS [ID],
               [Description] 
		FROM AB_Accounts 
		WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
		ORDER BY [Description]

    --> 'Purchases' GL Control Account
	ELSE 
	IF @Option = 9
        SELECT AB_Accounts_ID AS [ID]
        FROM AB_Control_Accounts
        WHERE Control_Number = 301

    --> Uninvoiced Goods RETURNED Vouchers
	ELSE 
	IF @Option = 10
		SELECT AO_Suppliers_ID AS [ID],
               Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT DISTINCT AO_Suppliers_ID 
                                  FROM AO_GRV
                                  WHERE Sys_AW_Transaction_Types_ID = 20 AND
                                        AO_GRV_ID NOT IN (SELECT AO_GRV_ID 
                                                          FROM AO_Transactions 
                                                          WHERE AO_GRV_ID is NOT NULL)) AND
			  AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC

    --> 'Purchases - Consumables' GL Control Account
	ELSE 
	IF @Option = 11
        SELECT AB_Accounts_ID AS [ID]
        FROM AB_Control_Accounts
        WHERE Control_Number = 302

    --> Supplier Transaction Types - Multi-Split Invoices
	ELSE 
	IF @Option = 12
		SELECT Sys_AW_Transaction_Types_ID AS [ID],
			[Description] AS [Transaction_Types]
		FROM Sys_AW_Transaction_Types
		WHERE Sys_AW_Transaction_Types_ID = 8 OR
			  Sys_AW_Transaction_Types_ID = 9

    --> GL Accounts List
	ELSE 
	IF @Option = 13
		SELECT AB_Accounts_ID AS [ID],
               [Description] AS [GL Account] 
		FROM AB_Accounts 
		WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
		ORDER BY [Description]

    --> Tax Codes
    ELSE
    IF @Option = 14
    	SELECT Sys_AW_Tax_Codes_ID AS [ID], 
              [Description] AS [Tax Code],
    	       Tax_Rate AS [Rate] 
    	FROM Sys_AW_Tax_Codes
    
    --> Tax Methods
    ELSE
    IF @Option = 15
    	SELECT Sys_AW_Tax_Methods_ID AS [ID],
              [Description] AS [Tax Method] 
    	FROM Sys_AW_Tax_Methods
        ORDER BY [Tax Method] DESC
    
    --> Active
    ELSE
    IF @Option = 16
    	
    	SELECT Slu_AW_Active_ID as [ID],
              [Description] AS [Active] 
    	FROM Slu_AW_Active

	ELSE 
	
	--> Uninvoiced Consignment RECEIVED Vouchers
	IF @Option = 17
		SELECT AO_Suppliers_ID AS [ID],
               Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT DISTINCT AO_Suppliers_ID 
                                  FROM AO_GRV
                                  WHERE Sys_AW_Transaction_Types_ID = 31 AND
                                        AO_GRV_ID NOT IN (SELECT AO_GRV_ID 
                                                          FROM AO_Transactions 
                                                          WHERE AO_GRV_ID is NOT NULL)) AND
			  AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC

    --> Uninvoiced Consignment RETURNED Vouchers
	ELSE 
	IF @Option = 18
		SELECT AO_Suppliers_ID AS [ID],
               Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT DISTINCT AO_Suppliers_ID 
                                  FROM AO_GRV
                                  WHERE Sys_AW_Transaction_Types_ID = 32 AND
                                        AO_GRV_ID NOT IN (SELECT AO_GRV_ID 
                                                          FROM AO_Transactions 
                                                          WHERE AO_GRV_ID is NOT NULL)) AND
			  AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC
		
    --> Suppliers With Received CRV's
	ELSE  
	IF @Option = 19
		SELECT AO_Suppliers_ID AS [ID],
			Supplier_Name AS [Supplier Name]
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID IN (SELECT AO_Suppliers_ID 
									FROM AO_GRV
									WHERE Sys_AW_Transaction_Types_ID = 31 ) AND
			  AW_User_Companies_ID = @CompanyID
		ORDER BY Supplier_Name ASC


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV_Report_Data
--Purpose       :Returns GRV data for the GRV Report
--Parameters    :	
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
--Mods		    :22/04/02 - Inserted h.Sys_AW_Transaction_Types_ID AS [TranTypeID]
--              :           to enable printing a Goods Returned Voucher
--              :24/10/04 - Added AO_GRV_ID as [GRVID]
--              :11/05/05 - Added Received/Returned Ny as [Username]
--2004.2.5      :28/11/05 - Changed [SubTotal] field to use Net_Amount column
--2004.3.5      :05/04/07 - Changed [Co Name] to include Company_Name as primary
--V6.3	RL	2017/09/19	:Returned noted for sales order replinishment
----------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_GRV_Report_Data]
    (
    	@GRV_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @SuppliersID int,
    		@CompanyID int,
            @OrdersID int,
            @OrderNumber varchar(20),
            @OurOrderRef varchar(20)

BEGIN
	
	SELECT @SuppliersID = AO_Suppliers_ID ,
		   @CompanyID = AW_User_Companies_ID ,
           @OrdersID = AO_Orders_ID
	FROM AO_GRV
	WHERE AO_GRV_ID = @GRV_ID

    IF @OrdersID > 0
        BEGIN
            SELECT @OrderNumber = Order_Number,
                   @OurOrderRef = Our_Ref
            FROM AO_Orders
            WHERE AO_Orders_ID = @OrdersID

            SET @OrderNumber = @OrderNumber + ' (' +
                               CONVERT(VARCHAR(10),@OrdersID) + ')'

        END
    ELSE
        BEGIN
            SET @OrderNumber = ''
            SET @OurOrderRef = ''
        END
	
	SELECT
        s.Supplier_Name AS [Supp Name],	
        s.Post_Box AS [Supp PostBox],
        s.Post_Office AS [Supp PostOffice],
        s.Post_Code AS [Supp PostCode],
        s.Supplier_Telephone AS [Supp TelNo],
        s.Supplier_Fax AS [Supp FaxNo],
        s.Tax_Number AS [Supp TaxNo],
--        c.Company_Trading_Name AS [Co Name],
        ISNULL(c.Company_Name, '') + ISNULL(', ' + c.Company_Trading_Name, '') AS [Co Name],
        c.Company_Registration_Number AS [Co RegNo],
        c.Company_Addr1 AS [Co Address1],
        c.Company_Addr2 AS [Co Address2],
        c.Company_Post_Code	AS [Co PostCode],
        c.Tel_No AS [Co TelNo],
        c.Fax_No AS [Co FaxNo],
        c.TAX_Number AS [Co TaxNo],
        h.Date_Received AS [Date Received],
        @OrderNumber AS [Order Number],
        @OurOrderRef AS [Our Ref],
        h.Delivery_Note_Number AS [Del Note Number],
        h.Supplier_Reference AS [Supp Ref],
    --> From GRV Details
        d.AO_GRV_Details_ID AS [ID],
        p.Product_Code AS [Product Code],
        p.[Description] AS [Product Desc],
        d.Qty AS [QTY],
        d.Unit_Price AS [Unit Price],
        d.Trade_Discount_Amount AS [Trade Disc],
        d.Rebate_Discount_Amount AS [Rebate Disc],
        d.Other_Discount_Amount AS [Other Disc],	

--      ((d.Qty * d.Unit_Price) - d.Trade_Discount_Amount - d.Rebate_Discount_Amount - d.Other_Discount_Amount) AS [SubTotal],
        d.Net_Amount AS [SubTotal],

        d.Tax_Amount AS [Tax Amount],
        d.Total_Cost AS [Total Cost],
        h.Sys_AW_Transaction_Types_ID AS [TranTypeID],
        h.AO_GRV_ID AS [GRVID],
        ISNULL(u.Firstname, '' + ' ') + ISNULL(u.Surname, '') AS [Username],
		ISNULL(h.Notes,'') AS [Notes]

	FROM AO_GRV h
        LEFT JOIN AO_Suppliers s
			ON h.AO_Suppliers_ID = s.AO_Suppliers_ID 
		LEFT JOIN AW_User_Companies c 
			ON h.AW_User_Companies_ID = c.AW_User_Companies_ID
		LEFT JOIN AW_Users u 
			ON h.[User_ID] = u.AW_Users_ID
		INNER JOIN AO_GRV_Details d
			ON h.AO_GRV_ID = d.AO_GRV_ID 
		INNER JOIN AP_Products p 
			ON d.AP_Products_ID = p.AP_Products_ID
	WHERE h.AO_GRV_ID = @GRV_ID

END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Journal_Lups
--Purpose       :Gets a GL Accounts, TAX & Supplier List
--Functionality :Used in new Supplier Journals
--Parameters    :
--Date          :2002/06/29
--Authors       :TB
--MODS          :
--2004.3.8      :30/05/08 - Added 'SundryPurchases' as mlngDefaultGLAccountID
--2004.5.1      :10/06/11 - Modified Option 'Account' to only select ACTIVE GL Accounts
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Journal_Lups
    (
    	@CompanyID int,
    	@Option varchar(20) = ''
    )

AS

SET NOCOUNT ON

	IF @Option = 'Account'
		SELECT
            AB_Accounts_ID AS [ID],
            [Description] 
		FROM AB_Accounts 
		WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
		ORDER BY [Description]

	ELSE
	IF @Option = 'Tax'
		SELECT
            Sys_AW_Tax_Codes_ID AS [ID],
            [Description],
            Tax_Rate AS [Tax] 
		FROM Sys_AW_Tax_Codes

    ELSE
    IF @Option = 'SundryPurchases'
        SELECT
            AB_Accounts_ID AS [ID]
        FROM AB_Control_Accounts
        WHERE Control_Number = 302

	ELSE
		SELECT 
			AO_Suppliers_ID AS [ID],
    		ISNULL(Supplier_Name, '') AS [Name],
    		ISNULL(Supplier_Number, '') AS [No]
		FROM AO_Suppliers
		WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Name]

SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Multi_Split_Transaction_History
--Purpose       :Returns Multi-Split Supplier Transaction History
--              :from AB_GL_Transactions
--Date          :2003/12/13
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Multi_Split_GL_History
    (
        @SupplierTranID int,
        @SupplierID int
    )

AS

SET NOCOUNT ON

    SELECT T.AO_Transactions_ID AS [ID], 
           T.AO_Suppliers_ID AS [SupplierID],
           A.AB_Accounts_ID AS [GLID], 
           A.[Description]  AS [GL Account],
--           TT.[Description] AS [Transaction Type],
           G.AB_Source_Ref AS [Ref No],
           G.AB_Transaction_Date AS [Date],
           M.[Description] AS [Month],
           Y.[Description] AS [Year],
           G.[Description] AS [Description],
           G.AB_Transaction_Amount AS [Amount],
           T.Date_Captured AS [Date Captured],
           T.[User_ID] AS [User ID], 
           T.AW_User_Companies_ID AS [Company ID], 
           T.Slu_AW_Active_ID AS [Active] 
    FROM AB_GL_Transactions G
        INNER JOIN AB_Accounts A
        	ON G.AB_Accounts_ID = A.AB_Accounts_ID 
        INNER JOIN AO_Transactions T
        	ON G.AB_Transaction_Ref = T.AO_Transactions_ID
        INNER JOIN Sys_AB_Transaction_Types TT
        	ON G.Sys_AB_Transaction_Types_ID = TT.Sys_AB_Transaction_Types_ID
        INNER JOIN Slu_AW_Months M 
        	ON G.Slu_AW_Months_ID = M.Slu_AW_Months_ID
        INNER JOIN Slu_AW_Years Y
        	ON G.Slu_AW_Years_ID  = Y.Slu_AW_Years_ID
     WHERE G.AB_Transaction_Ref = @SupplierTranID AND
           T.AO_Suppliers_ID = @SupplierID AND
          (G.Sys_AB_Transaction_Types_ID = 5 OR
           G.Sys_AB_Transaction_Types_ID = 6 OR
           G.Sys_AB_Transaction_Types_ID = 7 OR
           G.Sys_AB_Transaction_Types_ID = 8 OR
           G.Sys_AB_Transaction_Types_ID = 25) 



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Multi_Split_Transaction_Details
--Purpose       :Returns the Supplier Transaction Details
--              :for a specific Supplier Header ID
--              :Distant relationship to AB_Cash_Book_Transaction_Details is to
--              :relate Sys_AW_Tax_Methods and Sys_AW_Tax_Codes
--Date          :2003/12/09
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Multi_Split_Transaction_Details
    (
        @AO_Transactions_ID int
    )

AS

SET NOCOUNT ON

    SELECT T.AO_Transactions_ID AS [ID], 
           A.AB_Accounts_ID AS [FK ID], 
           A.[Description]  AS [GL Account] ,
           M.[Description] AS [Tax Method], 
           C.[Description] AS [Tax Code], 
           T.Total_Amount AS [Amount], 
           T.Total_Tax_Amount AS [Tax Amount],
           T.Net_Amount AS [Net], 
           T.Comment, 
           T.Date_Captured AS [Date Captured],
           T.[User_ID] AS [User ID], 
           T.AW_User_Companies_ID AS [Company ID], 
           T.Slu_AW_Active_ID AS [Active] 
    FROM AO_Transactions T
        INNER JOIN AB_Accounts A
        	ON T.AB_Accounts_ID = A.AB_Accounts_ID 
        INNER JOIN AB_Cash_Book_Transaction_Details CD
        	ON CD.AB_Accounts_ID = A.AB_Accounts_ID 
        INNER JOIN Sys_AW_Tax_Methods M 
        	ON CD.Sys_AW_Tax_Methods_ID = M.Sys_AW_Tax_Methods_ID
        INNER JOIN Sys_AW_Tax_Codes C
        	ON CD.Sys_AW_Tax_Codes_ID  = C.Sys_AW_Tax_Codes_ID
     WHERE T.AO_Transactions_ID = @AO_Transactions_ID 


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Multi_Split_Transaction_History
--Purpose       :Returns Multi-Split Supplier Transaction History
--              :from AO_Transactions
--Date          :2003/12/13
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Multi_Split_Transaction_History
	(
    	@SupplierID int,
        @TransactionTypeID int,
    	@StartDate datetime,
    	@EndDate datetime,
    	@MonthsID int,
    	@YearsID int,
    	@CheckTypes tinyint,
    	@CheckDates tinyint,
    	@CheckPeriod tinyint,
    	@Company_ID int
	)

AS

--SHAPE {{CALL dbo.sp_AO_Select_Multi_Split_Transaction_History( 2, 0, '00:00:00', '00:00:00', 0, 0, 1, 0, 0, 1) }} AS chpHistTransactions APPEND ({{CALL dbo.sp_AO_Select_Multi_Split_GL_History( ? ) }} AS chpHistTransactionDetails RELATE 'ID' TO PARAMETER 0) AS chpTransactionDetails

SET NOCOUNT ON

	DECLARE @sql varchar(6000)

    SET @sql = ' SELECT ' +
                ' t.AO_Transactions_ID AS [ID], ' +
                ' t.AO_Suppliers_ID AS [SupplierID], ' +
                ' tt.[Description] AS [Type], ' +
                ' t.Document_Number AS [Ref No], ' +
                ' t.Document_Date AS [Date], ' +
                ' m.[Description] AS [Month], ' +
                ' y.[Description] AS [Year], ' +
                ' t.Comment AS [Comment], ' +
                ' t.Net_Amount AS [Net Amount], ' +
                ' t.Total_Tax_Amount [Tax Amount], ' +
                ' t.Total_Amount AS [Amount], ' +
                ' t.Payment_Amount AS [Payment], ' +
                ' t.Trade_Discount_Total AS [Trade Disc], ' +
                ' t.Rebate_Discount_Total AS [Rebate Disc], ' +
                ' t.Other_Discount_Total AS [Other Disc], ' +
                ' t.Date_Captured AS [Captured], ' +
                ' u.UserName AS [User] ' +
			' FROM AO_Transactions t ' +
                ' LEFT JOIN Sys_AW_Transaction_Types tt ' +
				    ' ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID ' +
                ' LEFT JOIN Slu_AW_Months m ' +
                    ' ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID ' +
                ' LEFT JOIN Slu_AW_Years y ' +
                    ' ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID ' +
                ' LEFT JOIN AW_Users u ' +
                    ' ON t.User_ID = u.AW_Users_ID '

--WHERE
    SET @sql = @sql +
                ' WHERE t.AO_Suppliers_ID = ' + CONVERT(VARCHAR(20), @SupplierID) + ' AND ' +
                '       t.AW_User_Companies_ID = ' + CONVERT(VARCHAR(20), @Company_ID) + ' '

--Additional WHERE
    IF @CheckTypes = 0    -- Specific TRANSACTION TYPE
        BEGIN
            SET @sql = @sql +
                    ' AND t.Sys_AW_Transaction_Types_ID = ' + CONVERT(VARCHAR(20), @TransactionTypeID)
        END
    ELSE
        BEGIN
            SET @sql = @sql +
                    ' AND (t.Sys_AW_Transaction_Types_ID = 6 OR ' +
                    '      t.Sys_AW_Transaction_Types_ID = 8 OR ' +
                    '      t.Sys_AW_Transaction_Types_ID = 9 OR ' +
                    '      t.Sys_AW_Transaction_Types_ID = 10 OR ' +
                    '      t.Sys_AW_Transaction_Types_ID = 12) '
        END

    IF @CheckDates = 1    -- Specific DATES
        SET @sql = @sql +
                ' AND DATEDIFF(d, t.Document_Date, ''' + CONVERT(VARCHAR(20), @StartDate) + ''') <= 0 ' +
                ' AND DATEDIFF(d, t.Document_Date, ''' + CONVERT(VARCHAR(20), @EndDate) + ''') >= 0 '

    IF @CheckPeriod = 1   --Between Accounting Periods
        SET @sql = @sql +
                ' AND t.Slu_AW_Months_ID = ' + CONVERT(VARCHAR(20), @MonthsID) +
                ' AND t.Slu_AW_Years_ID = ' + CONVERT(VARCHAR(20), @YearsID)

    SET @sql = @sql +
        ' ORDER BY t.Document_Date DESC '

--> RUN the script
--  --------------
    EXEC (@sql)


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Multi_Split_Transactions
--Purpose       :Returns the Supplier Transactions
--              :for specific Supplier, Transaction Type
--Date          :2003/12/09
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Multi_Split_Transactions
    (
        @Supplier_ID int,
        @Transaction_Type_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    SELECT AO_Transactions_ID AS [ID], 
           AO_Suppliers_ID AS [Bank], 
           Sys_AW_Transaction_Types_ID AS [Transaction Types], 
           Document_Date AS [Date], 
           Slu_AW_Months_ID AS [Month], 
           Slu_AW_Years_ID AS [Year],
           Supplier_Reference AS [Ref No], 
           Comment AS [Description], 
           Total_Amount AS [Amount]
    FROM AO_Transactions 
    WHERE AO_Suppliers_ID = @Supplier_ID AND 
          Sys_AW_Transaction_Types_ID = @Transaction_Type_ID AND 
          AW_User_Companies_ID = @Company_ID 

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_Candidates
--Purpose       :Returns all Order Candidates
--Functionality :Used in the Purchase Orders UI to filter the records in this query
--              :When an Order Candidate is added to an order that record's show field is set = 0 
--Parameters    :
--Date          :2002/02/19
--Authors       :TB
--Version       :1.0.0
--MODS          :05/09/04 - Added ORDER BY c.Date_Captured DESC
--V6.3	RL	2017/04/08	:Update order candidates to product catalog last cost
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Order_Candidates]
    (
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	UPDATE AO_Order_Candidates
	SET AO_Order_Candidates.Last_Cost = p.Last_Cost
	FROM AO_Order_Candidates c
		INNER JOIN AP_Products p
			On c.AP_Products_ID = p.AP_Products_ID

   SELECT
        c.AO_Order_Candidates_ID AS [ID],
        c.Ready AS [Ready],
        c.AP_Products_ID AS [FK ID],
		p.Product_Code AS [Code],
        p.[Description] AS [Product],
        c.AO_Suppliers_ID AS [Supplier ID],
        s.Supplier_Name AS [Supplier],
        c.Order_Date AS [Date],
        c.Qty AS [Qty],
        c.Last_Cost AS [Last Cost],
        c.Notes AS [Notes],
        c.Reviews AS [Reviews],
        ISNULL(u.Firstname + ' ', '') + ISNULL(u.Surname, '') as [Originator],
        c.Date_Captured AS [Date Captured],
        c.[User_ID] AS [User ID],
        c.AW_User_Companies_ID AS [Company]
	FROM AO_Order_Candidates c
        LEFT JOIN AO_Suppliers s
	        ON s.AO_Suppliers_ID = c.AO_Suppliers_ID
        LEFT JOIN AP_Products p
	        ON c.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AW_Users u
	        ON c.Originator =  u.AW_Users_ID
	WHERE c.AW_User_Companies_ID = @CompanyID
    ORDER BY c.Date_Captured DESC 

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Orders_Details
--Purpose       :Fetches Details for a selected OrderID in Purchase Orders
--Functionality :NB: MUST match field names in UI DB update section
--Parameters    :
--Date          :2002/01/15
--Authors       :TB
--Version       :1.0.0
--MODS          :10/11/03 - Added User-Friendly labels for sugOrderDetails(0) in
--              :           Supplier Purchase Orders
---------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Select_Order_Details 
    (
    	@Orders_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT
        OD.AO_Order_Details_ID AS [ID],
        OD.AO_Orders_ID AS [FK ID],
        OD.AP_Products_ID AS [Products ID],
        P.[Description] AS [Product],
        OD.Order_Qty AS [Qty],
        OD.Unit_Price AS [Unit Price],
        OD.Trade_Discount_Amount AS [Trade Disc],
        OD.Rebate_Discount_Amount AS [Rebate Disc],
        OD.Other_Discount_Amount AS [Other Disc],
        OD.Net_Amount AS [Net Amount],
        OD.Tax_Amount AS [Tax],
        OD.Total_Cost AS [Total Cost],
        OD.Received_Qty AS [Received],
        OD.Receipt_Date AS [Receipt Date],
        OD.Free_Qty AS [Free Qty],
        OD.Back_Order_Qty AS [B/O Qty],
        OD.Trade_Discount_Formula_ID AS [Trade_Discount_Formula_ID],
        TDF.[Description] AS [T/Disc Formula],
        OD.Trade_Discount_Percentage AS [T/Disc %],
        OD.Rebate_Formula_ID AS [Rebate_Formula_ID],
        RDF.[Description] AS [R/Disc Formula],
        OD.Rebate_Discount_Percentage AS [R/Disc %],
        OD.Other_Discount_Formula_ID AS [Other_Discount_Formula_ID],
        ODF.[Description] AS [O/Disc Formula],
        OD.Other_Discount_Percentage AS [O/Disc %],
        OD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        TC.[Description] AS [Tax Code],
        OD.Lead_Time AS [Lead Time],
        OD.Date_Captured AS [Date Captured],
        OD.[User_ID] AS [User ID],
        OD.AW_User_Companies_ID AS [Company],
        A.[Description] AS [Active]
	FROM AO_Order_Details OD
        LEFT JOIN AP_Products P
	        ON OD.AP_Products_ID  = P.AP_Products_ID
	    LEFT JOIN AW_Formulas TDF
            ON OD.Trade_Discount_Formula_ID = TDF.AW_Formulas_ID
	    LEFT JOIN AW_Formulas RDF
            ON OD.Rebate_Formula_ID = RDF.AW_Formulas_ID
	    LEFT JOIN AW_Formulas ODF
            ON OD.Other_Discount_Formula_ID = ODF.AW_Formulas_ID
	    LEFT JOIN Sys_AW_Tax_Codes TC
            ON OD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
        LEFT JOIN Slu_AW_Active A
            ON OD.Slu_AW_Active_ID = A.Slu_AW_Active_ID
	WHERE OD.AO_Orders_ID = @Orders_ID AND 
          OD.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_Details_Product_Details
--Purpose       :Gets the details for a product that is selected in the
--              :    Order Details section for editing 
--				:    of the Purchase Orders UI
--Functionality :
--Parameters    :
--Date          :2002/02/09
--Authors       :TB
--MODS          :
--2004.2.5      :14/01/06 - Replaced in DECLARE all amount type DECIMAL(14,6) variable
--              :           declarations with type MONEY !!!!
--V6.3	RL	2017/05/04	:Change select reserved stock from transactions and not AP_Products
-----------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_Order_Details_Product_Details]
    (
        @AP_Products_ID int,
    	@Suppliers_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @Use_Supplier_Discounts Bit,
    	@Use_Rebate_Disc_GL_Acc Bit,
    	@Use_Other_Disc_GL_Acc Bit,
    	@Rebate_Disc_GL_Acc int,
    	@Other_Disc_GL_Acc int,
    	@Purchases_Contol_Acc_ID int,

    	@OtherDisc money,
    	@RebateDisc money,
    	@TradeDisc money,
    	@OtherDiff money,
    	@RebateDiff money,
    	@TradeDiff money,
    	@GrossPurchasePrice money,
    	@Last_Cost money

    -- 	SET @AP_Products_ID = 1
    -- 	SET @Suppliers_ID = 4 
    -- 	SET @Company_ID = 1
    
    BEGIN 
    	BEGIN
    		SELECT @Use_Supplier_Discounts = Use_Supplier_Discount_Defaults,
    				@Use_Rebate_Disc_GL_Acc = Use_Rebate_Discount_Control_Acc,
    				@Use_Other_Disc_GL_Acc = Use_Other_Discount_Control_Acc,
    				@Rebate_Disc_GL_Acc = AB_Rebate_Discount_Account_ID,
    				@Other_Disc_GL_Acc = AB_Other_Discounts_Account_ID
    		FROM AO_Suppliers 
    		WHERE AO_Suppliers_ID = @Suppliers_ID
    
    		SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    		FROM AB_Control_Accounts
    		WHERE Control_Number = 301
    
    	END
    
        ---------------------------------------------------------------------
        --    Calculate the Last Trade, Rebate and Other Discounts allowed
        --        for the @AP_Products_ID product
        --    To be used in a reverse Calculation of the Gross Purchase Price
        --        for the @AP_Products_ID product
        ---------------------------------------------------------------------
    
    	BEGIN
    		BEGIN
    			SELECT @Last_Cost = ISNULL(Last_Cost,0)
    			FROM AP_Products 
    			WHERE AP_Products_ID = @AP_Products_ID
    		END 
    
    		BEGIN	
    			SET @OtherDisc = 0
    			SET @RebateDisc = 0
    			SET @TradeDisc = 0
    
    			SELECT TOP 1 @OtherDisc =ISNULL(Other_Discount_Percentage,0) ,
                             @RebateDisc = ISNULL(Rebate_Discount_Percentage,0) ,
                             @TradeDisc = ISNULL(Trade_Discount_Percentage,0) 
    			FROM AO_Order_Details
    			WHERE AP_Products_ID = @AP_Products_ID AND
    				  AW_User_Companies_ID = @Company_ID AND
    				  Receipt_Date IS NOT NULL
    			ORDER BY Receipt_Date DESC
    		END
    
    		BEGIN			
    			SET @OtherDiff = ((100 - @OtherDisc)/100) 
    			SET @RebateDiff = ((100 - @RebateDisc)/100) 
    			SET @TradeDiff = ((100 - @TradeDisc)/100)	
    
    ---------------------------------------------------------------------------------------------------------------			
    		/* Determine if the Other Discount was subtracted from Unit Price to Calculate Last Cost */
    
    			IF @Use_Other_Disc_GL_Acc = 1
    				BEGIN
    					IF @Other_Disc_GL_Acc = @Purchases_Contol_Acc_ID
    						BEGIN
    							SET @GrossPurchasePrice = (@Last_Cost / @OtherDiff)
    						END
    					ELSE
    						BEGIN
    							SET @GrossPurchasePrice = @Last_Cost
    						END
    
    				END
    			ELSE
    			/* This means that the Other Disc was written to the Purchases Control Acc*/
    				BEGIN
    					SET @GrossPurchasePrice = (@Last_Cost / @OtherDiff)
    				END
    
    ---------------------------------------------------------------------------------------------------------------					
    		/* Determine if the Rebate Discount was subtracted from Unit Price to Calculate Last Cost */
    
    			IF @Use_Rebate_Disc_GL_Acc = 1
    				BEGIN
    					IF @Rebate_Disc_GL_Acc = @Purchases_Contol_Acc_ID
    						BEGIN
    							SET @GrossPurchasePrice = (@GrossPurchasePrice / @RebateDiff)
    						END
    					ELSE
    						BEGIN
    							SET @GrossPurchasePrice = @GrossPurchasePrice 
    						END
    
    				END
    			ELSE
    			/* This means that the Other Disc was written to the Purchases Control Acc*/
    				BEGIN
    					SET @GrossPurchasePrice = (@GrossPurchasePrice / @RebateDiff)
    				END
    
    ---------------------------------------------------------------------------------------------------------------					
    
    -- 			SET @GrossPurchasePrice = (@Last_Cost / @OtherDiff)
    -- 			SET @GrossPurchasePrice = (@GrossPurchasePrice / @RebateDiff)
    -- 			SET @GrossPurchasePrice = (@Last_Cost / @RebateDiff)
    
    ---------------------------------------------------------------------------------------------------------------					
    
    			SET @GrossPurchasePrice = (@GrossPurchasePrice / @TradeDiff)
    		END
    
    	END
    ---------------------------------------------------------------------------------------------------------------
    
    		SELECT DISTINCT P.AP_Products_ID AS [ID],
    			P.[Description] AS [Product],
    			dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) as [Price 1],
    			dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()) as [Price 2],
    -- 			P.Price1_Price1 AS [Price 1],
    -- 			P.Price1_Price2 AS [Price 2],
    			@GrossPurchasePrice AS [Gross_Purchase_Price],
    			(SELECT DISTINCT Lead_Time 
    				FROM AP_Products_Suppliers 
    				WHERE AP_Products_ID = @AP_Products_ID AND AO_Suppliers_ID = @Suppliers_ID) 
    				AS [Lead Time],
    			P.Service_Level AS [Service Level],
    			P.Last_Sale_Date AS [Last Sale],
    			P.On_Hand AS [Stock On Hand],
    			--V6.3 Get reserved stock from transactions and not product table
    			CONVERT(decimal(9, 3), (dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID) + dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) ) as [Stock Reserved],
    			--P.Job_Reserved + P.Sales_Order_Reserved AS [Stock Reserved],
    			P.Last_Cost	AS [Last_Cost],	
    
    -- 			(SELECT Sum(OD.Order_Qty)+ Sum(OD.Back_Order_Qty)  
    -- 					FROM AO_Order_Details OD 
    -- 						INNER JOIN AO_Orders O 
    -- 							ON OD.AO_Orders_ID = O.AO_Orders_ID  
    -- 					WHERE O.Date_Ordered is not null AND OD.AP_Products_ID = @AP_Products_ID ) 
    -- 					AS [Qty on order],
    		
    			(SELECT (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
    			        FROM AO_Order_Details od INNER JOIN AO_Orders o
    			            ON od.AO_Orders_ID = o.AO_Orders_ID
    			        WHERE o.Date_Ordered is not null AND
    			              o.Complete <> 1 AND
    			              od.AP_Products_ID = @AP_Products_ID) AS [Qty on order],
    
    
    			(SELECT Sum(OD.Order_Qty)+ Sum(OD.Back_Order_Qty)      
    					FROM AO_Order_Details OD 
    						INNER JOIN AO_Orders O 
    							ON OD.AO_Orders_ID = O.AO_Orders_ID  
    					WHERE O.Date_Ordered is null AND OD.AP_Products_ID = @AP_Products_ID ) 
    					AS [Orders Pending],
    		
    			(SELECT Sum(OC.Qty) 
    					FROM AO_Order_Candidates OC 
    					WHERE OC.AP_Products_ID =  @AP_Products_ID ) 
    					AS [Shopping List Qty],

            --> SELECT THE DISCOUNT FORMULAS OF THE SUPPLIER/PRODUCT
                CASE @Use_Supplier_Discounts WHEN 1
                    THEN 
                        (SELECT AW_Trade_Discount_Formula_ID
                         FROM AO_Suppliers
                         WHERE AO_Suppliers_ID = @Suppliers_ID)
    				ELSE
    					(SELECT DISTINCT AW_Trade_Discount_Formula_ID
                         FROM AP_Products_Suppliers
                         WHERE AP_Products_ID = @AP_Products_ID AND
                               AO_Suppliers_ID = @Suppliers_ID AND
                               AW_User_Companies_ID = @Company_ID)
    				END	AS [Trade_Discount_Formula_ID],
    			
                CASE @Use_Supplier_Discounts WHEN 1
                    THEN
                        (SELECT AW_Rebate_Discount_Formula_ID
                         FROM AO_Suppliers
                         WHERE AO_Suppliers_ID = @Suppliers_ID)
    				ELSE   
                        (SELECT DISTINCT AW_Rebate_Discount_Formula_ID
                         FROM AP_Products_Suppliers
                         WHERE AP_Products_ID = @AP_Products_ID AND
                               AO_Suppliers_ID = @Suppliers_ID AND
                               AW_User_Companies_ID = @Company_ID)
    				END AS [Rebate_Discount_Formula_ID],
    			
                (SELECT Sys_AW_Tax_Codes_ID FROM AO_Suppliers WHERE AO_Suppliers_ID = @Suppliers_ID) AS [Tax_Codes_ID]
    			
    		FROM AP_Products P 
    		WHERE P.AP_Products_ID = @AP_Products_ID 
    
    END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









----------------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_Lups
--Purpose       :Returns a Lup of all the Formulas 
--Functionality :
--Parameters    :	
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
----------------------------------------------------------------------------------

-- @Choice values
-- 1 = Trade Discount
-- 2 = Rebate Discount
-- 3 = Other Discount
-- 4 = Tax Codes
----------------------------------------------------------------------------------
CREATE    Procedure sp_AO_Select_Order_Lups
    (
    	@Choice tinyint,
    	@Company_ID int = 0
    )

AS

BEGIN 

	IF @Choice = 1 	
		SELECT AW_Formulas_ID AS [Trade_Discount_Formula_ID],
			[Description] AS [Trade_Formula],
			Formula AS [Formula]
		FROM AW_Formulas
--		WHERE AW_User_Companies_ID = @Company_ID

	ELSE 
	IF @Choice = 2
		SELECT AW_Formulas_ID AS [Rebate_Formula_ID],
			[Description] AS [Rebate_Formula],
			Formula AS [Formula]
		FROM AW_Formulas
--		WHERE AW_User_Companies_ID = @Company_ID

	ELSE 
	IF @Choice = 3 
		SELECT AW_Formulas_ID AS [Other_Discount_Formula_ID],
			[Description] AS [Other_Discount_Formula],
			Formula AS [Formula]
		FROM AW_Formulas
--		WHERE AW_User_Companies_ID = @Company_ID

	ELSE 
	IF @Choice = 4	
		SELECT Sys_AW_Tax_Codes_ID AS [Sys_AW_Tax_Codes_ID],
			[Description] AS [TaxCodes],
			Tax_Rate AS [Tax Rate]
		FROM Sys_AW_Tax_Codes

END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_No
--Purpose       :Gets the next Order no from Sys_AW_Transaction_Types
--Date          :2003/10/10
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Order_No
    (
    	@Company_ID int 
    )

AS

SET NOCOUNT ON

    DECLARE @OrderNumber varchar(20),
    		@LastNumber decimal(7,0)
    
    BEGIN	
    	SELECT @LastNumber = (n.Last_Number + 1)
    	FROM Sys_AW_Transaction_Types t
            JOIN Sys_AW_Transaction_Numbers n 
    	        ON n.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
    	WHERE t.Sys_AW_Transaction_Types_ID = 14 AND 
    		n.AW_User_Companies_ID = @Company_ID
    	
    	SELECT @LastNumber AS [OrderNo]	
    END 












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   :sp_AO_Select_Order_Originator
--Purpose       :Returns a lup of all the order originators
--Functionality :
--Parameters    :	
--Date          : 2001/04/27
--Authors       : Charl 
--Version       : 1.0.0

CREATE Procedure sp_AO_Select_Order_Originator

AS

SELECT AW_Users_ID as ID , firstname + ' ' + Surname as Originator 
FROM AW_Users 
UNION 
SELECT Sys_AT_Actor_Types_ID as ID, Description as Originator 
FROM Sys_AT_Actor_Types 
ORDER BY Originator









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Orders
--Purpose       :Fetches a Supplier Order 
--Functionality :
--Parameters    :
--Date          :2002/01/15
--Authors       :TB 
--Version       :1.0
--MODS          :06/11/03 - Added JOINS to display user-friendly descriptions
--V6.0	RL	2014-09-18 :Added Fields in selects for pended orders
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Orders]
    (
    	@OrderStatus tinyint = 0,
    	@SupplierID int = 0,
    	@CompanyID int			
    )

-- @OrderStatus:    0=All, 1=Pending, 2=Outstanding, 3=Completed

AS

SET NOCOUNT ON

    BEGIN 
    --> 0 = All Orders
    	IF @OrderStatus = 0	
    		SELECT
                O.AO_Orders_ID AS [ID],
                O.Order_Number AS [Order No],
                CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                B.NodeName AS [Ordered By],
                B.NodeName AS [Branch_Codes],                    
                O.AO_Suppliers_ID AS [SupplierID],
                S.Supplier_Name AS [Supplier],
                O.Net_Amount AS [Net Amount],
                O.Tax_Total AS [Tax],
                O.Tax_Total AS [Tax Total],
                O.Order_Total AS [Total Amount],
                O.Order_Total AS [Order Total],
                (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
                 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                M.[Description] AS [Order Method],
                O.Send_To_Address AS [Deliver To],
                O.Delivery_Addr1 AS [Address],
                O.Delivery_Addr2 AS [Suburb],
                O.Delivery_Addr3 AS [City],
                O.Postal_Code AS [Post Code],
                O.Invoice_Total AS [Invoice Total],
                O.Admin_Fee  AS [Admin Fee],
                O.Trade_Discount_Total AS [Trade Disc],
                O.Trade_Discount_Total AS [Trade Discount],                
                O.Rebate_Discount_Total AS [Rebate Disc],
                O.Rebate_Discount_Total AS [Rebate Discount],
                O.Other_Discount_Total AS [Other Disc],
                O.Other_Discount_Total AS [Other Discount],
                O.Version AS [Version],
                O.Supplier_Rep AS [Supplier Rep],
                O.Supplier_Type AS [Supplier Type],
                O.Confirmation AS [Confirmed],
                O.Confirmation_Date AS [Confirm Date],
                O.Our_Ref AS [Our Ref],
                O.Supplier_Reference AS [Supplier Ref],
                O.Invoice_Type AS [Invoice Type],
                O.Date_Captured AS [Date Captured],
                O.[User_ID] AS [User ID],
                U.UserName AS [User],
                O.AW_User_Companies_ID AS [Company],
                A.[Description] AS [Active]
    		FROM AO_Orders O
                LEFT JOIN AO_Suppliers S
                    ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                LEFT JOIN AW_Remote_Access B
                    ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                LEFT JOIN Sys_AO_Delivery_Methods M
                    ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                LEFT JOIN AW_Users U
                    ON O.[User_ID] = U.AW_Users_ID
                LEFT JOIN Slu_AW_Active A
                    ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    		WHERE O.AW_User_Companies_ID = @CompanyID
    
    --> 1 = Pending Orders
    	ELSE 
    	IF @OrderStatus = 1 
    		BEGIN
    		IF @SupplierID = 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
					B.NodeName AS [Branch_Codes],                    
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],                    
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
                    O.Trade_Discount_Total AS [Trade Discount],
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NULL AND
                      O.Complete = 0 AND 
                      O.AW_User_Companies_ID = @CompanyID
    
    		ELSE 
    		IF @SupplierID <> 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NULL AND
                      O.Complete = 0 AND 
                      O.AO_Suppliers_ID = @SupplierID AND
                      O.AW_User_Companies_ID = @CompanyID
    
    		END
    --> 2 = Outstanding Orders
    	ELSE 
    	IF @OrderStatus = 2 
    		BEGIN
    		IF @SupplierID = 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NOT NULL AND
                      O.Complete = 0 AND
                      O.AW_User_Companies_ID = @CompanyID
    		ELSE
    		IF @SupplierID <> 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
					O.Rebate_Discount_Total AS [Rebate Discount],                    
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NOT NULL AND
                      O.Complete = 0 AND
                      O.AO_Suppliers_ID = @SupplierID AND
                      O.AW_User_Companies_ID = @CompanyID
    		END
    
    --> 3 = Completed Orders
    	ELSE 
    	IF @OrderStatus = 3
    		BEGIN
    		IF @SupplierID = 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Complete = 1 AND
                      O.AW_User_Companies_ID = @CompanyID
    		ELSE
    		IF @SupplierID <> 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Complete = 1 AND
                      O.AO_Suppliers_ID = @SupplierID AND
                      O.AW_User_Companies_ID = @CompanyID
    		END
    	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Procurement_Lups
--Purpose       :Procurement Look-ups
--Date          :2009/06/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Procurement_Lups
    (
        @Option tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    IF @Option = 1
    	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 AND
              Slu_AW_Active_ID = 1
        ORDER BY [ID]



SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Procurement_Order_Details
--Purpose       :Fetches Details for a selected Order
--Functionality :
--Parameters    :
--Date          :2003/11/10
--Authors       :TB
--Version       :1.0.0
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Procurement_Order_Details 
    (
    	@Orders_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT
        OD.AO_Order_Details_ID AS [ID],
        OD.AO_Orders_ID AS [FK ID],
        OD.AP_Products_ID AS [Products ID],
        P.[Description] AS [Product],
        OD.Order_Qty AS [Qty],
        OD.Unit_Price AS [Unit Price],
        OD.Net_Amount AS [Net Amount],
        OD.Tax_Amount AS [Tax],
        OD.Total_Cost AS [Total Amount],
        OD.Received_Qty AS [Received],
        OD.Receipt_Date AS [Last Receipt],
        OD.Free_Qty AS [Free Qty],
        OD.Back_Order_Qty AS [B/O Qty],
        TDF.[Description] AS [T/Disc Formula],
        OD.Trade_Discount_Amount AS [Trade Disc],
        OD.Trade_Discount_Percentage AS [T/Disc %],
        RDF.[Description] AS [R/Disc Formula],
        OD.Rebate_Discount_Amount AS [Rebate Disc],
        OD.Rebate_Discount_Percentage AS [R/Disc %],
        ODF.[Description] AS [O/Disc Formula],
        OD.Other_Discount_Amount AS [Other Disc],
        OD.Other_Discount_Percentage AS [O/Disc %],
        OD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        TC.[Description] AS [Tax Code],
        OD.Lead_Time AS [Lead Time],
        OD.Date_Captured AS [Date Captured],
        OD.[User_ID] AS [User ID],
        OD.AW_User_Companies_ID AS [Company],
        A.[Description] AS [Active]
	FROM AO_Order_Details OD
        LEFT JOIN AP_Products P
	        ON OD.AP_Products_ID  = P.AP_Products_ID
	    LEFT JOIN AW_Formulas TDF
            ON OD.Trade_Discount_Formula_ID = TDF.AW_Formulas_ID
	    LEFT JOIN AW_Formulas RDF
            ON OD.Rebate_Formula_ID = RDF.AW_Formulas_ID
	    LEFT JOIN AW_Formulas ODF
            ON OD.Other_Discount_Formula_ID = ODF.AW_Formulas_ID
	    LEFT JOIN Sys_AW_Tax_Codes TC
            ON OD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
        LEFT JOIN Slu_AW_Active A
            ON OD.Slu_AW_Active_ID = A.Slu_AW_Active_ID
	WHERE OD.AO_Orders_ID = @Orders_ID AND 
          OD.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Product_Linked_Suppliers
--Purpose       :Returns a lup of all Linked Suppliers of a Product
--Functionality :
--Parameters    :
--Date          :2008/06/16
--Authors       :TB 
--MODS          :
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Product_Linked_Suppliers
    (
        @ProductID int
    )

AS

    SELECT s.AO_Suppliers_ID AS [ID],
    	   s.Supplier_Name AS [Supplier]
    FROM AP_Products_Suppliers ps
        INNER JOIN AO_Suppliers s
            ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
    WHERE ps.AP_Products_ID = @ProductID
    ORDER BY [Supplier]









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--Description   :sp_AO_Select_Product_Qty_Details
--Purpose       :Gets the Qty details for a product to be use as forecasting info 
--				 in the purchase orders interface
--Functionality :
--Parameters    :
--Date          : 2001/04/09
--Authors       : Charl
--Version       :

CREATE          PROCEDURE sp_AO_Select_Product_Qty_Details
(
    @AP_Products_ID int,
	@Company_ID int	
)

AS
    SET NOCOUNT ON
SELECT P.AP_Products_ID AS [ID],
	P.[Description] AS [Product],

	(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 OD.AP_Products_ID = @AP_Products_ID AND 
	 	O.Complete <> 1 AND
		O.AW_User_Companies_ID = @Company_ID ) 
	 AS [Qty on order],

	P.On_Hand AS [On Hand],
	P.Job_Reserved + P.Sales_Order_Reserved AS [Qty Reserved],
	P.Last_Sale_Date AS [Last Sale],

	(SELECT Sum(OD.Order_Qty)+ Sum(OD.Back_Order_Qty)  
	 FROM AO_Order_Details OD 
	 INNER JOIN AO_Orders O 
	 ON OD.AO_Orders_ID = O.AO_Orders_ID  
	 WHERE O.Date_Ordered is null AND OD.AP_Products_ID = @AP_Products_ID AND 
	 O.AW_User_Companies_ID = @Company_ID) 
	 AS [Orders Pending],

	(SELECT Sum(OC.Qty) 
	 FROM AO_Order_Candidates OC 
	 WHERE OC.AP_Products_ID =  @AP_Products_ID ) 
	 AS [Shopping List Qty], 

	(SELECT SUM(oc.Qty)
     FROM AO_Order_Candidates oc
     WHERE oc.AP_Products_ID = @AP_Products_ID) AS [Shopping List Qty],

	P.Service_Level AS [Service Level]

FROM AP_Products P
WHERE P.AP_Products_ID = @AP_Products_ID AND 
	P.AW_User_Companies_ID = @Company_ID













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--------------------------------------------------------------------------------------------
--sp_AO_Get_Last_14_Week_Sales
--Version 1.0
--Thu 12 Apr 2001
--------------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE  PROCEDURE sp_AO_Select_Product_Sales
   @ProductID int
AS
DECLARE @now float, @then float, @start_Date datetime, @end_date datetime, @end_week_no int    --output

--//set end date to today
SET @now = convert(float,(getdate()))

--//if today is not a Sunday
IF datepart(dw,convert(float,(getdate()))) <> 1
    --//set end date to last Sunday
    SET @now = convert(float,(getdate()) - (datepart(dw,convert(float,(getdate())))) - 1)

--//set the week number (from 01/01/1900) for the end date
SET @end_week_no = CONVERT(int, @now) / 7

--//go back 14 weeks (98 days) from the end date
SET @then = @now - 175

SET @end_date = CONVERT(datetime,(CONVERT(int,@now)))
SET @start_date = CONVERT(datetime,(CONVERT(int,@then)))

SELECT
  CONVERT(int, Date_Captured) / 7 as WeekNo,    --CONVERT(int, Date_Captured + 1) / 7 as WeekNo,
  SUM(quantity) as Ball1, 0 as Ball2 
FROM  AS_Transaction_Details
WHERE AP_Products_ID = @ProductID and
      Date_Captured > @start_date and
      Date_captured <= @end_date
GROUP BY CONVERT(int, Date_Captured) / 7
ORDER BY WeekNo DESC

RETURN @end_week_no







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Product_Search_Lups
--Purpose       :Supplier & Product Lookups
--Functionality :
--Parameters    :	
--Date          :2002/01/20
--Authors       :TB
--Version       :1.0.0
--MODS          :23/09/02 - Inserted check if Slu_AW_Active_ID = 1 in @Option = 1
--              :           to SELECT ONLY Active Suppliers
--              :           This sp used in Purchase Orders & Stock Adjustments
--              :28/09/03 - Added Users in option 7
--              :01/10/03 - Added ALL Suppliers (not only ACTIVE ones) in option 8
--              :13/10/03 - Added Connection Manager (Remote Access) in option 9
--              :08/01/04 - Added Stock Adjustment Types in option 10
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Select_Product_Search_Lups]
    (
    	@Option int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    BEGIN

    	IF @Option = 1    --> Supplier
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name ASC
    	ELSE 
    	IF @Option = 2    --> Manufacturer
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			  [Description] AS [Manufacturer] 
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 3    --> Type
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			  [Description] AS [Type] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 4    --> Group
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			  [Description] AS [Group] 
    		FROM Lup_AP_Product_Groups	
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 5    --> Department
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			  [Description] AS [Department] 
    		FROM Lup_AP_Product_Departments
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 6    --> Location
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			  [Description] AS [Location] 
    		FROM Lup_AP_Product_Locations
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 7    --> Users
          	SELECT AW_Users_ID as [ID],
--                   ISNULL(Surname, '') + ISNULL(', ' + FirstName, '') AS [User]
                   ISNULL(FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
            FROM AW_Users 
            ORDER BY [User]
        ELSE
    	IF @Option = 8    --> ALL Suppliers
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY Supplier_Name ASC
        ELSE
    	IF @Option = 9    --> Connection Manager (Remote Access)
    		SELECT AW_Remote_Access_ID AS [ID],
    			   NodeName AS [Originator] 
    		FROM AW_Remote_Access
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY NodeName ASC
        ELSE
    	IF @Option = 10    --> Stock Adjustment Types
    		SELECT Sys_AP_Adjustment_Types_ID AS [ID],
    			   [Description] AS [Type] 
    		FROM Sys_AP_Adjustment_Types
        ELSE
    	IF @Option = 11    --> Product Bins
    		SELECT Lup_AP_Product_Bins_ID AS [ID],
    			   [Description] AS [Bin] 
    		FROM Lup_AP_Product_Bins


    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Product_Suppliers
--Purpose       :Supplier Catalog - Products
--Functionality :
--Parameters    :
--Date          :2001/12/13
--Authors       :TB
--Version       :1.0.0
--MODS          :20/06/02 - Changed column order and added [Std GP%]
--              :07/07/03 - Added Average Cost
--              :18/12/04 - Added ORDER p.[Description]
--2004.3.8      :07/11/07 - Changed AP_Products JOIN to INNER from LEFT to eliminate
--              :           redundant AP_Products_Suppliers joins
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Select_Product_Suppliers
    (
        @SuppliersID int ,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT
        ps.AP_Products_Suppliers_ID AS [ID],
        ps.AP_Products_ID AS [Product ID],
        p.[Description] AS [Product],
        p.Product_Code AS [Product Code],
        p.Manufacturer_Code AS [Manuf Code],
        p.Manufacturer_Description AS [Manuf Description],
        p.On_Hand AS [On Hand],
        p.Last_Cost AS [Last Cost],
        p.Average_Cost AS [Avg Cost],
        p.Price1_Price1 AS [Price1],
        CASE WHEN p.Price1_Price1 <> 0
             THEN CONVERT(money,(((p.Price1_Price1 - p.Last_Cost) / p.Price1_Price1) * 100))
             ELSE 0.00
             END AS [Std GP%],
        p.Price1_Price2 AS [Price2],
        p.Price2_Price1 AS [Prev Price1],
        p.Price1_Price2 AS [Prev Price2],
        p.Sales_Order_Reserved AS [S/O Res],
        p.Job_Reserved AS [Job Res],
        p.Quote_Reserved AS [Quote Res],
        p.Last_Sale_Date AS [Last Sale],
        ps.AO_Suppliers_ID AS [FK ID], 
        ps.Lead_Time AS [LT Days], 
        ps.Start_Date AS [Start Date], 
        ps.Slu_AW_Active_ID AS [Active] 
    FROM AP_Products_Suppliers ps
        INNER JOIN AP_Products p 
            ON ps.AP_Products_ID = p.AP_Products_ID
    WHERE ps.AO_Suppliers_ID = @SuppliersID AND
    	  ps.AW_User_Companies_ID = @CompanyID
    ORDER BY p.[Description]

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE  PROCEDURE sp_AO_Select_Products
   @CompanyID int, 
   @Choice int,
   @Value int
AS
   IF @Choice = 0
      Select p.AP_Products_ID as ID, p.Description  , p.Service_Level as [Reorder Level],
          p.Max_Order_Qty as [Reorder Qty]
      FROM AP_Products p  
      WHERE p.AP_Products_ID in (SELECT distinct td.AP_Products_ID 
                                 FROM AS_Transaction_Details td WHERE td.ap_Products_ID = p.AP_Products_ID) 
         AND p.AW_User_Companies_ID = 1

   ELSE
   IF @Choice = 1
      Select top 20 Percent AP_Products_ID as ID, Description, Service_Level as [Reorder Level],
         Max_Order_Qty as [Reorder Qty] FROM AP_Products WHERE AW_User_Companies_ID = @CompanyID 
   ELSE
   IF @Choice = 2
      Select AP_Products_ID as ID, Description  , Service_Level as [Reorder Level],
         Max_Order_Qty as [Reorder Qty] FROM AP_Products WHERE  Lup_AP_Product_Types_ID = @Value
   ELSE
   IF @Choice = 3
      Select AP_Products_ID as ID, Description  , Service_Level as [Reorder Level],
         Max_Order_Qty as [Reorder Qty] FROM AP_Products WHERE  Lup_AP_Product_Groups_ID = @Value
   ELSE
   IF @Choice = 4
      Select AP_Products_ID as ID, Description , Service_Level as [Reorder Level],
         Max_Order_Qty as [Reorder Qty]  FROM AP_Products WHERE  Lup_AP_Product_Departments_ID = @Value
   ELSE
   IF @Choice = 5
      Select p.AP_Products_ID as ID, p.Description , p.Service_Level as [Reorder Level],
         p.Max_Order_Qty as [Reorder Qty]  FROM AP_Products p
               JOIN AP_Products_Suppliers s ON p.AP_Products_ID = s.AP_Products_ID 
         WHERE  s.AO_Suppliers_ID = @Value
   ELSE
   IF @Choice = 6
      Select AP_Products_ID as ID, Description , Service_Level as [Reorder Level],
         Max_Order_Qty as [Reorder Qty]  FROM AP_Products WHERE  Lup_AP_Product_Locations_ID = @Value
   ELSE
   IF @Choice = 7
      Select AP_Products_ID as ID, Description , Service_Level as [Reorder Level],
         Max_Order_Qty as [Reorder Qty]  FROM AP_Products WHERE  Lup_AP_Product_Manufacturers_ID = @Value









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-----------------------------------------------------------------------------
--Description   :sp_AO_Select_Products_For_PickList
--Purpose       :Select all Products for the Picklist
--Functionality :
--Parameters    :
--Date          :2001/12/22
--Authors       :TB
--Version       :1.0.0
--MODS          :01/09/04 - Added ISNULL validation to prevent NULL value error
--              :           in UI Picklist field data conversions (T2K m.o.)
-----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Products_For_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AP_Products_ID AS [ID],
           ISNULL(Product_Code, '') AS [Code],
           ISNULL([Description], '') AS [Product]
	FROM AP_Products
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--EXEC sp_AO_Select_Products_With_Sales 1, '2003/01/01 00:00:01', '2003/08/01 23:59:59'

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Products_With_Sales
--Purpose       :Selects products for inventory replenishment with attributes:
--              :    Conditional upon:
--              :    1.    Product has sales
--              :    2.    Product has stock
--              :    3.    MSL <> 0
--              :    4.    MIN <> 0
--              :    5.    MAX <> 0
--              :    6.    Product has Outstanding Orders (possibly NEW product)
--              :    7.    Product is ACTIVE
--Functionality :Uses TABLE datatype
--Date          :2003/09/29
--Authors       :TB
--Version       :19/10/03 - Added NEW temp table method. Drops execution time
--              :           from 4 minutes to 5 seconds
--              :23/10/03 - Modified to use TABLE datatype instead of a #TempTable
--              :           and now selects ORDERS from SALES instead of SALES
--              :           from ORDERS which improves execution speed a further 2x
--              :23/11/07 - Added EXCLUDE NON-STOCK items
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Select_Products_With_Sales
    (
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime
    )
AS

SET NOCOUNT ON

---------------------------------------------
--> NEW 23/10/03 using TABLE datatype
---------------------------------------------
    DECLARE @ActiveProducts table
                (
                    [AP_Products_ID] int
                )

    INSERT INTO @ActiveProducts
    SELECT DISTINCT d.AP_Products_ID
    FROM AS_Transaction_Details d
        INNER JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AW_User_Companies_ID = 1 AND
          d.Slu_AW_Active_ID = 1 AND
          p.Slu_AW_YesNo_Non_Stock_Item = 0 AND
          dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT od.AP_Products_ID
    FROM AO_Order_Details od
        INNER JOIN AO_Orders oh
            ON od.AO_Orders_ID = oh.AO_Orders_ID
        INNER JOIN AP_Products p
            ON od.AP_Products_ID = p.AP_Products_ID
    WHERE oh.AW_User_Companies_ID = 1 AND
          oh.Slu_AW_Active_ID = 1 AND
          p.Slu_AW_YesNo_Non_Stock_Item = 0 AND
          oh.Date_Ordered IS NOT NULL AND
          oh.Complete <> 1 AND
          ISNULL(od.Order_Qty, 0) +
          ISNULL(od.Back_Order_Qty, 0) -
          ISNULL(od.Received_Qty, 0) > 0 AND
          dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AP_Products
    WHERE AW_User_Companies_ID = 1 AND
          Slu_AW_Active_ID = 1 AND
          Slu_AW_YesNo_Non_Stock_Item = 0 AND
          (
              On_Hand <> 0 OR
              Min_Stock_Level <> 0 OR
              Min_Order_Qty <> 0 OR
              Max_Order_Qty <> 0
          )


    SELECT DISTINCT AP_Products_ID
    FROM @ActiveProducts
    ORDER BY AP_Products_ID



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Purchase_Order_Data
--Purpose       :Gets data for Purchase Order Print
--Date          :2002/02/10
--Authors       :TB
--Version       :1.0.0
--MODS		    :11/11/02 - Added fields: Branch, Salesperson (Rep)
--              :06/11/03 - Replaced Lup_AW_Branch_Codes with AW_Remote_Access
--              :08/11/03 - Get Billing and Delivery addresses from AW_Remote_Access
--              :09/11/03 - Added [Credit Terms], [Supplier No], [Supplier Acct No],
--              :           [DeliveryMethod], and [OrdersURL]
--              :27/09/04 - Added selective Billing Delivery Addresses from Remote Access
--              :           or Company Catalog dependant upon value of Remote Access
--              :           Billing_Name or Delivery_Name value
--2004.3.2      :03/09/06 - Reset to fetch Billing Address from the Order
--2004.3.4      :13/12/06 - Added fetch Product_Code/Description from AP_Products
--              :           if Manufacturer Code/Description data not available
--V6.0	RL	2014-09-18	:Added Default Message To Report
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Purchase_Order_Data]
    (
    	@OrdersID int
    )
AS

SET NOCOUNT ON

    DECLARE @SuppliersID int,
    		@CompanyID int,
            @RemoteAccessID int,
    		@Billing_Name varchar(50),
    		@Billing_Address1 varchar(40),
    		@Billing_Address2 varchar(40),
    		@Billing_Address3 varchar(40),
    		@Billing_Post_Code varchar(10),
    		@Billing_TelNo varchar(16),
    		@Billing_FaxNo varchar(16),
    		@Billing_VATNo varchar(16),
    		@Billing_RegNo varchar(16),
    		@Delivery_Name varchar(50),
    		@Delivery_Address1 varchar(40),
    		@Delivery_Address2 varchar(40),
    		@Delivery_Address3 varchar(40),
    		@Delivery_Post_Code varchar(10),
    		@Default_Message varchar(500)


	SELECT @SuppliersID = AO_Suppliers_ID,
		   @CompanyID = AW_User_Companies_ID,
           @RemoteAccessID = AW_Remote_Access_ID
	FROM AO_Orders 
	WHERE AO_Orders_ID = @OrdersID

	SET @Default_Message = ''
	SELECT @Default_Message = ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtPODocumentText'

    SELECT @Billing_Name = ISNULL(Billing_Name, ''),
           @Billing_Address1 = ISNULL(Billing_Address1, ''),
           @Billing_Address2 = ISNULL(Billing_Address2, ''),
           @Billing_Address3 = ISNULL(Billing_Address3, ''),
           @Billing_Post_Code = ISNULL(Billing_Post_Code, ''),
           @Billing_TelNo = ISNULL(Billing_TelNo, ''),
           @Billing_FaxNo = ISNULL(Billing_FaxNo, ''),
           @Billing_VATNo = ISNULL(Billing_VATNo, ''),
           @Billing_RegNo = ISNULL(Billing_RegNo, ''),
           @Delivery_Name = ISNULL(Delivery_Name, ''),
           @Delivery_Address1 = ISNULL(Delivery_Address1, ''),
           @Delivery_Address2 = ISNULL(Delivery_Address2, ''),
           @Delivery_Address3 = ISNULL(Delivery_Address3, ''),
           @Delivery_Post_Code = ISNULL(Delivery_Post_Code, '')
    FROM AW_Remote_Access
    WHERE AW_Remote_Access_ID = @RemoteAccessID


	SELECT @OrdersID AS [OrderID],
            S.Supplier_Name AS [Supp Name],	
    		S.Post_Box AS [Supp PostBox],
    		S.Post_Office AS [Supp PostOffice],
    		S.Post_Code AS [Supp PostCode],
    		S.Supplier_Telephone AS [Supp TelNo],
    		S.Supplier_Fax AS [Supp FaxNo],
    		S.Tax_Number AS [Supp TaxNo],
            O.Supplier_Rep AS [Rep],

--     		B.Billing_Name AS [Co Name],
--     		B.Billing_Address1 AS [Co Address1],
--     		B.Billing_Address2 AS [Co Address2],
--     		B.Billing_Address3 AS [Co Address3],
--     		B.Billing_Post_Code	AS [Co PostCode],
--     		B.Billing_TelNo AS [Co TelNo],
--     		B.Billing_FaxNo AS [Co FaxNo],
--     		B.Billing_VATNo AS [Co TaxNo],
--     		B.Billing_RegNo AS [Co RegNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Name
                 ELSE B.Billing_Name
            END AS [Co Name],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Address1
                 ELSE B.Billing_Address1
            END AS [Co Address1],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Address2
                 ELSE B.Billing_Address2
            END AS [Co Address2],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Address3
                 ELSE B.Billing_Address3
            END AS [Co Address3],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Post_Code
                 ELSE B.Billing_Post_Code
            END	AS [Co PostCode],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_TelNo
                 ELSE B.Billing_TelNo
            END AS [Co TelNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_FaxNo
                 ELSE B.Billing_FaxNo
            END AS [Co FaxNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_VATNo
                 ELSE B.Billing_VATNo
            END AS [Co TaxNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_RegNo
                 ELSE B.Billing_RegNo
            END AS [Co RegNo],


    		O.Date_Ordered AS [Date Ordered],
    		O.Order_Number AS [Order Number],
    		O.Our_Ref AS [Our Ref],
    		O.Supplier_Reference AS [Supp Ref],

--------------------------------------------------------------------
--2004.3.2  03/09/06 - Reset to fetch Billing Address from the Order
--------------------------------------------------------------------
            O.Send_To_Address AS [Del Name],
            O.Delivery_Addr1 AS [Del Addr1],
            O.Delivery_Addr2 AS [Del Addr2],
            O.Delivery_Addr3 AS [Del Addr3],
            O.Postal_Code AS [Del PostCode],

--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Name
--                  ELSE O.Send_To_Address
--             END AS [Del Name],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Address1
--                  ELSE O.Delivery_Addr1
--             END AS [Del Addr1],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Address2
--                  ELSE O.Delivery_Addr2
--             END AS [Del Addr2],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Address3
--                  ELSE O.Delivery_Addr3
--             END AS [Del Addr3],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Post_Code
--                  ELSE O.Postal_Code
--             END	AS [Del PostCode],
--------------------------------------------------------------------

    	    OD.AO_Order_Details_ID AS [ID],

--    		P.Manufacturer_Code [Product Code],
            CASE WHEN RTRIM(LTRIM(ISNULL(P.Manufacturer_Code, ''))) = ''
                 THEN P.Product_Code
                 ELSE P.Manufacturer_Code
            END AS [Product Code],

--    		P.Manufacturer_Description [Product Desc],
            CASE WHEN RTRIM(LTRIM(ISNULL(P.Manufacturer_Description, ''))) = ''
                 THEN P.Description
                 ELSE P.Manufacturer_Description
            END AS [Product Desc],

    		(OD.Order_Qty + OD.Back_Order_Qty) AS [QTY] ,
    		OD.Unit_Price AS [Unit Price],
    		OD.Trade_Discount_Amount AS [Trade Disc],
    		OD.Rebate_Discount_Amount AS [Rebate Disc],
    		OD.Other_Discount_Amount AS [Other Disc],	
    		(((OD.Order_Qty + OD.Back_Order_Qty) * OD.Unit_Price) - OD.Trade_Discount_Amount - OD.Rebate_Discount_Amount - OD.Other_Discount_Amount) AS SubTotal,
            OD.Net_Amount AS [Net Amount],
    		OD.Tax_Amount AS [Tax Amount],
    		OD.Total_Cost AS [Total Cost],
            T.[Description] AS [Credit Terms],
            S.Supplier_Number AS [Supplier No], 
            S.Old_Code AS [Supplier Acct No], 
            S.Sys_AO_Delivery_Methods_ID AS [DeliveryMethod],
            S.Orders_URL AS [OrdersURL],
            @Default_Message As [DefaultMessage]
	FROM AO_Orders O
        LEFT JOIN AO_Suppliers S 
			ON O.AO_Suppliers_ID = S.AO_Suppliers_ID 
		INNER JOIN AO_Order_Details OD
			ON O.AO_Orders_ID = OD.AO_Orders_ID 
		INNER JOIN AP_Products P 
			ON OD.AP_Products_ID = P.AP_Products_ID
        LEFT JOIN AW_Remote_Access B
            ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
        LEFT JOIN Slu_AW_Credit_Terms T
            ON S.Slu_AW_Credit_Terms_ID = T.Slu_AW_Credit_Terms_ID
	WHERE O.AO_Orders_ID = @OrdersID   

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--Description   : sp_AO_Select_Purchases_Transactions
--Purpose       : Selects the Transaction History for the specified suplier
--Functionality :
--Parameters    : @Suppliers_ID
--Date          : 2001/06/19
--Authors       : Charl
--Version       : 1.0.0

CREATE    Procedure sp_AO_Select_Purchases_Transactions
(
    @Suppliers_ID int ,
	@CompanyID int 
)

AS
    SET NOCOUNT ON
   
	SELECT PT.AO_Transactions_ID AS [ID], 
		PT.AO_Suppliers_ID AS [FK ID], 
		PT.Supplier_Reference AS [Supplier Ref], 
		PT.Sys_AW_Transaction_Types_ID AS [Transaction_Type_ID], 
		LupTT.[Description] AS [Transaction Type],
		PT.Document_Number AS [Invoice No], 
		PT.Document_Date AS [Invoice Date], 
		PT.AO_GRV_ID AS [GRV ID], 
		PT.Trade_Discount_Total AS [Trade Disc],
		PT.Rebate_Discount_Total AS [Rebate Disc],
		PT.Other_Discount_Total AS [Other Disc],
		PT.Net_Amount AS [Net], 
		PT.Total_Tax_Amount AS [Tax], 
		PT.Total_Amount AS [Total], 
		PT.Date_Captured AS [Date Captured], 
		PT.[User_ID] AS [User ID], 
		PT.AW_User_Companies_ID AS [Company ID], 
		PT.Slu_AW_Active_ID AS Active 
	FROM AO_Transactions PT LEFT JOIN Sys_AW_Transaction_Types LupTT
	ON PT.Sys_AW_Transaction_Types_ID = LupTT.Sys_AW_Transaction_Types_ID
	WHERE AO_Suppliers_ID = @Suppliers_ID AND
		PT.AW_User_Companies_ID = @CompanyID

	SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------
--Description   :sp_AO_Select_Purchases_Transactions
--Purpose       :Selects the Transactions for the specified GRV
--Functionality :
--Parameters    :
--Date          :2001/06/19
--Authors       :TB
--Version       :1.0.0
----------------------------------------------------------------------------

CREATE            Procedure sp_AO_Select_Purchases_Transactions_For_GRV
    (
        @GRV_ID int,
    	@Company_ID int 
    )

AS
    SET NOCOUNT ON
   
	SELECT PT.AO_Transactions_ID AS [ID], 
		PT.AO_Suppliers_ID AS [FK ID], 
		PT.Supplier_Reference AS [Supplier Ref], 
		PT.Sys_AW_Transaction_Types_ID AS [Transaction_Type_ID], 
		LupTT.[Description] AS [Transaction Type],
		PT.Document_Number AS [Invoice No], 
		PT.Document_Date AS [Invoice Date], 
		PT.AO_GRV_ID AS [GRV ID], 
		PT.Trade_Discount_Total AS [Trade Disc],
		PT.Rebate_Discount_Total AS [Rebate Disc],
		PT.Other_Discount_Total AS [Other Disc],
		PT.Net_Amount AS [Net], 
		PT.Total_Tax_Amount AS [Tax], 
		PT.Total_Amount AS [Total], 
		PT.Date_Captured AS [Date Captured], 
		PT.[User_ID] AS [User ID], 
		PT.AW_User_Companies_ID AS [Company ID], 
		PT.Slu_AW_Active_ID AS Active 
	FROM AO_Transactions PT
        LEFT JOIN Sys_AW_Transaction_Types LupTT
            ON PT.Sys_AW_Transaction_Types_ID = LupTT.Sys_AW_Transaction_Types_ID
	WHERE PT.AO_GRV_ID = @GRV_ID AND
          PT.AW_User_Companies_ID = @Company_ID

	SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Select_ReceivedCRV_Details
--Purpose       :Fetches Product Details for a selected CRV
--Functionality :SELECT 
--Parameters    :@AO_GRV_ID
--Date          :2015/04/14
--Authors       :RL
--MODS          :
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_ReceivedCRV_Details]
    (
    	@GRV_ID int
    )

AS

	SELECT AO_GRV_Details_ID AS [ID],
		GRVD.AO_GRV_ID AS [FK ID],
		GRVD.AP_Products_ID AS [Products ID],
		P.[Description] AS [Product],
		P.Product_Code AS [Code],
		GRVD.Qty AS [Qty],
		GRVD.Qty_Returned AS [Qty Returned],
		GRVD.Qty_Sold AS [Qty Sold],	
		GRVD.Qty_Left AS [Qty Left],	
		GRVD.Unit_Price AS [Unit Price],
		GRVD.Trade_Discount_Amount AS [Trade Disc],
		GRVD.Rebate_Discount_Amount AS [Rebate Disc],
		GRVD.Other_Discount_Amount AS [Other Disc],
		GRVD.Net_Amount AS [Net],
		GRVD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
		TC.[Description] AS [Tax Code],
		GRVD.Tax_Amount AS [Tax],
		GRVD.Total_Cost AS [Total Cost],
		GRVD.Date_Captured AS [Date Captured],
		GRVD.[User_ID] AS [User ID],
		GRVD.AW_User_Companies_ID AS [Company],
--		GRVD.Slu_AW_Active_ID AS [Active]
		ACT.[Description] AS [Active]
	FROM AO_GRV_Details GRVD
        LEFT JOIN AP_Products P
	        ON GRVD.AP_Products_ID  = P.AP_Products_ID 
    	LEFT JOIN Sys_AW_Tax_Codes TC
            ON GRVD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
    	LEFT JOIN Slu_AW_Active ACT
            ON GRVD.Slu_AW_Active_ID = ACT.Slu_AW_Active_ID
	WHERE GRVD.AO_GRV_ID = @GRV_ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--------------------------------------------------------------------------------
--Description   :sp_AO_Select_ReceivedGRV_Details
--Purpose       :Fetches Product Details for a selected GRV
--Functionality :SELECT 
--Parameters    :@AO_Orders_ID
--Date          :2001/10/02
--Authors       :TB
--MODS          :
--2004.3.8      :30/05/08 - Added [Code] field
--------------------------------------------------------------------------------

CREATE    Procedure sp_AO_Select_ReceivedGRV_Details
    (
    	@GRV_ID int
    )

AS

	SELECT AO_GRV_Details_ID AS [ID],
		GRVD.AO_GRV_ID AS [FK ID],
		GRVD.AP_Products_ID AS [Products ID],
		P.[Description] AS [Product],
		P.Product_Code AS [Code],
		GRVD.Qty AS [Qty],	
		GRVD.Unit_Price AS [Unit Price],
		GRVD.Trade_Discount_Amount AS [Trade Disc],
		GRVD.Rebate_Discount_Amount AS [Rebate Disc],
		GRVD.Other_Discount_Amount AS [Other Disc],
		GRVD.Net_Amount AS [Net],
		GRVD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
		TC.[Description] AS [Tax Code],
		GRVD.Tax_Amount AS [Tax],
		GRVD.Total_Cost AS [Total Cost],
		GRVD.Date_Captured AS [Date Captured],
		GRVD.[User_ID] AS [User ID],
		GRVD.AW_User_Companies_ID AS [Company],
--		GRVD.Slu_AW_Active_ID AS [Active]
		ACT.[Description] AS [Active]
	FROM AO_GRV_Details GRVD
        LEFT JOIN AP_Products P
	        ON GRVD.AP_Products_ID  = P.AP_Products_ID 
    	LEFT JOIN Sys_AW_Tax_Codes TC
            ON GRVD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
    	LEFT JOIN Slu_AW_Active ACT
            ON GRVD.Slu_AW_Active_ID = ACT.Slu_AW_Active_ID
	WHERE GRVD.AO_GRV_ID = @GRV_ID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Received_CRV
--Purpose       :Fetches all CRV that have already been received for the specified supplier 
--Functionality :SELECT 
--Parameters    :@Supplier_ID
--Date          :2015/03/25
--Authors       :RL
--MODS          :
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_Received_CRV]
    (
    	@SupplierID int = 0,
    	@Company_ID int			
    )

AS

	BEGIN
	
		SELECT AO_GRV_ID AS [ID],
    			Sys_AW_Transaction_Types_ID,
    			AO_Suppliers_ID AS [Suppliers ID],
    			AO_Orders_ID AS [Order],
                AO_GRV_ID AS [CRV],
    			Date_Received AS [Date Received],
    			Delivery_Note_Number AS [Del Note No],
    			Supplier_Reference AS [Suppliers Ref],
    			Trade_Discount_Total AS [Trade Disc],
    			Rebate_Discount_Total AS [Rebate Disc],
    			Other_Discount_Total AS [Other Disc],
    			Net_Amount AS [Net],
    			Total_Tax_Amount AS [Tax],
    			Total_Amount AS [Total],
    			Date_Captured AS [Date Captured],
    			[User_ID] AS [User ID],
    			AW_User_Companies_ID AS [Company],
    			Slu_AW_Active_ID AS [Active]
		FROM AO_GRV g
		WHERE AO_Suppliers_ID = @SupplierID AND
			Sys_AW_Transaction_Types_ID = 31 AND
			AW_User_Companies_ID = @Company_ID
		ORDER BY AO_GRV_ID DESC
		
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Received_GRV
--Purpose       :Fetches all GRV that have already been received for the specified supplier 
--Functionality :SELECT 
--Parameters    :@Supplier_ID
--Date          :2001/10/02
--Authors       :TB
--MODS          :
--2004.3.8      :30/05/08 - Added [GRV] field
--              :30/05/08 - Renamed [Orders ID] field to [Order]
--V6.2	RL	2016-07-07	:Added order by GRV_ID Descending
--------------------------------------------------------------------------------

CREATE Procedure [sp_AO_Select_Received_GRV]
    (
    	@SupplierID int = 0,
    	@Company_ID int			
    )

AS

	BEGIN
	
		SELECT AO_GRV_ID AS [ID],
    			Sys_AW_Transaction_Types_ID,
    			AO_Suppliers_ID AS [Suppliers ID],
    			AO_Orders_ID AS [Order],
                AO_GRV_ID AS [GRV],
    			Date_Received AS [Date Received],
    			Delivery_Note_Number AS [Del Note No],
    			Supplier_Reference AS [Suppliers Ref],
    			Trade_Discount_Total AS [Trade Disc],
    			Rebate_Discount_Total AS [Rebate Disc],
    			Other_Discount_Total AS [Other Disc],
    			Net_Amount AS [Net],
    			Total_Tax_Amount AS [Tax],
    			Total_Amount AS [Total],
    			Date_Captured AS [Date Captured],
    			[User_ID] AS [User ID],
    			AW_User_Companies_ID AS [Company],
    			Slu_AW_Active_ID AS [Active]
		FROM AO_GRV g
		WHERE AO_Suppliers_ID = @SupplierID AND
			Sys_AW_Transaction_Types_ID = 19 AND
			AW_User_Companies_ID = @Company_ID
		ORDER BY AO_GRV_ID DESC
		
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-- ???? REDUNDANT ????

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Remittance_Advice_Report_Data
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2001/10/11
--Authors       :TB
--Version       :1.0.0
--MODS          :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Remittance_Advice_Report_Data

    (
    	@Choice tinyint,
    	@Suppliers_ID int = null,
    	@Company_ID int
    )

-- @Choice Values -------------------------------------------------------------
-- 1 => All Suppliers
-- 2 => Specific Supplier
-- 3 => Supplier PickList
-- 4 => Supplier Ageing (All Suppliers)
-------------------------------------------------------------------------------

AS

SET NOCOUNT ON

    DECLARE @Now datetime, 
    		@D1 dateTime, 
    		@D2 datetime, 
    		@D3 datetime, 
    		@D4 datetime, 
    		@D5 datetime, 
    		@D6 datetime, 
    		@D7 datetime
    
--     		@Suppliers_ID int,
--     		@Company_ID int,
--     		@Choice int

    BEGIN 
    
    	SET @Now = getdate()
    
    -- 	SET @Suppliers_ID = 2
    -- 	SET @Company_ID = 1
    -- 	SET @Choice = 1
    
    	EXEC  sp_AW_Period_Procedures_Select
                        @Now,
                        @D1 OUTPUT,
                        @D2 OUTPUT,
                        @D3 OUTPUT,
                        @D4 OUTPUT,
                        @D5 OUTPUT,
                        @D6 OUTPUT,
                        @D7 OUTPUT,
                        4,            -- 4 = Supplier    (4 ??????????????????????????)
                        @Company_ID
    
    -- @Choice = 1 --------------------------------------------------------------------------------------
    
    	IF @Choice = 1
    		BEGIN
    			SELECT AOT.AO_Transactions_ID AS [ID],
    				AOT.AO_Suppliers_ID,
    				S.Supplier_Name,
    				S.Post_Box,
    				S.Post_Office,
    				S.Post_Code,
    				S.Supplier_Telephone,
    				S.Supplier_Fax,
    				S.Tax_Number,
    				AOT.Document_Date,
    				AOT.Document_Number	,
    				AWTT.[Description] ,
    				AOT.Total_Amount,
    				AOT.To_Be_Paid_Amount,
    				AOT.Remittance_Balance,
    			
    				A.[Current] ,
    				A.[30 Days],
    				A.[60 Days],
    				A.[90 Days],
    				A.[120 Days],
    				A.[150 Days],
    				A.[180+ Days]
    			
    			FROM AO_Transactions AOT LEFT JOIN AO_Suppliers S
    				ON AOT.AO_Suppliers_ID = S.AO_Suppliers_ID LEFT JOIN dbo.fn_AO_Supplier_Ageing_Non_Grouped_ALL_Suppliers(@Now, @D1,@D2,@D3,@D4,@D5,@D6,@D7,@Company_ID) a 
    				ON AOT.AO_Transactions_ID = a.SupplierID
    			LEFT JOIN Sys_AW_Transaction_Types AWTT 
    				ON AOT.Sys_AW_Transaction_Types_ID = AWTT.Sys_AW_Transaction_Types_ID
    			WHERE AOT.AO_Suppliers_ID in (SELECT DISTINCT AO_Suppliers_ID
    									  FROM AO_Transactions 
    									  WHERE To_Be_Paid = 1 AND 
    										To_Be_Paid_Amount <> 0 AND							
    										Sys_AW_Transaction_Types_ID = 8 AND
    										AW_User_Companies_ID = @Company_ID)AND
    					AOT.To_Be_Paid = 1 AND 
    					AOT.To_Be_Paid_Amount <> 0 AND							
    					AOT.Sys_AW_Transaction_Types_ID = 8 AND
    					AOT.AW_User_Companies_ID = @Company_ID
    
    		END						
    
    -- @Choice = 2 --------------------------------------------------------------------------------------
    
    	ELSE
    	IF @Choice = 2
    		BEGIN
    			SELECT AOT.AO_Transactions_ID AS [ID],
    				AOT.AO_Suppliers_ID,
    				S.Supplier_Name,
    				S.Post_Box,
    				S.Post_Office,
    				S.Post_Code,
    				S.Supplier_Telephone,
    				S.Supplier_Fax,
    				S.Tax_Number,
    				AOT.Document_Date,
    				AOT.Document_Number	,
    				AWTT.[Description] ,
    				AOT.Total_Amount,
    				AOT.To_Be_Paid_Amount,
    				AOT.Remittance_Balance,
    			
    				A.[Current] ,
    				A.[30 Days],
    				A.[60 Days],
    				A.[90 Days],
    				A.[120 Days],
    				A.[150 Days],
    				A.[180+ Days]
    			
    			FROM AO_Transactions AOT LEFT JOIN AO_Suppliers S
    				ON AOT.AO_Suppliers_ID = S.AO_Suppliers_ID LEFT JOIN dbo.fn_AO_Supplier_Ageing_Non_Grouped(@Suppliers_ID,@Now, @D1,@D2,@D3,@D4,@D5,@D6,@D7) a 
    				ON AOT.AO_Transactions_ID = a.ID
    			LEFT JOIN Sys_AW_Transaction_Types AWTT 
    				ON AOT.Sys_AW_Transaction_Types_ID = AWTT.Sys_AW_Transaction_Types_ID
    			WHERE (AOT.AO_Suppliers_ID = @Suppliers_ID) AND
    					AOT.To_Be_Paid = 1 AND 
    					AOT.To_Be_Paid_Amount <> 0 AND							
    					AOT.Sys_AW_Transaction_Types_ID = 8 AND
    					AOT.AW_User_Companies_ID = @Company_ID
    
    		END	
    
    -- @Choice = 3 --------------------------------------------------------------------------------------
    	
    	ELSE
    	IF @Choice = 3
    		BEGIN
    			SELECT DISTINCT AO_Suppliers_ID
    			FROM AO_Transactions 
    			WHERE (To_Be_Paid = 1 AND 
    				To_Be_Paid_Amount <> 0 AND							
    				Sys_AW_Transaction_Types_ID = 8 AND
    				AW_User_Companies_ID = @Company_ID)
    		END
    
    -- @Choice = 4 --------------------------------------------------------------------------------------
    	
    	ELSE
    	IF @Choice = 4
    		BEGIN
    			SELECT A.SupplierID,
    				S.Supplier_Name,
    				Sum(A.[Current]) ,
    				Sum(A.[30 Days]),
    				Sum(A.[60 Days]),
    				Sum(A.[90 Days]),
    				Sum(A.[120 Days]),
    				Sum(A.[150 Days]),
    				Sum(A.[180+ Days])
    			
    			FROM dbo.fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers(@Now, @D1,@D2,@D3,@D4,@D5,@D6,@D7,@Company_ID) A LEFT JOIN AO_Suppliers S
    				ON A.SupplierID = S.AO_Suppliers_ID 
    			WHERE S.AW_User_Companies_ID = @Company_ID	
    			GROUP BY A.SupplierID,S.Supplier_Name
    		END
    
    END


	

		
		







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












--exec sp_AO_Select_Replenish_Order_Candidates 1

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Replenish_Order_Candidates
--Purpose       :Select Order Candidates in Inventory Manager
--Date          :2003/09/28
--Authors       :TB
--Version       :1.0.0
--MODS          :30/09/03 - Added 'Network_Identity_Number' input parameter
--              :02/10/03 - Added JOIN with AO_Suppliers and ORDER BY Supplier_Name
--              :05/10/03 - Updated to match AO_Order_Candidates_Temp table
--              :13/10/03 - Replaced Network_Identity_Number with AW_Remote_Access_ID
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AO_Select_Replenish_Order_Candidates
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT
        b.AO_Order_Candidates_ID AS [ID],
        a.AP_Products_ID as [ProductID],
        b.Ready AS [Order],
        b.AW_Remote_Access_ID AS [Originator],
        b.AO_Suppliers_ID as [Supplier],
        a.[Description] as [Product],
        a.Product_Code as [Code],
        ISNULL(a.On_Hand, 0) as [On Hand],
        b.Qty as [To Order],
        ISNULL(a.Price1_Price1, 0) AS [Selling],
        ISNULL(d.Trade_Disc_Perc, 0) AS [Disc %],
        ISNULL(b.Last_Cost, 0) AS [Cost],
        ISNULL(b.Last_Cost, 0) AS [Last Cost],
        ROUND(ISNULL(b.Qty, 0) * ISNULL(b.Last_Cost, 0), 2)  AS [Total Cost],
        ISNULL(a.Min_Stock_Level, 0) AS [MSL],
        ISNULL(a.Min_Order_Qty, 0) as [Min],
        ISNULL(a.Max_Order_Qty, 0) as [Max],
        a.Service_Level AS [SL],

--> On Order
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                 END
            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 = a.AP_Products_ID) as [O/S Ords],
--> Pending Orders
        (SELECT
            CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                 THEN 0
                 ELSE (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty))
                 END
            FROM AO_Order_Details od
                INNER JOIN AO_Orders o
                    ON od.AO_Orders_ID = o.AO_Orders_ID
            WHERE o.Date_Ordered IS NULL AND
                  od.AP_Products_ID = a.AP_Products_ID) AS [Pend Ords],

        ISNULL(Sales_Order_Reserved, 0) + ISNULL(Job_Reserved, 0) AS [Res],

--> Last Order Date
        (SELECT TOP 1 CONVERT(CHAR(10), Date_Ordered, 121)
            FROM AO_Order_Details od
                INNER JOIN AO_Orders o
                    ON od.AO_Orders_ID = o.AO_Orders_ID
            WHERE o.Date_Ordered IS NOT NULL AND
                  od.AP_Products_ID = a.AP_Products_ID
            ORDER BY Date_Ordered DESC) AS [Last Order],

        CONVERT(CHAR(10), a.Last_Sale_Date, 121) AS [Last Sale],
        b.Notes AS [Notes],
        b.Date_Captured AS [Captured],
        b.[User_ID] AS [User]
    FROM AP_Products a
        INNER JOIN AO_Order_Candidates b
            ON a.AP_Products_ID = b.AP_Products_ID
        LEFT JOIN AO_Suppliers c
            ON b.AO_Suppliers_ID = c.AO_Suppliers_ID
        INNER JOIN AP_Products_Suppliers d
            ON d.AP_Products_ID = b.AP_Products_ID AND
               d.AO_Suppliers_ID = b.AO_Suppliers_ID
    WHERE b.AW_User_Companies_ID = @CompanyID
    ORDER BY c.Supplier_Name, a.[Description]






SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Replenish_Order_Candidates_Temp
--Purpose       :Select Order Candidates Temp in Inventory Manager
--Date          :2003/09/28
--Authors       :TB
--MODS          :30/09/03 - Added 'Network_Identity_Number' input parameter
--              :02/10/03 - Added JOIN with AO_Suppliers and ORDER BY Supplier_Name
--              :02/10/03 - Removed JOIN with AO_Suppliers: rs not updatable
--              :13/10/03 - Replaced Network_Identity_Number with AW_Remote_Access_ID
--2004.4.8      :29/04/10 - Added @Option to Exclude products with negative On Hand quantity 
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Select_Replenish_Order_Candidates_Temp
    (
       	@CompanyID int,
        @Option tinyint = 0
    )

AS

SET NOCOUNT ON

    IF @Option = 0
        BEGIN
            SELECT
                AO_Order_Candidates_Temp_ID AS [ID],
                AP_Products_ID AS [ProductID],
                Order_Item AS [Order],
                AW_Remote_Access_ID AS [Originator],
                AO_Suppliers_ID AS [Supplier],
                Product_Description AS [Product],
                Product_Code as [Code],
                On_Hand AS [On Hand],
                Order_Qty AS [To Order],
                Selling AS [Selling],
                Trade_Discount AS [Disc %],
                Cost AS [Cost],
                Last_Cost AS [Last Cost],
                Total_Cost AS [Total Cost],
                Min_Stock_Level AS [MSL],
                Min_Order_Qty AS [Min],
                Max_Order_Qty AS [Max],
                Service_Level AS [SL],
                Outstanding_Order_Qty AS [O/S Ords],
                Pending_Order_Qty AS [Pend Ords],
                ISNULL(Sales_Order_Reserved, 0) + ISNULL(Job_Reserved, 0) AS [Res],
                CONVERT(CHAR(10), Last_Order_Date, 121) AS [Last Order],
                CONVERT(CHAR(10), Last_Sale_Date, 121) AS [Last Sale],
                Notes AS [Notes],
                Date_Captured AS [Captured],
                [User_ID] AS [User]
            FROM AO_Order_Candidates_Temp
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AO_Suppliers_ID, Product_Description
        END

    ELSE
        BEGIN
            SELECT
                AO_Order_Candidates_Temp_ID AS [ID],
                AP_Products_ID AS [ProductID],
                Order_Item AS [Order],
                AW_Remote_Access_ID AS [Originator],
                AO_Suppliers_ID AS [Supplier],
                Product_Description AS [Product],
                Product_Code as [Code],
                On_Hand AS [On Hand],
                Order_Qty AS [To Order],
                Selling AS [Selling],
                Trade_Discount AS [Disc %],
                Cost AS [Cost],
                Last_Cost AS [Last Cost],
                Total_Cost AS [Total Cost],
                Min_Stock_Level AS [MSL],
                Min_Order_Qty AS [Min],
                Max_Order_Qty AS [Max],
                Service_Level AS [SL],
                Outstanding_Order_Qty AS [O/S Ords],
                Pending_Order_Qty AS [Pend Ords],
                ISNULL(Sales_Order_Reserved, 0) + ISNULL(Job_Reserved, 0) AS [Res],
                CONVERT(CHAR(10), Last_Order_Date, 121) AS [Last Order],
                CONVERT(CHAR(10), Last_Sale_Date, 121) AS [Last Sale],
                Notes AS [Notes],
                Date_Captured AS [Captured],
                [User_ID] AS [User]
            FROM AO_Order_Candidates_Temp
            WHERE AW_User_Companies_ID = @CompanyID AND
                  On_Hand >= 0
            ORDER BY AO_Suppliers_ID, Product_Description
        END



SET NOCOUNT OFF

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Replenish_ReorderPoint
--Purpose       :Retrieves ReorderPoint (MSL) Qty to be ordered
--Date          :2003/09/30
--Authors       :TB
--Version       :1.0.0
--MODS:         :05/10/03 - Added @Option to insert ALL SCAN products
--2004.4.8      :29/04/10 - Added ISNULL validation in subquery to SUM values of
--              :           od.Order_Qty + od.Back_Order_Qty - od.Received_Qty
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AO_Select_Replenish_ReorderPoint_Qty

    (
        @Option tinyint,
        @CompanyID int,
        @ProductID int,
       	@SupplierID int OUTPUT,
    	@Qty decimal(9,3) OUTPUT
    )

AS

SET NOCOUNT ON


	DECLARE @ReturnCode tinyint

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)


    --> Insert ALL products
    IF @Option = 0
        BEGIN
            SELECT
                @Qty = ISNULL(Min_Stock_Level, 0) -
                          (ISNULL(On_Hand, 0) +
                           ISNULL((
                                SELECT ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)
                                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 = @ProductID
                                ), 0) ),
                @SupplierID = ISNULL(Default_Supplier_ID, 0)
            FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AP_Products_ID = @ProductID AND
                  Slu_AW_Active_ID = 1
        
            SET @ReturnCode = 1       -- 1 = Successful (True)
        
            RETURN @ReturnCode

        END

    --> Insert only products that need replenishing
    ELSE
    IF @Option = 1
        BEGIN
            SELECT
                @Qty = ISNULL(Min_Stock_Level, 0) -
                          (ISNULL(On_Hand, 0) +
                           ISNULL((
                                SELECT ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)
                                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 = @ProductID
                                ), 0) ),
                @SupplierID = ISNULL(Default_Supplier_ID, 0)
            FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AP_Products_ID = @ProductID AND
                  Slu_AW_Active_ID = 1 AND
                 (ISNULL(Min_Stock_Level, 0) -
                     (ISNULL(On_Hand, 0) +
                      ISNULL((
                           SELECT ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)
                           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 = @ProductID
                      ), 0))) > 0
        
        
            SET @ReturnCode = 1       -- 1 = Successful (True)
        
            RETURN @ReturnCode
    
        END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Supplier_Catalog
--Purpose       :Select ONE Supplier_ID 
--Date          :2002/02/27
--Authors       :TB
--Version       :1.0.0
--MODS          :15/08/02 - Added fields for Supplier Bank Details in Catalog
--              :09/10/03 - Added Sys_AO_Delivery_Methods_ID
--2004.3.8      :22/01/08 - Added Lup_AO_Supplier_Types_ID
--              :           and Lup_AO_Supplier_Groups_ID
--2004.4.7      :26/08/09 - Added Sys_AC_Account_Types_ID
--2004.4.9 RL   :2013-07-08 - Added AW_YesNo_Apply_Product_Levy
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_Supplier_Catalog]
    (
        @Supplier_ID int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

    SELECT
        AO_Suppliers_ID AS [ID], 
        Supplier_Name AS [Supplier Name], 
        Supplier_Number AS [Supplier No], 
        Old_Code AS [Old Supplier No], 
        Lup_AO_Purchase_Price_Types_ID AS [Purchase Price Type], 
        Use_Supplier_Discount_Defaults AS [Use_Supplier_Discount_Defaults],
        AW_Trade_Discount_Formula_ID AS [Trade Discount Formula],
        AW_Rebate_Discount_Formula_ID AS [Rebate Discount Formula],
        AB_Other_Discounts_Account_ID AS [Other Disc GL Account], 
        AB_Rebate_Discount_Account_ID AS [Rebate Disc GL Account], 
        Use_Other_Discount_Control_Acc AS [Use_Other_Discount_Control_Acc],
        Use_Rebate_Discount_Control_Acc AS [Use_Rebate_Discount_Control_Acc],
        Start_Date AS [Start Date], 
        Credit_Limit AS [Credit Limit], 
        Slu_AW_Credit_Terms_ID AS [Credit Terms], 
        Default_Settlement_Discount AS [Settlement Disc],
        Supplier_Contact AS [Contact Name], 
        Slu_AW_Active_ID AS [Active], 
        Sys_AC_Account_Types_ID AS [Account Types],
        Sys_AC_Account_Status_ID AS [Account Status], 
        Sys_AW_Tax_Codes_ID AS [Tax Code], 
        Tax_Number AS [Tax Number], 
        Notes AS [Notes],
        Post_Box AS [Post Box], 
        Post_Office AS [Post Office], 
        Post_Code AS [Post Code], 
        Street_Address AS [Street Address], 
        Suburb AS Suburb, 
        City AS City, 
        Street_Post_Code AS [Street Code], 
        Slu_AW_Countries_ID AS Country, 
        Supplier_Telephone AS [Tel No], 
        Contact_Cellphone AS [Contact Cell], 
        Supplier_Fax AS [Fax No], 
        Web_Site_URL AS [Web Site URL], 
        Orders_URL AS [Orders URL], 
        Sys_AO_Delivery_Methods_ID AS [Orders Delivery], 
        Email_Address AS [E-mail Address],
        Account_Balance AS [Account Balance], 
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company ID] ,
        Slu_AW_Active_ID AS [Status],
        Slu_AW_Banks_ID AS [Bank Name],
        Bank_Branch AS [Branch Name],
        Bank_Branch_Code AS [Branch Code],
        Account_Name AS [Account Name],
        Account_Number AS [Account Number],
        Lup_AO_Supplier_Types_ID AS [Supplier_Type],
        Lup_AO_Supplier_Groups_ID AS [Supplier_Group],
        AW_YesNo_Apply_Product_Levy As [Apply_Product_Levy]
    FROM AO_Suppliers 
    WHERE AO_Suppliers_ID = @Supplier_ID AND 
    	  AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Supplier_Orders
--Purpose       :
--Date          :2002/01/17
--Authors       :TB
--Version       :1.0.0
--MODS          :06/11/03 - Replaced Lup_AW_Branch_Codes with AW_Remote_Access
-------------------------------------------------------------------------------

CREATE           Procedure sp_AO_Select_Supplier_Orders
    (
        @Suppliers_ID int 
    )

AS

SET NOCOUNT ON


    SELECT
        AO_Orders_ID AS [ID], 
        AO_Suppliers_ID AS [FK ID], 
        Order_Number AS [Order No], 
        Order_Date AS Date, 
        Version AS Version, 
        AW_Remote_Access_ID AS Branch, 
        Supplier_Rep AS [Supplier Rep], 
        Supplier_Type AS [Supplier Type], 
        Date_Ordered AS [Date Ordered], 
        Confirmation AS Confirmed, 
        Confirmation_Date AS [Confirm Date], 
        Our_Ref AS [Our Ref], 
        Supplier_Reference AS [Supplier Ref], 
        Order_Total AS [Order Total], 
        Invoice_Type AS [Invoice Type], 
        Invoice_Total AS [Invoice Total], 
        Admin_Fee AS [Admin Fee], 
        --Discount_Total AS [Discount Total], 
        Tax_Total AS [Tax Total], 
        Delivery_Addr1 AS [Delivery Addr 1], 
        Delivery_Addr2 AS [Delivery Addr 2], 
        Delivery_Addr3 AS [Delivery Addr 3], 
        Postal_Code AS [Postal Code], 
        Slu_AW_Active_ID AS Active 
    FROM AO_Orders 
    WHERE AO_Suppliers_ID = @Suppliers_ID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Supplier_Payment_Detail
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2001/12/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Supplier_Payment_Detail
    (
        @Supplier_ID int,
        @Company_ID int 
    )

AS

SET NOCOUNT ON


	SELECT AO_Suppliers_ID AS [ID], 
           Supplier_Name, 
           Default_Settlement_Discount, 
           Slu_AW_Credit_Terms_ID 
	FROM AO_Suppliers
	WHERE AO_Suppliers_ID = @Supplier_ID AND
		  AW_User_Companies_ID = @Company_ID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers
--Functionality :Returns Supplier Info
--Parameters    :
--Date          :2013/10/28
--Authors       :RL
--Version       :5.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Suppliers]
AS

SET NOCOUNT ON

	SELECT AO_Suppliers_ID AS [ID],
		   Supplier_Name AS [Supplier_Name],
		   a.Description AS [Supplier_Status],
		   uc.Company_Name As [Company_Name]
	FROM AO_Suppliers s
	INNER JOIN Slu_AW_Active a
	ON s.Slu_AW_Active_ID = a.Slu_AW_Active_ID
	Inner Join AW_User_Companies uc
	On s.AW_User_Companies_ID = uc.AW_User_Companies_ID 	
	ORDER BY Supplier_Name ASC

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_As_Lup
--Purpose       :Returns all Suppliers as a Lookup
--Functionality :
--Parameters    :
--Date          :2003/12/15
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Select_Suppliers_As_Lup
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AO_Suppliers_ID AS [ID],
    	   Supplier_Name AS [Supplier]
    FROM AO_Suppliers
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY [Supplier]


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_As_Lup_Extended
--Purpose       :Returns all Supplier Accounts as a Lookup PLUS street address
--Date          :2009/09/16
--Authors       :TB
--MODS          :
--------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Suppliers_As_Lup_Extended
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AO_Suppliers_ID AS [ID],
    	   ISNULL(Supplier_Name, '') +
           ISNULL(', ' + Street_Address, '') +
           ISNULL(', ' + Suburb, '') +
           ISNULL(', ' + City, '') AS [Supplier]
    FROM AO_Suppliers
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY [Supplier]


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_For_PickList
--Purpose       :Select all suppliers for the Picklist
--Functionality :
--Parameters    :
--Date          :2002/01/11
--Authors       :TB
--Version       :1.0.0
--MODS          :04/11/02 - Commented out a version that return a PickList of
--              :           ONLY Suppliers with OUTSTANDING transactions
------------------------------------------------------------------------------

CREATE      Procedure sp_AO_Select_Suppliers_For_PickList
    (
    	@CompanyID as int
    )

AS

SET NOCOUNT ON
	
	SELECT AO_Suppliers_ID AS [ID],
    		ISNULL(Supplier_Name, '') AS [Supplier],
            ISNULL(Supplier_Number, '') AS [Number]
	FROM AO_Suppliers 
	WHERE AW_User_Companies_ID = @CompanyID
	ORDER BY Supplier_Name ASC



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_From_Order_Candidates
--Purpose       :Returns a lup of all the suppliers in Order_Candidates 
--Functionality :
--Parameters    :
--Date          :2002/01/16
--Authors       :TB 
--MODS          :
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AO_Select_Suppliers_From_Order_Candidates
    (
    	@Company_ID int
    )

AS

SELECT AO_Suppliers_ID AS [ID],
	Supplier_Name
FROM AO_Suppliers 
WHERE AO_Suppliers_ID IN 
			(SELECT AO_Suppliers_ID 
			 FROM AO_Order_Candidates 
			 WHERE AW_User_Companies_ID = @Company_ID)
  AND AW_User_Companies_ID = @Company_ID



 













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_From_Orders
--Purpose       :Returns rs of all the suppliers in Outstanding Orders
--Functionality :
--Parameters    :
--Date          :2002/01/16
--Authors       :TB 
--MODS          :
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Suppliers_From_Orders
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    SELECT AO_Suppliers_ID AS [ID],
    	   Supplier_Name
    FROM AO_Suppliers 
    WHERE AO_Suppliers_ID IN (SELECT AO_Suppliers_ID 
                              FROM AO_Orders 
                              WHERE Complete = 0 AND 
                                    AW_User_Companies_ID = @Company_ID) AND
          AW_User_Companies_ID = @Company_ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_From_Orders
--Purpose       :Returns rs of all the suppliers in Outstanding Orders
--Functionality :
--Parameters    :
--Date          :2002/01/16
--Authors       :TB 
--MODS          :
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Suppliers_From_Pended_Orders]
    (
    	@Company_ID int
    )
AS

SET NOCOUNT ON

    SELECT AO_Suppliers_ID AS [ID],
    	   Supplier_Name
    FROM AO_Suppliers 
    WHERE AO_Suppliers_ID IN (SELECT AO_Suppliers_ID 
                              FROM AO_Orders 
                              WHERE Complete = 0 AND 
                                    AW_User_Companies_ID = @Company_ID AND
                                    Date_Ordered IS NULL) 
    AND AW_User_Companies_ID = @Company_ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   :sp_AO_Select_Suppliers_Per_Product
--Purpose       :Use this sp to return a list of the suppliers for the Selected product
--Functionality :SELECT and a Join
--Parameters    :@AP_Products_ID
--Date          : 2001/04/12
--Authors       : Charl
--Version       : 1.0.0

CREATE  Procedure sp_AO_Select_Suppliers_Per_Product
(
    @AP_Products_ID int,
	@Company_ID int
)

AS
    SET NOCOUNT ON

SELECT AP_Products_Suppliers_ID AS [ID],
	PS.AO_Suppliers_ID AS [Suppliers_ID],
	S.Supplier_Name	AS [Supplier]

FROM AP_Products_Suppliers PS LEFT JOIN AO_Suppliers S
ON PS.AO_Suppliers_ID = S.AO_Suppliers_ID
WHERE PS.AP_Products_ID = @AP_Products_ID AND 
	PS.AW_User_Companies_ID = @Company_ID
	







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Top_Supplier_ID
--Purpose       :Select FIRST or LAST Supplier ID
--Functionality :
--Date          :2002/09/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Select_Top_Supplier_ID
	(
    	@CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AO_Suppliers_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AO_Suppliers_ID
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AO_Suppliers_ID
        END

    ELSE

--> Get the LAST AO_Suppliers_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AO_Suppliers_ID
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AO_Suppliers_ID DESC
        END

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-----------------------------------------------------------------------------
--Description   :sp_AO_Select_Uninvoiced_GRV
--Functionality :Returns Uninvoiced Grv's  
--Parameters    : 
--Date          :2002/02/17
--Authors       :TB
--Version       :1.0.0
--Mods			:14/08/02 - Added @TranType to distinguish between
--              :             Goods RECEIVED and Goods RETURNED vouchers
-----------------------------------------------------------------------------


CREATE    PROCEDURE sp_AO_Select_Uninvoiced_GRV
    (
    	@Supplier_ID int,
    	@CompanyID int,
        @TranType tinyint        -- 19=Goods Received, 20=Goods Returned
    )

AS

    BEGIN
    
    	SELECT AO_GRV_ID AS [ID],
                AO_Suppliers_ID AS [SupplierID],
                AO_Orders_ID AS [Order ID],
                Date_Received AS [Date Received],
                Delivery_Note_Number AS [Delivery Note],
                Supplier_Reference AS [Supplier Reference],
                Trade_Discount_Total AS [Trade Discount],
                Rebate_Discount_Total AS [Rebate Discount],
                Other_Discount_Total AS [Other Discount],
                Net_Amount AS [Net],
                Total_Tax_Amount AS [Tax],
                Total_Amount AS [Total]
    	FROM AO_GRV
    	WHERE AO_GRV_ID NOT IN (SELECT DISTINCT AO_GRV_ID 
                                FROM AO_Transactions 
                                WHERE AO_GRV_ID IS NOT NULL) AND 
     		  AO_Suppliers_ID = @Supplier_ID AND
    		  AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID = @TranType
    
    
    END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






------------------------------------------------------------------------------
--Description   :sp_AO_Select_User
--Purpose       :Returns the User's first and last name 
--Functionality :
--Parameters    :	
--Date          :2002/04/09
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE  Procedure sp_AO_Select_User
    (
    	@UserID int
    )

AS

SET NOCOUNT ON

    SELECT
        AW_Users_ID AS [ID],
        FirstName AS [FirstName],
        Surname AS [Surname]
    FROM AW_Users
    WHERE AW_Users_ID = @UserID

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Journals_Insert_Update
--Purpose       :Posts Supplier Journals
--Parameters    :
--Date          :2002/07/28
--Authors       :TB
--Mods          :28/10/02 - Added insert MonthID and YearsID to AO_Transactions
--              :12/02/03 - reverse the SIGN for the double-entry to the
--              :           Creditors Control as if seen from the perspective
--              :           of the SELECTED GL Account (if amount is debit, then
--              :           DEDIT the SELECTED GL Account and CREDIT Creditors)
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :04/03/04 - Fixed double-entry allocation amounts
--              :06/04/04 - Renamed @FKID as @SupplierID
--              :06/04/04 - Moved creating the narration BEFORE the INSERT of the
--              :           GL Transaction for the SELECTED GL Account
--              :17/04/04 - Moved reversing the sign for Creditors Control posting
--              :           from before AO_Transactions insert
--              :           to before Creditors Control insert
--              :03/12/04 - Fixed @RefNo written to SELECTED GL Account as NULL,
--              :           renamed GL account vars, and removed trailing comments
--              :           Moved GL Insert below AO_Transactions INSERT because @ID
--              :           was ONLY CREATED AFTER AO_Transactions INSERT !!!!!!!
--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 TRANSACTION Save_Supplier_Journal !!!
--              :30/04/08 - Replaced @ID with @New_Supplier_Journal_ID
--2004.5.2      :11/07/11 - Fixed Supplier_Name field length to new size 40 !!!!
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AO_Supplier_Journals_Insert_Update
	(
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(20),
		@Amount money,
		@Tax money,
		@Total money,
		@GLAccountID int,
		@MonthsID int, 
		@YearsID int,
		@TransactionType int,
		@SupplierID int,
		@CompanyID int,
		@UserID int
	)
AS     

SET NOCOUNT ON

    DECLARE @New_Supplier_Journal_ID int,
            @GLControlAccountID int,
            @GLTranTypeID tinyint,
            @Narration varchar(50),
            @SupplierName varchar(30),

            --> 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)


    ---------------------------------------------------------------
    --> 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
    ---------------------------------------------------------------


    IF @TransactionType = 10
        BEGIN
            SET @GLTranTypeID = 7    --Sys_AB_Transaction_Types_ID - Accounts Payable - Journal
        END


    SELECT @SupplierName = LEFT(Supplier_Name, 30)
    FROM AO_Suppliers
    WHERE AO_Suppliers_ID = @SupplierID

    SET @Narration = LEFT(RTRIM(LTRIM(@SupplierName)), 25) + ' - ' + LEFT(@Comment, 20)


    -------------------------------------------------------------------------------
    --> UPDATE SUPPLIER TRANSACTIONS
    -------------------------------------------------------------------------------
    BEGIN TRAN Save_Supplier_Journal
    	BEGIN	


        	INSERT AO_Transactions 
        		(
        	         Document_Number,
        		     Document_Date,
                     Slu_AW_Months_ID,
                     Slu_AW_Years_ID,
        	         Net_Amount ,
        	         Total_Tax_Amount,
        	         Total_Amount,
        	         AB_Accounts_ID ,
        	         Comment,
        	         Sys_AW_Transaction_Types_ID ,
        	         AO_Suppliers_ID,	
        		     AW_User_Companies_ID,
        		     [User_ID]
        		)
        	VALUES
        		(
        			@RefNo,
        			@Date,
                    @MonthsID,
                    @YearsID,
        			@Amount,
        			@Tax,
        			@Total,
        			@GLAccountID,
        			@Comment,
        			@TransactionType,
        			@SupplierID,
        			@CompanyID,
        			@UserID
        		)
        
        	SET @New_Supplier_Journal_ID = Scope_Identity()
        
        
        --> UPDATE Supplier Account Balance
        	UPDATE AO_Suppliers
            SET Account_Balance = Account_Balance + @Total
            WHERE AO_Suppliers_ID = @SupplierID
        
        
            ---------------------------------------------------------------
            --> 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
                        (
                            @SupplierID,
                            @New_Supplier_Journal_ID,
--                            @AO_GRV_ID,
                            @MonthsID,
                            @YearsID,
                            @Current_Month_ID,
                            @Current_Year_ID,
                            @LastME_Month_ID,
                            @LastME_Year_ID,
                            @UserID,
                            @CompanyID
                        )
                END
            ---------------------------------------------------------------
        
        
            -------------------------------------------------------------------------------
            --> INSERT a GL Transaction for the SELECTED GL Account
            -------------------------------------------------------------------------------
        	EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    @GLTranTypeID,
                    @GLAccountID,
                    @Date,
                    @RefNo,
                    @MonthsID,
                    @YearsID,
                    @New_Supplier_Journal_ID,
                    @Amount,
                    @UserID,
                    @CompanyID
        
        
            -------------------------------------------------------------------------------
            --> Seen from the perspective of the SELECTED GL Account,
            -->     reverse the SIGN for the double-entry to the Creditors Control
            -------------------------------------------------------------------------------
            SET @Total = -@Total
            -------------------------------------------------------------------------------
        
        
            -------------------------------------------------------------------------------
            --> INSERT CREDITORS CONTROL
            -------------------------------------------------------------------------------
            SELECT @GLControlAccountID = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 201	
        	
            --> INSERT a GL Transaction for the Trade Creditors Control Account
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    @GLTranTypeID,
                    @GLControlAccountID,
                    @Date,
                    @RefNo,
                    @MonthsID,
                    @YearsID,
                    @New_Supplier_Journal_ID,
                    @Total,
                    @UserID,
                    @CompanyID
        		
            -------------------------------------------------------------------------------
            --> UPDATE V.A.T. CONTROL
            -------------------------------------------------------------------------------
        	IF @Tax <> 0 
        		BEGIN
        			SELECT @GLControlAccountID = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 401	
        			
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            @GLTranTypeID,
                            @GLControlAccountID,
                            @Date,
                            @RefNo,
                            @MonthsID,
                            @YearsID,
                            @New_Supplier_Journal_ID,
                            @Tax,
                            @UserID,
                            @CompanyID
        		END



        END

    COMMIT TRAN Save_Supplier_Journal


SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Lumpsum_GL_Clearing_Insert
--Purpose       :NEW Supplier Lumpsum Payment Creditors Clearing insert
--Functionality :INSERTS GL Transactions for:
--              :        1. Trade Creditors Control,
--              :        2. Trade Creditors Payment Clearing,
--              :        3. Settlement Discount Received
--              :        4. V.A.T. on Settlement Discount
--Date          :2009/09/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AO_Supplier_Lumpsum_GL_Clearing_Insert
    (
    	@Payment_Total money,
        @Company_Banks_ID int,
    	@Transaction_Type_ID tinyint,
    	@Month tinyint, 
    	@Year int,
    	@AO_Transactions_ID int,
    	@UserID int,
        @CompanyID int,
        @TranRefNo varchar(20),
        @Comment varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE
        @Supplier_ID int,
        @Supplier_Name varchar(25),
        @DocDate datetime,
        @GLControlAccount int,
        @Narration varchar(50),
        @Settlement_VAT money,
        @Settlement_Ex_VAT money,
        @TaxRate decimal(5,2)


	SELECT @Supplier_ID = AO_Suppliers_ID,
           @DocDate = Document_Date
	FROM AO_Transactions
	WHERE AO_Transactions_ID = @AO_Transactions_ID
	
	SELECT @Supplier_Name = LEFT(RTRIM(LTRIM(ISNULL(Supplier_Name, ''))), 25) 
	FROM AO_Suppliers
	WHERE AO_Suppliers_ID = @Supplier_ID

	SET @Narration = LEFT(('Lumpsum ' + @Supplier_Name + ' ' + @Comment), 50)


	BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

		BEGIN TRANSACTION

-------------------------------------------------------------------------------
    --Debit Trade Creditors Control
-------------------------------------------------------------------------------
            BEGIN
    
                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 201    --Trade Creditors Control
    
            --> Create GL TRANSACTION: DEBIT Creditors Control
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        8,                         --ABTranType = A/P - Payment
                        @GLControlAccount,         --@AB_Accounts_ID
                        @DocDate,                  --NEW
                        @TranRefNo,                --Next Payment Transaction Number
                        @Month,                    --@AW_Months_ID
                        @Year,                     --@AW_Years_ID
                        @AO_Transactions_ID,       --@Transaction_Ref
                        @Payment_Total,            --Invoices Total
                        @UserID,                   --@User_ID
                        @CompanyID                 --@Company_ID
    
            END

-------------------------------------------------------------------------------
    --Credit Trade Creditors Payment Clearing
-------------------------------------------------------------------------------
            BEGIN
    
                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 207    --Trade Creditors Payment Clearing

                --Reverse the SIGN opposite (DR or CR) to Trade Creditors entry 
                SET @Payment_Total = (@Payment_Total * -1)
    
            --> Create GL TRANSACTION: DEBIT Creditors Control
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        8,                         --ABTranType = AP Payment
                        @GLControlAccount,         --@AB_Accounts_ID
                        @DocDate,                  --NEW
                        @TranRefNo,                --Next Payment Transaction Number
                        @Month,                    --@AW_Months_ID
                        @Year,                     --@AW_Years_ID
                        @AO_Transactions_ID,       --@Transaction_Ref
                        @Payment_Total,            --Cheque Amount
                        @UserID,                   --@User_ID
                        @CompanyID                 --@Company_ID
    
            END

        COMMIT TRANSACTION

    END


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/26
--Authors       :TB
--MODS          :15/08/02 - Added @Choice=13 - Supplier Bank from Slu_AW_Banks
--              :29/08/02 - Removed ORDER BY [Description] in 8 = Credit Terms
--              :               This displays confusing ASCII Collating order
--              :28/10/02 - Added @Choice=14 - Months from Slu_AW_Months and
--              :               @Choice=15 - Years from Slu_AW_Years
--              :03/10/03 - Added @Choice 16 = Users and @Choice 17 = ALL Suppliers
--              :09/10/03 - Added @Choice 18 = Sys_AO_Delivery_Methods
--              :13/12/04 - Excluded Payment Method 11 and 13 from @Choice 11
--              :           Supplier Payment Methods
--2004.3.5      :01/05/07 - Added @Choice 19 = Supplier E-mail Address
--2004.3.8      :22/01/08 - Added @Choice 20 and 21 - Supplier Types and Groups
--2004.4.7      :26/08/09 - Added @Choice 22 - Account Type
--              :18/09/09 - Changed Option 11 and INCLUDED 'Debit Order' (Lombard)
--              :           and 'Credit Card' (TB)
--2004.5.9 RL   :2013-07-08 Added @Choice 23 = Apply Product Levy
--V6.2	RL	2015-06-10	:Added Supplier Consignment Transactions to options 31 and 32
------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Supplier_Lups]
    (
        @Choice int,
    	@CompanyID int = 1
    )
AS

SET NOCOUNT ON

    BEGIN
    --> 1 Purchase Price Types ID
    	IF @Choice = 1
			SELECT Lup_AO_Purchase_Price_Types_ID AS [ID], 
			      [Description] AS [Purchase Price Type] 
			FROM Lup_AO_Purchase_Price_Types
			WHERE AW_User_Companies_ID = @CompanyID
			ORDER BY [Description] ASC

    --> 2 Formulas
    	ELSE
    	IF @Choice = 2
    		SELECT AW_Formulas_ID AS [ID], 
    		      [Description] AS [Formulas] 
    		FROM AW_Formulas
    		WHERE AW_User_Companies_ID = @CompanyID
    		ORDER BY [Description] ASC

    --> 3 GL Accounts
    	ELSE 
    	IF @Choice = 3
    		SELECT AB_Accounts_ID AS [ID], 
    		      [Description] AS [GL Account] 
    		FROM AB_Accounts
    		WHERE AW_User_Companies_ID = @CompanyID
    		ORDER BY [Description] ASC
    	
    --> 4 Active
    	ELSE
    	IF @Choice = 4
    		SELECT Slu_AW_Active_ID AS [ID], 
    		      [Description] AS [Active] 
    		FROM Slu_AW_Active
    		ORDER BY [Description] ASC

    --> 5 Account Status
    	ELSE 
    	IF @Choice = 5
    		SELECT Sys_AC_Account_Status_ID AS [ID], 
    		      [Description] AS [Account Status] 
    		FROM Sys_AC_Account_Status
    		ORDER BY [Description] ASC
    	
    --> 6 Tax Codes
    	ELSE 
    	IF @Choice = 6
    		SELECT Sys_AW_Tax_Codes_ID AS [ID], 
    		      [Description] AS [Tax_Code] 
    		FROM Sys_AW_Tax_Codes
    		ORDER BY [Description] ASC
    	
    --> 7 Countries
    	ELSE 
    	IF @Choice = 7
    		SELECT Slu_AW_Countries_ID AS [ID], 
    		      [Description] AS [Country] 
    		FROM Slu_AW_Countries
    		ORDER BY [Description] ASC
    	
    --> 8 Credit Terms
    	ELSE
    	IF @Choice = 8
    		SELECT Slu_AW_Credit_Terms_ID AS [ID],
    		      [Description] As [Credit Terms] 
    		FROM Slu_AW_Credit_Terms
--    --> ORDER BY [Description] displays confusing ASCII Collating order
--    		ORDER BY [Description]  ASC
    
    --> 9 Actor2
    	ELSE
    	IF @Choice = 9	--'Actor2'
          	SELECT AW_Users_ID as ID,
                ISNULL(Firstname + ' ', '') + ISNULL(Surname, '') as [Actor2] 
        	FROM AW_Users 
        	WHERE AW_Users_ID <> 1
        	ORDER BY firstname,Surname ASC
    
    --> 10 Transaction Types
    	ELSE
    	IF @Choice = 10	
           	SELECT Sys_AW_Transaction_Types_ID as [ID], 
                  [Description] as [Transaction Type] 
        	FROM Sys_AW_Transaction_Types 
        	WHERE Sys_AW_Transaction_Types_ID = 6 OR
                  Sys_AW_Transaction_Types_ID = 8 OR
                  Sys_AW_Transaction_Types_ID = 9 OR
                  Sys_AW_Transaction_Types_ID = 10 OR
                  Sys_AW_Transaction_Types_ID = 12 OR
                  Sys_AW_Transaction_Types_ID = 31 OR	--V6.2 Consignment Transactions
                  Sys_AW_Transaction_Types_ID = 32		--V6.2 Consignment Transactions
            ORDER BY [Description] ASC
    
    --> 11 Payment Methods (from GL)
    	ELSE
    	IF @Choice = 11
--     		SELECT Sys_AW_Payment_Methods_ID as [ID],
--                 Description as [Description] 
--     		FROM Sys_AW_Payment_Methods 
--     		WHERE (Sys_AW_Payment_Methods_ID <> 4 AND 
--     			   Sys_AW_Payment_Methods_ID <> 5 AND
--     			   Sys_AW_Payment_Methods_ID <> 7 AND
--     			   Sys_AW_Payment_Methods_ID <> 8 AND
--     			   Sys_AW_Payment_Methods_ID <> 9 AND
--     			   Sys_AW_Payment_Methods_ID <> 10 AND
--     			   Sys_AW_Payment_Methods_ID <> 11 AND
--     			   Sys_AW_Payment_Methods_ID <> 13 )
--     		ORDER BY [Description] ASC 

    		SELECT Sys_AW_Payment_Methods_ID as [ID],
                   Description as [Description] 
    		FROM Sys_AW_Payment_Methods 
    		WHERE (Sys_AW_Payment_Methods_ID = 1 OR 
    			   Sys_AW_Payment_Methods_ID = 2 OR 
    			   Sys_AW_Payment_Methods_ID = 3 OR 
    			   Sys_AW_Payment_Methods_ID = 4 OR 
    			   Sys_AW_Payment_Methods_ID = 6 OR 
    			   Sys_AW_Payment_Methods_ID = 12)
    		ORDER BY [Description] ASC 
    
    --> 12 Company Bank Accounts
    	ELSE
    	IF @Choice = 12
    	   	SELECT AW_Company_Banks_ID as [ID],
                   Account_Name as [Account Name] 
    		FROM AW_Company_Banks
    		WHERE AW_User_Companies_ID = @CompanyID
    		ORDER BY Account_Name ASC

    --> 13 Supplier Bank Account
    	ELSE
    	IF @Choice = 13
    	   	SELECT Slu_AW_Banks_ID as [ID],
                  [Description] as [Bank Name] 
    		FROM Slu_AW_Banks
    		ORDER BY [Description]

        --> Months
    	ELSE
    	IF @Choice = 14
    		SELECT Slu_AW_Months_ID AS [ID],
                  [Description] AS [Months]
    		FROM Slu_AW_Months
    
    --> Years
    	ELSE 
    	IF @Choice = 15
    		SELECT Slu_AW_Years_ID AS [ID],
                  [Description] AS [Years]
    		FROM Slu_AW_Years

    --> Users
    	ELSE 
    	IF @Choice = 16
          	SELECT AW_Users_ID as [ID],
--                   ISNULL(Surname, '') + ISNULL(', ' + FirstName, '') AS [User]
                   ISNULL(FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
            FROM AW_Users 
            ORDER BY [User]
        ELSE

    --> ALL Suppliers
    	IF @Choice = 17    --> ALL Suppliers
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Supplier_Name ASC

    --> Purchase Order Delivery Methods
    	ELSE 
    	IF @Choice = 18
    		SELECT Sys_AO_Delivery_Methods_ID AS [ID], 
    		      [Description] AS [Delivery Method] 
    		FROM Sys_AO_Delivery_Methods
    		ORDER BY [Description] ASC

    --> Supplier E-mail Address
    	ELSE 
    	IF @Choice = 19
    		SELECT ISNULL(Email_Address, '') AS [Email] 
    		FROM AO_Suppliers
            WHERE AO_Suppliers_ID = @CompanyID

    --> Supplier Types
        ELSE
    	IF @Choice = 20
			SELECT Lup_AO_Supplier_Types_ID AS [ID], 
			      [Description] AS [Supplier_Type] 
			FROM Lup_AO_Supplier_Types
			WHERE AW_User_Companies_ID = @CompanyID
			ORDER BY [Description] ASC

    --> Supplier Groups
        ELSE
    	IF @Choice = 21
			SELECT Lup_AO_Supplier_Groups_ID AS [ID], 
			      [Description] AS [Supplier_Group] 
			FROM Lup_AO_Supplier_Groups
			WHERE AW_User_Companies_ID = @CompanyID
			ORDER BY [Description] ASC

	--> Account Types
        ELSE
        IF @Choice = 22
          	SELECT Sys_AC_Account_Types_ID AS [ID],
                  [Description] 
            FROM Sys_AC_Account_Types
            ORDER BY [Description]
            
	--> Apply Product Levy
		ELSE
        IF @Choice = 23    
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description] AS [Apply Product Levy]
            FROM Slu_AW_YesNo

    END 

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Payment
--Purpose       :Inserts a Supplier (Creditor) Payment
--Functionality :
--Parameters    :
--Date          :2002/01/07
--Authors       :TB
--Mods          :11/06/02 - Update Supplier Account_Balance with payment amount
--              :11/06/02 - Inserted Document_Number & Document_Date, fields
--              :11/07/02 - Reversed Document_Number & Document_Date fields (error)
--              :16/12/03 - Added @Month and @Year input parameters and Update/Insert
--              :16/12/03 - Added @GLCreditorsControl in payment transactions INSERT
--              :16/12/03 - Renamed @Number to @DocNumber and insert LEFT(20)
--              :18/03/04 - REMOVED replacing SOURCE transaction's Date_Captured
--              :           with Date of its Payment !!!!
--              :25/11/04 - Added @DateCaptured to ref a transaction's components
--              :25/11/04 - Added new field Tran_Ref_No in AO_Transaction_Payments
--              :           and AO_Transactions_Transactions to ref a Supplier PAYMENT
--              :           components using new @TranRefNo input parameter
--              :14/12/04 - Added new input parameters @Supplier_ID and @DateCaptured
--              :           to conform to new sp_AO_Supplier_Payment_Single
--              :14/12/04 - Added RETURN @PaymentTran_ID to pick up Payment TranDate in UI
--2004.3.2      :12/10/06 - Added @DatePaid input parameter to post as Document_Date
--2004.3.8      :30/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 - Replaced @Supplier_ID with @SupplierID
--              :                    @PaymentTran_ID with @New_Supplier_Payment_ID
--              :                    @Month with @MonthsID
--              :                    @Year with @YearsID
--              :                    @User_ID with @UserID
--              :                    @Company_ID with @CompanyID
--2004.4.6      :12/08/09 - Added @Comment parameter
--2004.5.2      :11/07/11 - Removed UNUSED DECLARE @SupplierName (varchar, 30) !!!!
-------------------------------------------------------------------------------

CREATE                 Procedure sp_AO_Supplier_Payment
    (
        @SupplierID int,
        @AO_Transactions_ID int,
        @Payment_Amount money,
        @To_Be_Paid bit,
        @Remit_Balance money,
        @TranType_ID int,
        @Payment_Method_ID int,
        @Company_Banks_ID int,
        @DocNumber varchar(20),
    	@MonthsID tinyint, 
    	@YearsID int,
        @UserID int,
        @CompanyID int,
        @TranRefNo varchar(20),
        @DateCaptured datetime,
        @DatePaid datetime,
        @Comment varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE @Source_AO_Transaction_ID int,
            @Destination_AO_Transaction_ID int,
            @New_Supplier_Payment_ID int,
            @Prev_Pmnt_Amount money,
            @New_Pmnt_Amount money,
            @GLCreditorsControl 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)


    ---------------------------------------------------------------
    --> 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
    ---------------------------------------------------------------


    SELECT @GLCreditorsControl = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 201    --Trade Creditors Control


    -----------------------------------------------------------
    BEGIN TRAN Supplier_Payment_Tran
    -----------------------------------------------------------

        BEGIN

            -----------------------------------------------------------
            -- UPDATE EACH AO_Transactions
            -----------------------------------------------------------
        	BEGIN	
        		SELECT @Prev_Pmnt_Amount = ISNULL(Payment_Amount, 0)
        		FROM AO_Transactions
        		WHERE AO_Transactions_ID = @AO_Transactions_ID 
        
        		SET @New_Pmnt_Amount = (@Prev_Pmnt_Amount + (@Payment_Amount * -1))
        
        		UPDATE AO_Transactions
        			SET To_Be_Paid = 0,
        				To_Be_Paid_Amount = 0,
        				Remittance_Balance = @Remit_Balance,
        				Payment_Amount = @New_Pmnt_Amount
        		WHERE AO_Transactions_ID = @AO_Transactions_ID 

        		SET @Source_AO_Transaction_ID = @AO_Transactions_ID
        	END

            -----------------------------------------------------------
            -- Inserts EACH Transaction as a Payment in AO Transactions
            -----------------------------------------------------------
        	BEGIN 
        		INSERT INTO AO_Transactions
        			(	
                        AO_Suppliers_ID,
                        AB_Accounts_ID,
                        Sys_AW_Transaction_Types_ID,
                        Supplier_Reference,
                        Document_Date,
                        Document_Number,
                        Slu_AW_Months_ID,
                        Slu_AW_Years_ID,
                        AO_GRV_ID,
                        Comment,
                        Total_Amount,
                        Payment_Amount,
                        [User_ID],
                        Date_Captured,
                        AW_User_Companies_ID
                    )
        		VALUES
                    (
                        @SupplierID,
                        @GLCreditorsControl,
                        @TranType_ID,
                        @TranRefNo,
                        @DatePaid,
                        LEFT(@DocNumber, 20),
                        @MonthsID,
                        @YearsID,
                        0,
                        LEFT(@Comment, 20),
                       (@Payment_Amount * -1),
                        @Payment_Amount,
                        @UserID,
                        @DateCaptured,
                        @CompanyID
                    )
        	
        		SELECT @New_Supplier_Payment_ID = Scope_Identity()

        		SET @Destination_AO_Transaction_ID = @New_Supplier_Payment_ID
        	END


            ---------------------------------------------------------------
            --> INSERT Supplier Transaction Log
            ---------------------------------------------------------------
            IF @TranGLPeriod <= @LastMEPeriod
                BEGIN
                    INSERT AO_Transactions_Log
                        (
                            AO_Suppliers_ID,
                            AO_Transactions_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
                        (
                            @SupplierID,
                            @New_Supplier_Payment_ID,
                            @MonthsID,
                            @YearsID,
                            @Current_Month_ID,
                            @Current_Year_ID,
                            @LastME_Month_ID,
                            @LastME_Year_ID,
                            @UserID,
                            @CompanyID
                        )
                END
            ---------------------------------------------------------------


            -----------------------------------------------------------
            --Insert Transaction XREF in AO_Transaction_Payments	
            -----------------------------------------------------------
        	BEGIN 
        		INSERT INTO AO_Transaction_Payments
        			(	
        				AO_Transactions_ID,
        				Sys_AW_Payment_Methods_ID,
        				AW_Company_Banks_ID,
        				Number,
        				Amount,
                        Tran_Ref_No,
        				Date_Captured,
                        [User_ID],
        				AW_User_Companies_ID
                    )
        		VALUES
                    (	
        				@New_Supplier_Payment_ID,
        				@Payment_Method_ID,
        				@Company_Banks_ID,
        				LEFT(@DocNumber, 20),
        				@Payment_Amount ,
                        @TranRefNo,
        				@DateCaptured,
                        @UserID,
        				@CompanyID
                    )
        	END

            -----------------------------------------------------------
            --Insert Payment XREF in AO_Transactions_Transactions
            -----------------------------------------------------------
        	BEGIN 
        		INSERT INTO AO_Transactions_Transactions
        			(	
        				Source_AO_Transactions_ID,
        				Destination_AO_Transactions_ID,
        				Amount,
                        Tran_Ref_No,
        				Date_Captured,
                        [User_ID],
        				AW_User_Companies_ID
                    )
        		VALUES
                    (	
        				@Source_AO_Transaction_ID,
        				@Destination_AO_Transaction_ID,
        				@Payment_Amount,
                        @TranRefNo,
        				@DateCaptured,
                        @UserID,
        				@CompanyID
                    )
        	END

            -----------------------------------------------------------
            --UPDATE Supplier Account Balance
            -----------------------------------------------------------
        	UPDATE AO_Suppliers
            SET Account_Balance = Account_Balance + (@Payment_Amount * -1)
            WHERE AO_Suppliers_ID = @SupplierID

        END


    -----------------------------------------------------------
    COMMIT TRAN Supplier_Payment_Tran
    -----------------------------------------------------------



    RETURN @New_Supplier_Payment_ID




SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Payment_GL_Clearing_Insert
--Purpose       :NEW Supplier Payment Creditors Clearing insert
--Functionality :INSERTS GL Transactions for:
--              :        1. Trade Creditors Control,
--              :        2. Trade Creditors Payment Clearing,
--              :        3. Settlement Discount Received
--              :        4. V.A.T. on Settlement Discount
--              :
--Date          :2002/07/21
--Authors       :TB
--MODS          :21/11/02 - Removed 'Supplier Payment: prefixed to GL Tran @Narration
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :16/12/03 - Changed @Month parameter from int to tinyint
--              :25/11/04 - Added new @TranRefNo input parameter to replace irrelevant
--              :           (last) @Supplier_Inv_No inserted into AB_Source_Ref
--              :           to XREF a Supplier PAYMENT in GL to its constituant parts
--              :14/12/04 - Appended ' Payment' to the GL @Narration
--2004.2.7      :01/04/06 - Changed GL TranType for Settlement AMOUNT and VAT
--              :           from 25 to 8 (AP Payment) for GL Popup
--              :01/04/06 - Changed GL Narration for each Settlement entry
--              :01/04/06 - Added TRIM(@Supplier_Name)
--2004.4.6      :12/08/09 - Added @Comment parameter
--2016.6.2	RL	:2016-08-04	:Changed Settlement discount from 8 to 25 ABTranType - AP Settlement
--							 So that it shows in its own section on TAX report
-------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AO_Supplier_Payment_GL_Clearing_Insert]
    (
    	@Invoices_Total money,
    	@Discount_Amount money,
    	@Payment_Total money,
        @Company_Banks_ID int,
    	@Transaction_Type_ID tinyint,
    	@Month tinyint, 
    	@Year int,
    	@AO_Transactions_ID int,
    	@UserID int,
        @CompanyID int,
        @TranRefNo varchar(20),
        @Comment varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE
        @Supplier_ID int,
        @Supplier_Name varchar(25),
        @DocDate datetime,
        @GLControlAccount int,
        @Narration varchar(50),
        @Settlement_VAT money,
        @Settlement_Ex_VAT money,
        @TaxRate decimal(5,2)


	SELECT @Supplier_ID = AO_Suppliers_ID,
           @DocDate = Document_Date
	FROM AO_Transactions
	WHERE AO_Transactions_ID = @AO_Transactions_ID
	
	SELECT @Supplier_Name = LEFT(RTRIM(LTRIM(ISNULL(Supplier_Name, ''))), 25) 
	FROM AO_Suppliers
	WHERE AO_Suppliers_ID = @Supplier_ID

	SET @Narration = LEFT(('Payment ' + @Supplier_Name + ' ' + @Comment), 50)


	BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

		BEGIN TRANSACTION

-------------------------------------------------------------------------------
    --Debit Trade Creditors Control
-------------------------------------------------------------------------------
            BEGIN
    
                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 201    --Trade Creditors Control
    
            --> Create GL TRANSACTION: DEBIT Creditors Control
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        8,                     --ABTranType = A/P - Payment
                        @GLControlAccount,     --@AB_Accounts_ID
                        @DocDate,              --NEW
                        @TranRefNo,            --Next Payment Transaction Number
                        @Month,                --@AW_Months_ID
                        @Year,                 --@AW_Years_ID
                        @AO_Transactions_ID,   --@Transaction_Ref
                        @Invoices_Total,       --Invoices Total
                        @UserID,               --@User_ID
                        @CompanyID             --@Company_ID
    
            END

-------------------------------------------------------------------------------
    --Credit Trade Creditors Payment Clearing
-------------------------------------------------------------------------------
            BEGIN
    
                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 207    --Trade Creditors Payment Clearing

                --Make the SIGN opposite (DR or CR) to Trade Creditors entry 
                SET @Payment_Total = (@Payment_Total * -1)
    
            --> Create GL TRANSACTION: DEBIT Creditors Control
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        8,                     --ABTranType = AP Payment
                        @GLControlAccount,     --@AB_Accounts_ID
                        @DocDate,              --NEW
                        @TranRefNo,            --Next Payment Transaction Number
                        @Month,                --@AW_Months_ID
                        @Year,                 --@AW_Years_ID
                        @AO_Transactions_ID,   --@Transaction_Ref
                        @Payment_Total,        --Cheque Amount
                        @UserID,               --@User_ID
                        @CompanyID             --@Company_ID
    
            END

-------------------------------------------------------------------------------
    --SETTLEMENT DISCOUNT RECEIVED
-------------------------------------------------------------------------------
            IF @Discount_Amount <> 0
            --> Update SETTLEMENT DISCOUNT RECEIVED & VAT
                BEGIN
    
                --> (NEW 21 JUL 2002) VAT ON SETTLEMENT DISCOUNT --------
                    --Get the Current Tax Rate
                    SELECT @TaxRate = ISNULL(Tax_Rate, 0)
                    FROM Sys_AW_Tax_Codes
                    WHERE Tax_Code = 'S'    --Standard (Current) rate (e.g. 14%)
                    
                    SET @Settlement_VAT = ROUND((@Discount_Amount * (@TaxRate / (100 + @TaxRate))) ,2)
                    SET @Settlement_Ex_VAT = (@Discount_Amount - @Settlement_VAT) 

                    --Changed the SIGN to opposite (DR or CR) in Back Office UI
--                     SET @Settlement_VAT = (@Settlement_VAT * -1)
--                     SET @Settlement_Ex_VAT = (@Settlement_Ex_VAT * -1)
                    
                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 205    --SETTLEMENT DISCOUNT RECEIVED

                    SET @Narration = LEFT((@Supplier_Name + ' - Settlement'), 50)

                --> Create GL TRANSACTION: CREDIT Settlement Discount Received
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            --V6.2	RL	2016-08-04	Changed to display in own section of TAX Report
                            25,                     --ABTranType AP Settlement
                            --8,                     --ABTranType = AP Payment
                            @GLControlAccount,     --@AB_Accounts_ID
                            @DocDate,              --NEW
                            @TranRefNo,            --Next Payment Transaction Number
                            @Month,                --@AW_Months_ID
                            @Year,                 --@AW_Years_ID
                            @AO_Transactions_ID,   --@Transaction_Ref
                            @Settlement_Ex_VAT,    --@Invoiced Amount
                            @UserID,               --@User_ID
                            @CompanyID             --@Company_ID
    
                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 401    --VAT Control

                    SET @Narration = LEFT((@Supplier_Name + ' - Settlement VAT'), 50)

                --> Create GL TRANSACTION: CREDIT VAT Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            --V6.2	RL	2016-08-04	Changed to display in own section of TAX Report
                            25,                     --ABTranType AP Settlement                            
                            --8,                     --ABTranType = AP Payment
                            @GLControlAccount,     --@AB_Accounts_ID
                            @DocDate,              --NEW
                            @TranRefNo,            --Next Payment Transaction Number
                            @Month,                --@AW_Months_ID
                            @Year,                 --@AW_Years_ID
                            @AO_Transactions_ID,   --@Transaction_Ref
                            @Settlement_VAT,       --@Invoiced Amount
                            @UserID,               --@User_ID
                            @CompanyID             --@Company_ID
    
                END

        COMMIT TRANSACTION

    END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Payment_Lumpsum
--Purpose       :Inserts a Supplier Lumpsum Payment
--Date          :2009/09/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AO_Supplier_Payment_Lumpsum
    (
        @SupplierID int,
        @Payment_Amount money,
        @DocNumber varchar(20),
    	@MonthsID tinyint, 
    	@YearsID int,
        @UserID int,
        @CompanyID int,
        @TranRefNo varchar(20),
        @DateCaptured datetime,
        @DatePaid datetime,
        @Comment varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE @NewPaymentID int,
            @GLCreditorsControl int,
            @TranTypeID tinyint,

            --> 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)


    ---------------------------------------------------------------
    --> 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
    ---------------------------------------------------------------


    SET @NewPaymentID = 0
    SET @TranTypeID = 12        --Supplier Payment = 12


    -----------------------------------------------------------
    BEGIN TRAN Supplier_Lumpsum_Payment
    -----------------------------------------------------------
        BEGIN
            SELECT @GLCreditorsControl = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 201    --Trade Creditors Control


    		INSERT INTO AO_Transactions
    			(	
                    AO_Suppliers_ID,
                    AB_Accounts_ID,
                    Sys_AW_Transaction_Types_ID,
                    Supplier_Reference,
                    Document_Date,
                    Document_Number,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    AO_GRV_ID,
                    Comment,
                    Total_Amount,
                    Payment_Amount,
                    Settlement_Discount,
                    [User_ID],
                    Date_Captured,
                    AW_User_Companies_ID
                )
    		VALUES
                (
                    @SupplierID,
                    @GLCreditorsControl,
                    @TranTypeID,
                    @TranRefNo,
                    @DatePaid,
                    LEFT(@DocNumber, 20),
                    @MonthsID,
                    @YearsID,
                    0,
                    LEFT(@Comment, 20),
                   (@Payment_Amount * -1),
                    0,
                    0,
                    @UserID,
                    @DateCaptured,
                    @CompanyID
                )

    		SELECT @NewPaymentID = Scope_Identity()


            ---------------------------------------------------------------
            --> INSERT Supplier Transaction Log
            ---------------------------------------------------------------
            IF @TranGLPeriod <= @LastMEPeriod
                BEGIN
                    INSERT AO_Transactions_Log
                        (
                            AO_Suppliers_ID,
                            AO_Transactions_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
                        (
                            @SupplierID,
                            @NewPaymentID,
                            @MonthsID,
                            @YearsID,
                            @Current_Month_ID,
                            @Current_Year_ID,
                            @LastME_Month_ID,
                            @LastME_Year_ID,
                            @UserID,
                            @CompanyID
                        )
                END

            -----------------------------------------------------------
            --UPDATE Supplier Account Balance
            -----------------------------------------------------------
        	UPDATE AO_Suppliers
            SET Account_Balance = Account_Balance + (@Payment_Amount * -1)
            WHERE AO_Suppliers_ID = @SupplierID
    
        END

    -----------------------------------------------------------
    COMMIT TRAN Supplier_Lumpsum_Payment
    -----------------------------------------------------------


    -----------------------------------------------------------
    --Moved RETURN here so that COMMIT can insert the tran
    -----------------------------------------------------------
    RETURN @NewPaymentID
    -----------------------------------------------------------



SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Payment_Single
--Purpose       :Inserts a SINGLE TRANSACTION as a Supplier (Creditor) Payment
--              :    vs. previously a transaction for each invoice
--              :        in sp_AO_Supplier_Payment
--              :NB - no GL or CASHBOOK transactions here
--Date          :2004/12/13
--Authors       :TB
--MODS          :19/12/04 - Added @Settlement_Disc input parameter and insert
--              :           aggregated Settlement amount into AO_Transactions
--2004.3.2      :12/10/06 - Added @DatePaid input parameter to post as Document_Date
--2004.3.8      :30/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 - Replaced @Supplier_ID with @SupplierID
--              :                    @PaymentTran_ID with @New_Supplier_Payment_ID
--              :                    @Month with @MonthsID
--              :                    @Year with @YearsID
--              :                    @User_ID with @UserID
--              :                    @Company_ID with @CompanyID
--2004.4.6      :12/08/09 - Added @Comment parameter
--2004.5.2      :11/07/11 - Removed UNUSED DECLARE @SupplierName (varchar, 30) !!!!
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AO_Supplier_Payment_Single
    (
        @SupplierID int,
        @New_Supplier_Payment_ID int,
        @AO_Transactions_ID int,
        @Payment_Amount money,
        @To_Be_Paid bit,
        @Remit_Balance money,
        @Settlement_Disc money,
        @Payment_Method_ID int,
        @Company_Banks_ID int,
        @DocNumber varchar(20),
    	@MonthsID tinyint, 
    	@YearsID int,
        @UserID int,
        @CompanyID int,
        @TranRefNo varchar(20),
        @DateCaptured datetime,
        @DatePaid datetime,
        @Option tinyint,
        @Comment varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE @Source_AO_Transaction_ID int,
            @Destination_AO_Transaction_ID int,
            @Prev_Pmnt_Amount money,
            @New_Pmnt_Amount money,
            @GLCreditorsControl int,
            @TranTypeID tinyint,

            --> 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)


    ---------------------------------------------------------------
    --> 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
    ---------------------------------------------------------------


    SET @TranTypeID = 12        --Supplier Payment = 12


    -----------------------------------------------------------
    BEGIN TRAN Supplier_Payment_Tran_Single
    -----------------------------------------------------------

        BEGIN

            -----------------------------------------------------------
            -- Inserts SINGLE Payment Transaction in AO Transactions
            -----------------------------------------------------------
            IF @Option = 1
            	BEGIN 
    
                    SELECT @GLCreditorsControl = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 201    --Trade Creditors Control
    
    
            		INSERT INTO AO_Transactions
            			(	
                            AO_Suppliers_ID,
                            AB_Accounts_ID,
                            Sys_AW_Transaction_Types_ID,
                            Supplier_Reference,
                            Document_Date,
                            Document_Number,
                            Slu_AW_Months_ID,
                            Slu_AW_Years_ID,
                            AO_GRV_ID,
                            Comment,
                            Total_Amount,
                            Payment_Amount,
                            Settlement_Discount,
                            [User_ID],
                            Date_Captured,
                            AW_User_Companies_ID
                        )
            		VALUES
                        (
                            @SupplierID,
                            @GLCreditorsControl,
                            @TranTypeID,
                            @TranRefNo,
                            @DatePaid,
                            LEFT(@DocNumber, 20),
                            @MonthsID,
                            @YearsID,
                            0,
                            LEFT(@Comment, 20),
                           (@Payment_Amount * -1),
                            @Payment_Amount,
                            @Settlement_Disc,
                            @UserID,
                            @DateCaptured,
                            @CompanyID
                        )
            	
            		SELECT @New_Supplier_Payment_ID = Scope_Identity()
    
    
                    ---------------------------------------------------------------
                    --> INSERT Supplier Transaction Log
                    ---------------------------------------------------------------
                    IF @TranGLPeriod <= @LastMEPeriod
                        BEGIN
                            INSERT AO_Transactions_Log
                                (
                                    AO_Suppliers_ID,
                                    AO_Transactions_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
                                (
                                    @SupplierID,
                                    @New_Supplier_Payment_ID,
                                    @MonthsID,
                                    @YearsID,
                                    @Current_Month_ID,
                                    @Current_Year_ID,
                                    @LastME_Month_ID,
                                    @LastME_Year_ID,
                                    @UserID,
                                    @CompanyID
                                )
                        END
                    ---------------------------------------------------------------
    
    
            	END
    
    
            -----------------------------------------------------------
            -- Inserts Payment XREF Transactions
            -----------------------------------------------------------
            ELSE
            IF @Option = 2
                BEGIN
    
    
                    SET @Destination_AO_Transaction_ID = @New_Supplier_Payment_ID
    
    
                    -----------------------------------------------------------
                    -- UPDATE EACH AO_Transactions
                    -----------------------------------------------------------
                	BEGIN	
                		SELECT @Prev_Pmnt_Amount = ISNULL(Payment_Amount, 0)
                		FROM AO_Transactions
                		WHERE AO_Transactions_ID = @AO_Transactions_ID 
                
                		SET @New_Pmnt_Amount = (@Prev_Pmnt_Amount + (@Payment_Amount * -1))
                
                		UPDATE AO_Transactions
                			SET To_Be_Paid = 0,
                				To_Be_Paid_Amount = 0,
                				Remittance_Balance = @Remit_Balance,
                				Payment_Amount = @New_Pmnt_Amount
                		WHERE AO_Transactions_ID = @AO_Transactions_ID 
        
                		SET @Source_AO_Transaction_ID = @AO_Transactions_ID
                	END
        
    
                    -----------------------------------------------------------
                    --Insert Transaction XREF in AO_Transaction_Payments	
                    -----------------------------------------------------------
                	BEGIN 
                		INSERT INTO AO_Transaction_Payments
                			(	
                				AO_Transactions_ID,
                				Sys_AW_Payment_Methods_ID,
                				AW_Company_Banks_ID,
                				Number,
                				Amount,
                                Tran_Ref_No,
                				Date_Captured,
                                [User_ID],
                				AW_User_Companies_ID
                            )
                		VALUES
                            (	
                				@New_Supplier_Payment_ID,
                				@Payment_Method_ID,
                				@Company_Banks_ID,
                				LEFT(@DocNumber, 20),
                				@Payment_Amount ,
                                @TranRefNo,
                				@DateCaptured,
                                @UserID,
                				@CompanyID
                            )        
                	END
        
                    -----------------------------------------------------------
                    --Insert Payment XREF in AO_Transactions_Transactions
                    -----------------------------------------------------------
                	BEGIN 
                		INSERT INTO AO_Transactions_Transactions
                			(	
                				Source_AO_Transactions_ID,
                				Destination_AO_Transactions_ID,
                				Amount,
                                Tran_Ref_No,
                				Date_Captured,
                                [User_ID],
                				AW_User_Companies_ID
                            )
                		VALUES
                            (	
                				@Source_AO_Transaction_ID,
                				@Destination_AO_Transaction_ID,
                				@Payment_Amount,
                                @TranRefNo,
                				@DateCaptured,
                                @UserID,
                				@CompanyID
                            )
                	END
        
                    -----------------------------------------------------------
                    --UPDATE Supplier Account Balance
                    -----------------------------------------------------------
                	UPDATE AO_Suppliers
                    SET Account_Balance = Account_Balance + (@Payment_Amount * -1)
                    WHERE AO_Suppliers_ID = @SupplierID
        
                END

        END

    -----------------------------------------------------------
    COMMIT TRAN Supplier_Payment_Tran_Single
    -----------------------------------------------------------


    -----------------------------------------------------------
    --Moved RETURN here so that COMMIT can insert the tran
    -----------------------------------------------------------
    IF @Option = 1
        RETURN @New_Supplier_Payment_ID
    -----------------------------------------------------------



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












--REDUNDANT SP 21/07/02

-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Payments_CB_And_GL_Insert
--Purpose       :Insert Supplier Payment into CB & GL
--Functionality :
--Parameters    :
--Date          :2002/01/07
--Authors       :TB
--Version       :1.0.0
--Mods          :08 JUN 02 - Added missing @InsertGLTransaction parameter
--              :                to sp_AB_Insert_Cash_Book_Transactions
--              :09 JUN 02 - Added check 'IF @Disc_Ex_VAT <> 0'.
--              :                Only insert AB_Cash_Book_Transaction_Details
--              :                if Settlement Disc <> 0
--              :13 JUN 02 - Fixed VAT on Settlement Discount calculation to:
--              :                (TaxRate / (100 + TaxRate))
-------------------------------------------------------------------------------
--REDUNDANT SP 21/07/02
--REPLACED BY: sp_AO_Supplier_Payment_GL_Clearing_Insert
-------------------------------------------------------------------------------

CREATE         PROCEDURE sp_AO_Supplier_Payments_CB_And_GL_Insert
    (
    	@Invoices_Total money,
    	@Discount_Amount money,
    	@Payment_Total money,
        @Company_Banks_ID int,
    	@Transaction_Type_ID tinyint,
    	@AW_Months_ID int, 
    	@AW_Years_ID int,
    	@AO_Transactions_ID int,    --Reference
    	@User_ID int,
        @Company_ID int 
    )

AS

SET NOCOUNT ON

    DECLARE
        @CB_Transaction_ID int,
        @Date datetime,
        @Supplier_ID int,
        @Supplier_Name varchar(30),
        @Supplier_Inv_No varchar(10),
        @CB_Description varchar(50),
        @Trade_Creditors_GL_ID int,
        @Vat_GL_ID int,
        @Settlement_Disc_Received_GL_ID int,
        @Disc_Ex_VAT money,
        @Vat_Amount money,
        @InsertGLTransaction bit,
        @RefNo varchar(20),
    	@Comments varchar(50),
        @TaxRate decimal(5,2)

    BEGIN
    
    	BEGIN 
    
    		SELECT
                @Supplier_ID = AO_Suppliers_ID,
                @Supplier_Inv_No = LEFT(ISNULL(Document_Number, ''), 10)
    		FROM AO_Transactions
    		WHERE AO_Transactions_ID = @AO_Transactions_ID
    		
    		SELECT @Supplier_Name = LEFT(ISNULL(Supplier_Name, ''), 30) 
    		FROM AO_Suppliers
    		WHERE AO_Suppliers_ID = @Supplier_ID

            --Get the Current Tax Rate
            SELECT @TaxRate = ISNULL(Tax_Rate, 0)
            FROM Sys_AW_Tax_Codes
            WHERE Tax_Code = 'S'    --Standard rate (14)
    	
    		SET @CB_Description = LEFT('Payment ' + @Supplier_Name, 50)
            SET @RefNo = CONVERT(VARCHAR(20), @AO_Transactions_ID)

            SET @InsertGLTransaction = 1    -- 1 = YES, 0 = NO 
    	
    		SET @Date = GETDATE()
    
    		EXEC @CB_Transaction_ID = sp_AB_Insert_Cash_Book_Transactions
                                            @Company_Banks_ID,
                                            @Transaction_Type_ID,
                                            @Date,
                                            @AW_Months_ID,
                                            @AW_Years_ID,
                                            @RefNo,
                                            @CB_Description,
                                            @Payment_Total,
                                            @User_ID,
                                            @Company_ID,
                                            @InsertGLTransaction
    
    	END 
    
-------------------------------------------------------------------------------
    --UPDATE the GL CONTROL ACCOUNTS
-------------------------------------------------------------------------------
    	BEGIN
    		SELECT @Trade_Creditors_GL_ID = AB_Accounts_ID
    		FROM AB_Control_Accounts
    		WHERE Control_Number = 201    --Trade Creditors
    		
    		SELECT @Settlement_Disc_Received_GL_ID = AB_Accounts_ID
    		FROM AB_Control_Accounts
    		WHERE Control_Number = 205    --Settlement Discount Received
    
    		SELECT @Vat_GL_ID = AB_Accounts_ID
    		FROM AB_Control_Accounts
    		WHERE Control_Number = 401    --VAT Control Acc
    		
    		SET @Vat_Amount = (@Discount_Amount * (@TaxRate / (100 + @TaxRate)))
    		SET @Disc_Ex_VAT = (@Discount_Amount - @Vat_Amount) 
    
    		SET @Vat_Amount = (@Vat_Amount * -1)
    		SET @Disc_Ex_VAT = (@Disc_Ex_VAT * -1)
    	END
    
-------------------------------------------------------------------------------
    --Debit Trade Creditors 
-------------------------------------------------------------------------------
    	BEGIN 
    		EXEC sp_AB_Insert_Cash_Book_Transactions_Details
                                            @CB_Transaction_ID,
                                            @Trade_Creditors_GL_ID,
                                            3,
                                            @Invoices_Total,
                                            1,
                                            0,
                                            @Invoices_Total,
                                            @Comments,
                                            @CB_Description,
                                            @User_ID,
                                            @Company_ID,
                                            @InsertGLTransaction
    	END 

-------------------------------------------------------------------------------
    --Settlement Discount Received
-------------------------------------------------------------------------------
        IF @Disc_Ex_VAT <> 0    --TB 09 JUN 02
        	BEGIN 
        		EXEC sp_AB_Insert_Cash_Book_Transactions_Details
                                                @CB_Transaction_ID,
                                                @Settlement_Disc_Received_GL_ID,
                                                3,
                                                @Disc_Ex_VAT,
                                                1,
                                                0,
                                                @Disc_Ex_VAT,
                                                @Comments,
                                                @CB_Description,
                                                @User_ID,
                                                @Company_ID,
                                                @InsertGLTransaction
        	END 

-------------------------------------------------------------------------------
    --VAT Control
-------------------------------------------------------------------------------
    	IF @Vat_Amount <> 0
    		BEGIN 
    			EXEC sp_AB_Insert_Cash_Book_Transactions_Details
                                            @CB_Transaction_ID,
                                            @Vat_GL_ID,
                                            3,
                                            @Vat_Amount,
                                            1,
                                            0,
                                            @Vat_Amount,
                                            @Comments,
                                            @CB_Description,
                                            @User_ID,
                                            @Company_ID,
                                            @InsertGLTransaction
    		END 	
    END


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Remittances_Temp_Insert
--Purpose       :Saves an Ad-Hoc snapshot of ALL Suppliers (Creditors) accounts 
--              :    and payable Supplier Remittance Transactions
--              :
--Parameters    :
--Date          :2002/06/20
--Authors       :TB
--Version       :1.0.0
--MODS          :16/07/02 - Inserted @AllUnflagged to INSERT ALL transactions
--              :           or only FLAGGED (for payment) transactions
--              :07/08/02 - Clear the Ageing Balances BEFORE NEXT FETCH
--              :16/08/02 - Added NEW [AB_Accounts_ID] column into
--              :           AO_Remittance_Details_Temp
--              :19/08/02 - Added NEW [AO_Transactions_ID] column into
--              :           AO_Remittance_Details_Temp
--              :25/10/02 - Validated @ToBePaidTotal with ISNULL and
--              :           NB NB NB ALL INSNULL validations MUST BE ALIASED
--              :25/10/02 - Select all transactions up to MIDNIGHT with @ToDay
--              :01/11/02 - Retrieve Supplier Ageing Amounts by Accounting Period
--              :02/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
--              :17/12/03 - Added NEW Settlement_Discount field in AO_Transactions
--              :16/09/05 - Removed optional @AllUnflagged to ALWAYS fetch only Flagged
--              :           for Payment total
--2004.5.1      :20/05/11 - Added ISNULL validations EVERYWHERE
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Supplier_Remittances_Temp_Insert
	(
        @Date DateTime, 
        @CompanyID int,
        @UserID int,
        @AllUnflagged bit,
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
	)

AS

SET NOCOUNT ON

	DECLARE
        @PeriodProcedureID int,
        @SupplierID int,
        @SupplierName varchar(90),
        @SupplierNumber varchar(10),
    	@CreditLimit money,
    	@CreditTerms varchar(20),
    	@SettleDisc decimal(7, 2),
    	@SupplierContact varchar(30),
       	@SuppTel varchar(12),
    	@SuppCel varchar(12),
    	@SuppFax varchar(12),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @WorkEmail varchar(40),
        @AccountBalance money,
        @RemittanceID int,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @ToBePaidTotal money,
        @Period1 varchar(6)


    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)

    SET @PeriodProcedureID = 0


--Wipe the TEMP table-------
    BEGIN
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittance_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AO_Remittance_Details_Temp]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittances_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AO_Remittances_Temp]

        CREATE TABLE [dbo].[AO_Remittance_Details_Temp] (
        	[AO_Remittance_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AO_Remittances_Temp_ID] [int] NULL ,
        	[AO_Transactions_ID] [int] NULL ,
        	[AB_Accounts_ID] [int] NULL ,
        	[Transaction_Date] [datetime] NULL ,
        	[Sys_AW_Transaction_Types_ID] [int] NULL ,
        	[Transaction_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Settlement_Discount] [money] NULL ,
        	[To_Be_Paid][bit] NULL ,
        	[To_Be_Paid_Amount] [money] NULL ,
        	[Remittance_Balance] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL 
        ) ON [PRIMARY]

        CREATE TABLE [dbo].[AO_Remittances_Temp] (
        	[AO_Remittances_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AW_Period_Procedures_ID] [int] NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Supplier] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Credit_Limit] [money] NULL ,
        	[Credit_Terms] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Default_Settlement_Discount] [decimal](7, 2) NULL ,
        	[Supplier_Contact] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Supplier_Telephone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Contact_Cellphone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Supplier_Fax] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Account_Balance] [money] NULL ,
        	[To_Be_Paid_Total] [money] NULL ,
        	[Current] [money] NULL ,
        	[30Days] [money] NULL ,
        	[60Days] [money] NULL ,
        	[90Days] [money] NULL ,
        	[120Days] [money] NULL ,
        	[150Days] [money] NULL ,
        	[180+Days] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL 
        ) ON [PRIMARY]

        CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittance_Details_Temp] ON [dbo].[AO_Remittance_Details_Temp]([AO_Remittance_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
        CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittances_Temp] ON [dbo].[AO_Remittances_Temp]([AO_Remittances_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Remittances_Temp].[Date_Captured]'

        setuser
    END
----------------------------

    BEGIN

    --> Step 4: Define a CURSOR for AO_Suppliers
    	DECLARE Supplier_Temp_Cursor CURSOR FOR
            (
            --> Select ALL Suppliers
                SELECT DISTINCT        --DISTINCT = NB
                    s.AO_Suppliers_ID,
                    ISNULL(s.Supplier_Name,'') AS Supplier,
                	ISNULL(s.Credit_Limit, 0),
                	ISNULL(ct.[Description],''),
                	ISNULL(s.Default_Settlement_Discount, 0),
                	ISNULL(s.Supplier_Contact,''),
                   	ISNULL(s.Supplier_Telephone,''),
                	ISNULL(s.Contact_Cellphone,''),
                	ISNULL(s.Supplier_Fax,''),
                    ISNULL(s.Post_Box,''),
                    ISNULL(s.Post_Office,''),
                    ISNULL(s.Post_Code,''),
                    ISNULL(s.Email_Address,''),
                    ISNULL(Supplier_Number,'')
                FROM AO_Suppliers s
                    INNER JOIN AO_Transactions t
                        ON s.AO_Suppliers_ID = t.AO_Suppliers_ID
                    LEFT JOIN Slu_AW_Credit_Terms ct
                        ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
                WHERE dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1
            )
    
    	OPEN Supplier_Temp_Cursor
    
        	FETCH NEXT FROM Supplier_Temp_Cursor 
        	INTO
                @SupplierID,
                @SupplierName,
            	@CreditLimit,
            	@CreditTerms,
            	@SettleDisc,
            	@SupplierContact,
               	@SuppTel,
            	@SuppCel,
            	@SuppFax,
                @PostBox,
                @PostOffice,                @PostCode,
                @WorkEmail,
                @SupplierNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
        		SELECT
                        @AgePayment = ISNULL(Payment, 0),
                        @AgeAmount = ISNULL(Amount, 0),
                        @AgeCurrent = ISNULL([Current], 0),
                        @Age30Days = ISNULL([30 Days], 0),
                        @Age60Days = ISNULL([60 Days], 0),
                        @Age90Days = ISNULL([90 Days], 0),
                        @Age120Days = ISNULL([120 Days], 0),
                        @Age150Days = ISNULL([150 Days], 0),
                        @Age180Days = ISNULL([180+ Days], 0)
                FROM dbo.fn_AO_Supplier_Period_Ageing_Values
                        (
                        	@SupplierID, 
                        	@M1, @Y1,
                        	@M2, @Y2,
                        	@M3, @Y3,
                        	@M4, @Y4,
                        	@M5, @Y5,
                        	@M6, @Y6,
                        	@M7, @Y7
                        ) 

                SET @AccountBalance = @AgeCurrent + 
                                      @Age30Days + 
                                      @Age60Days + 
                                      @Age90Days + 
                                      @Age120Days + 
                                      @Age150Days + 
                                      @Age180Days


                SELECT @ToBePaidTotal = SUM(ISNULL(To_Be_Paid_Amount, 0))
                FROM AO_Transactions
                WHERE AO_Suppliers_ID = @SupplierID AND
                        Total_Amount <> -(Payment_Amount) AND
                        To_Be_Paid <> 0 AND
                        dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                       (Sys_AW_Transaction_Types_ID = 6 OR
                        Sys_AW_Transaction_Types_ID = 8 OR
                        Sys_AW_Transaction_Types_ID = 9 OR
                        Sys_AW_Transaction_Types_ID = 10 OR
                        Sys_AW_Transaction_Types_ID = 12)

            --> Insert ALL Suppliers        
        		INSERT INTO AO_Remittances_Temp
        			(
                        AW_Period_Procedures_ID,
                        AO_Suppliers_ID,
                        Supplier,
                        Supplier_Number,
                    	Credit_Limit,
                    	Credit_Terms,
                    	Default_Settlement_Discount,
                    	Supplier_Contact,
                       	Supplier_Telephone,
                    	Contact_Cellphone,
                    	Supplier_Fax,
                        Post_Box,
                        Post_Office,
                        Post_Code,
                        Email_Address,
                        [User_ID],
                        AW_User_Companies_ID,
                        Amount,
                        Payment,
                        Account_Balance,
                        To_Be_Paid_Total,
                        [Current],
                        [30Days],
                        [60Days],
                        [90Days],
                        [120Days],
                        [150Days],
                        [180+Days]
                    )
        		VALUES
        			(
                        @PeriodProcedureID,    --initialized to 0 ??
                        @SupplierID,
                        RTRIM(LTRIM(@SupplierName)),
                        @SupplierNumber,
                    	@CreditLimit,
                    	@CreditTerms,
                    	@SettleDisc,
                    	@SupplierContact,
                       	@SuppTel,
                    	@SuppCel,
                    	@SuppFax,
                        @PostBox,
                        @PostOffice,
                        @PostCode,
                        @WorkEmail,
                        @UserID,
                        @CompanyID,
                        @AgeAmount,
                        @AgePayment,
                        @AccountBalance,
                        @ToBePaidTotal,
                        @AgeCurrent,
                        @Age30Days,
                        @Age60Days,
                        @Age90Days,
                        @Age120Days,
                        @Age150Days,
                        @Age180Days
                    )
    
        	  	SELECT @RemittanceID = Scope_Identity()

                IF @AllUnflagged = 1    --1 = Insert only flagged To_Be_Paid transactions
                    BEGIN
                		INSERT INTO AO_Remittance_Details_Temp
                			(
                                AO_Remittances_Temp_ID,
                                AO_Transactions_ID,
                                AB_Accounts_ID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                Settlement_Discount,
                                To_Be_Paid,
                                To_Be_Paid_Amount,
                                Remittance_Balance,
                                [User_ID],
                                AW_User_Companies_ID
                            )
                        SELECT 
                                @RemittanceID,
                                AO_Transactions_ID,
                                AB_Accounts_ID,
                                Document_Date,
                                Sys_AW_Transaction_Types_ID,
                                ISNULL(Document_Number, ''),
                                ISNULL(Total_Amount, 0),
                                ISNULL(Payment_Amount, 0),
                                ISNULL(Settlement_Discount, 0),
                                To_Be_Paid,
                                ISNULL(To_Be_Paid_Amount, 0),
                                ISNULL(Remittance_Balance, 0),
                                [User_ID],
                                AW_User_Companies_ID
                        FROM AO_Transactions
                        WHERE AO_Suppliers_ID = @SupplierID AND
                                Total_Amount <> -(Payment_Amount) AND
                                To_Be_Paid <> 0 AND
                                dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                               (Sys_AW_Transaction_Types_ID = 6 OR
                                Sys_AW_Transaction_Types_ID = 8 OR
                                Sys_AW_Transaction_Types_ID = 9 OR
                                Sys_AW_Transaction_Types_ID = 10 OR
                                Sys_AW_Transaction_Types_ID = 12)
                    END
                ELSE    --@AllUnflagged = 0    --0 = Insert ALL UNPAID transactions
                    BEGIN
                		INSERT INTO AO_Remittance_Details_Temp
                			(
                                AO_Remittances_Temp_ID,
                                AO_Transactions_ID,
                                AB_Accounts_ID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                Settlement_Discount,
                                To_Be_Paid,
                                To_Be_Paid_Amount,
                                Remittance_Balance,
                                [User_ID],
                                AW_User_Companies_ID
                            )
                        SELECT 
                                @RemittanceID,
                                AO_Transactions_ID,
                                AB_Accounts_ID,
                                Document_Date,
                                Sys_AW_Transaction_Types_ID,
                                ISNULL(Document_Number, ''),
                                ISNULL(Total_Amount, 0),
                                ISNULL(Payment_Amount, 0),
                                ISNULL(Settlement_Discount, 0),
                                To_Be_Paid,
                                ISNULL(To_Be_Paid_Amount, 0),
                                ISNULL(Remittance_Balance, 0),
                                [User_ID],
                                AW_User_Companies_ID
                                
                        FROM AO_Transactions
                        WHERE AO_Suppliers_ID = @SupplierID AND
                                Total_Amount <> -(Payment_Amount) AND
                                dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                               (Sys_AW_Transaction_Types_ID = 6 OR
                                Sys_AW_Transaction_Types_ID = 8 OR
                                Sys_AW_Transaction_Types_ID = 9 OR
                                Sys_AW_Transaction_Types_ID = 10 OR
                                Sys_AW_Transaction_Types_ID = 12)
                    END

            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Supplier_Temp_Cursor 
            	INTO
                    @SupplierID,
                    @SupplierName,
                	@CreditLimit,
                	@CreditTerms,
                	@SettleDisc,
                	@SupplierContact,
                   	@SuppTel,
                	@SuppCel,
                	@SuppFax,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @SupplierNumber
    
        	END
    	
    	CLOSE Supplier_Temp_Cursor
    
    	DEALLOCATE Supplier_Temp_Cursor

    END


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














----------------------------------------------------------------------------
--Description   :sp_AO_Suppliers_Overdue
--Purpose       :Retrieves overdue Suppliers amount
--Date          :2002/12/26
--Authors       :TB
--MODS          :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--2004.3.2      :01/10/06 - Added [TermsValue] field to widen the net
--2004.5.2      :11/07/11 - Fixed a.Supplier_Name field size from varchar(30) to 40 in
--              :           fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers preventing
--              :           Manager Console from displaying actual Supplier overdue amount
----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AO_Suppliers_Overdue
   (        
        @TranDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime

-----------------------------
--     SET @TranDate = getdate()
--     SET @CompanyID = 1
-----------------------------

	SET @Now = @TranDate

--> Retrieves last (up to) 7 Month-Ends DATES
	EXEC sp_AW_Period_Procedures_Select
        @Now,
        @D1 OUTPUT,
        @D2 OUTPUT,
        @D3 OUTPUT,
        @D4 OUTPUT,
        @D5 OUTPUT,
        @D6 OUTPUT,
        @D7 OUTPUT,
        1,            --1 = Suppliers
        @CompanyID

	SELECT
		a.SupplierID, 
		RTRIM(LTRIM(ISNULL(a.Supplier_Name, ''))) AS [Supplier],
        MAX(ISNULL(c.Slu_AW_Credit_Terms_ID, 1)) AS [CTID],
        MAX(RTRIM(LTRIM(ISNULL(t.[Description], '')))) AS [Terms],
        MAX(RTRIM(LTRIM(ISNULL(t.Terms_Value, 0)))) AS [TermsValue],
		SUM(a.Amount + a.Payment) AS [Balance], 
        SUM(a.[Current]) AS [Current], 
        SUM(a.[30 Days]) AS [30 Days], 
        SUM(a.[60 Days]) AS [60 Days], 
        SUM(a.[90 Days]) AS [90 Days], 
        SUM(a.[120 Days]) AS [120 Days], 
        SUM(a.[150 Days]) AS [150 Days], 
        SUM(a.[180+ Days]) AS [180 Days]
    FROM dbo.fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers
        (
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7,
            @CompanyID
        ) a
        LEFT JOIN AO_Suppliers c
            ON c.AO_Suppliers_ID = a.SupplierID
        LEFT JOIN Slu_AW_Credit_Terms t
            ON c.Slu_AW_Credit_Terms_ID = t.Slu_AW_Credit_Terms_ID
    GROUP BY a.SupplierID, a.Supplier_Name
    ORDER BY a.Supplier_Name


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AO_Suppliers_Payments_PickList
--Purpose       :Suppliers Payments Picklist - NEW
--Functionality :Selects ONLY Suppliers with Outstanding Transactions
--Parameters    :
--Date          :2003/01/30
--Authors       :TB
--MODS          :26/12/03 - Added JOIN for Credit Terms to replace DBC in UI
--2004.4.3      :21/03/09 - Added @Option to INCLUDE Suppliers with an OUTSTANDING CREDIT BALANCE
--2004.5.0      :10/03/11 - Added [Email] field
------------------------------------------------------------------------------

CREATE         Procedure sp_AO_Suppliers_Payments_PickList
    (
    	@CompanyID int,
        @Option tinyint
    )

AS

SET NOCOUNT ON


	SELECT s.AO_Suppliers_ID AS [ID],
           ISNULL(s.Supplier_Name, '') AS [Supplier],
           ISNULL(s.Supplier_Number, '') AS [Number],
           ct.[Description] AS [Terms],
           LOWER(ISNULL(s.Email_Address, '')) AS [Email]
	FROM AO_Suppliers s
        INNER JOIN Slu_AW_Credit_Terms ct
            ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
    WHERE AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AO_Supplier_Has_Outstanding_Transactions(AO_Suppliers_ID, @Option) = 1
	ORDER BY Supplier_Name ASC



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AO_Suppliers_Period_Procedure_Insert
--Purpose       :Saves a snapshot of Suppliers Transactions up to the
--              :    selected month-end Accounting Period
--Functionality :ONLY Suppliers that have transactions PAYABLE are selected
--Calls         :fn_AO_Supplier_Period_Procedure_Ageing_Values
--Date          :2007/03/09
--Authors       :TB
--MODS          :
--2004.3.5      :18/04/07 - Added condition in Supplier_Cursor SELECT to INCLUDE
--              :           only Suppiers and Transactions <= @MonthID and @YearID
--              :18/04/07 - Added condition for INSERT into AO_Statement_Details to
--              :           INCLUDE only Transactions <= @MonthID and @YearID
--2004.4.2      :25/10/08 - Added new Standard Cost Inventory Valuation method
--              :27/11/08 - Added ISNULL validation on all ageing fields
------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AO_Suppliers_Period_Procedure_Insert
	(
        @MonthID int,
        @YearID int,
        @ProcedureDate DateTime, 
        @Description varchar(50),
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @PeriodProcedureID int,
            @SupplierID int,
            @SupplierName varchar(90),
            @SupplierNumber varchar(10),
            @PostBox varchar(20),
            @PostOffice varchar(30),
            @PostCode varchar(10),
            @EmailAddress varchar(40),
            @AccountBalance money,
            @StatementID int,
            @D1 varchar(6),
            @D2 varchar(6),
            @D3 varchar(6),
            @D4 varchar(6),
            @D5 varchar(6),
            @D6 varchar(6),
            @D7 varchar(6),
            @AgePayment money,
            @AgeAmount money,
            @AgeCurrent money,
            @Age30Days money,
            @Age60Days money,
            @Age90Days money,
            @Age120Days money,
            @Age150Days money,
            @Age180Days money,
            @StockValuation money,
            @ValuationMethod smallint,
            @ProcedureTypeID int,
            @ReturnCode int


    SET @ProcedureTypeID = 6        --6 = Suppliers Month-End
    SET @PeriodProcedureID = 0
    SET @ReturnCode = 0             --0 = Unsuccessful


    BEGIN TRANSACTION


    --> Stock Valuation (theoretical now)
        SELECT @ValuationMethod = ISNULL(Control_Index, 0)
        FROM Sys_AW_Options
        WHERE Control_Type = 'OptionButton' AND
              Control_Name = 'optInventoryValuation' AND
              Control_Value = 'True' AND
              AW_User_Companies_ID = @CompanyID


        IF @ValuationMethod = 0
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Average_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
    
            END
        ELSE
        IF @ValuationMethod = 1
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Last_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END
        ELSE
        IF @ValuationMethod = 2
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Standard_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END


    --> Step 2: Insert a Period Procedure record and get its ID
    	INSERT AW_Period_Procedures
            (
                Sys_AW_Period_Procedure_Types_ID,
                [Description],
                [Month],
                [Year],
                Month_End_Date,
                Stock_Valuation,
                [User_ID],
                AW_User_Companies_ID
            )
    	VALUES
            (
                @ProcedureTypeID,            -- 6 = Suppliers Month-End
                @Description,
                @MonthID,
                @YearID,
                @ProcedureDate,
                @StockValuation,                @UserID,
                @CompanyID
            )
    
    	SELECT @PeriodProcedureID = Scope_Identity()


    --> INSERT a STOCK VALUATION
        -----------------------------------------
        EXEC sp_AP_Products_History_Insert 2, @Description, @UserID, @CompanyID, @ProcedureDate


    --> Step 3: Get the last 7 ACCOUNTING PERIODS to insert ageing for each Account
        EXEC sp_AW_Period_Procedure_Periods_Select
                @MonthID,
                @YearID,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT


    --> Do as at Procedure cutoff ACCOUNTING PERIOD
    	DECLARE Supplier_Cursor CURSOR FOR
            (
                SELECT DISTINCT
                    c.AO_Suppliers_ID,
                    ISNULL(c.Supplier_Name, '') AS [FullName],
                    ISNULL(c.Post_Box, ''),
                    ISNULL(c.Post_Office, ''),
                    ISNULL(c.Post_Code, ''),
                    ISNULL(c.Email_Address, ''),
                    ISNULL(c.Supplier_Number, '')
                FROM AO_Suppliers c
                    INNER JOIN AO_Transactions t
                        ON c.AO_Suppliers_ID = t.AO_Suppliers_ID
                WHERE c.AW_User_Companies_ID = @CompanyID AND
                      dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
            )
    
    	OPEN Supplier_Cursor
    
        	FETCH NEXT FROM Supplier_Cursor 
        	INTO
                @SupplierID,
                @SupplierName,
                @PostBox,
                @PostOffice,
                @PostCode,
                @EmailAddress,
                @SupplierNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN


        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
                FROM dbo.fn_AO_Supplier_Period_Procedure_Ageing_Values
                    (
                        @SupplierID,
                        @ProcedureDate,
                        @MonthID,
                        @YearID,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = ISNULL(@AgeCurrent, 0) + 
                                      ISNULL(@Age30Days, 0) + 
                                      ISNULL(@Age60Days, 0) + 
                                      ISNULL(@Age90Days, 0) + 
                                      ISNULL(@Age120Days, 0) + 
                                      ISNULL(@Age150Days, 0) + 
                                      ISNULL(@Age180Days, 0)

        		INSERT INTO AO_Statements
        			(
                        AW_Period_Procedures_ID,
                        AO_Suppliers_ID,
                        FullName,
                        Supplier_Number,
                        Post_Address,
                        Post_Office,
                        Post_Code,
                        Email_Address,
                        [User_ID],
                        AW_User_Companies_ID,
                        Amount,
                        Payment,
                        Account_Balance,
                        [Current],
                        [30Days],
                        [60Days],
                        [90Days],
                        [120Days],
                        [150Days],
                        [180+Days],
                        Date_Captured
                    )
        		VALUES
        			(
                        @PeriodProcedureID,
                        @SupplierID,
                        rtrim(ltrim(@SupplierName)),
                        @SupplierNumber,
                        @PostBox,
                        @PostOffice,
                        @PostCode,
                        @EmailAddress,
                        @UserID,
                        @CompanyID,
                        ISNULL(@AgeAmount, 0),
                        ISNULL(@AgePayment, 0),
                        ISNULL(@AccountBalance, 0),
                        ISNULL(@AgeCurrent, 0),
                        ISNULL(@Age30Days, 0),
                        ISNULL(@Age60Days, 0),
                        ISNULL(@Age90Days, 0),
                        ISNULL(@Age120Days, 0),
                        ISNULL(@Age150Days, 0),
                        ISNULL(@Age180Days, 0),
                        @ProcedureDate
                    )

        	  	SELECT @StatementID = Scope_Identity()
        
        		--Insert Transactions from LAST Period Procedure Date
        		INSERT INTO AO_Statement_Details
        			(
                        AO_Statements_ID,
                        AO_Transactions_ID,
                        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,
                        AW_Comments_ID,
                        Trade_Discount_Total,
                        Rebate_Discount_Total,
                        Other_Discount_Total,
                        Net_Amount,
                        Total_Tax_Amount,
                        Total_Amount,
                        Payment_Amount,
                        Settlement_Discount,
                        To_Be_Paid,
                        To_Be_Paid_Amount,
                        Remittance_Balance,
                        [User_ID],
                        AW_User_Companies_ID,
                        Date_Captured
                    )
                SELECT 
                        @StatementID,
                        AO_Transactions_ID,
                        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,
                        AW_Comments_ID,
                        Trade_Discount_Total,
                        Rebate_Discount_Total,
                        Other_Discount_Total,
                        Net_Amount,
                        Total_Tax_Amount,
                        Total_Amount,
                        Payment_Amount,
                        Settlement_Discount,
                        To_Be_Paid,
                        To_Be_Paid_Amount,
                        Remittance_Balance,
                        [User_ID],
                        AW_User_Companies_ID,
                        @ProcedureDate

                FROM AO_Transactions
                WHERE AO_Suppliers_ID = @SupplierID AND
                     (Sys_AW_Transaction_Types_ID = 6 OR
                      Sys_AW_Transaction_Types_ID = 8 OR
                      Sys_AW_Transaction_Types_ID = 9 OR
                      Sys_AW_Transaction_Types_ID = 10 OR
                      Sys_AW_Transaction_Types_ID = 12) AND
                      ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
--                      AND Document_Date <= @ProcedureDate
                      dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Supplier_Cursor 
            	INTO
                    @SupplierID,
                    @SupplierName,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @EmailAddress,
                    @SupplierNumber
    
        	END
    	
    	CLOSE Supplier_Cursor
    
    	DEALLOCATE Supplier_Cursor


        SET @ReturnCode = 1


    COMMIT TRANSACTION


SET NOCOUNT OFF


RETURN @ReturnCode





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description	:sp_AO_Transaction_DocNo_Update
--Purpose       :UPDATE AS_Transactions.Payment_Amount
--Date			:2014/07/24
--Authors		:RL
--MODS    		:
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Transaction_DocNo_Update]
	(
		@TransactionID		int,
        @Document_Number	varchar(20)
	)
AS

SET NOCOUNT ON

	UPDATE AO_Transactions
    SET Document_Number = @Document_Number
    WHERE AO_Transactions_ID = @TransactionID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










-- ???? REDUNDANT ????

------------------------------------------------------------------------------
--Description   :sp_AO_Transaction_Headers_Unallocated_Select
--Purpose       :Select Supplier Transactions for the Ageing/Payment Allocation
--Functionality :
--Parameters    :@Choice - 1:Invoice, 2:Payments, 3:Customers
--Date          :2002/01/07
--Authors       :TB
--Version       :1.0.0
--Mods          :19/06/02 - Added tt.[Description] AS [Type] to choice 1
--              :12/09/02 - Modified the sort ORDER to t.Document_Date DESC
--              :14/09/02 - Added t.Document_Date as [Date] as well
--              :24/09/02 - Modified @Now to return MIDNIGHT TONIGHT which caused
--              :           not all transactions to be included for the @Now day
--              :28/10/02 - Changed column ORDER of Account Balances (Option 10)
--              :28/10/02 - Added missing Transaction Type ID 6, 10 and 12 to
--              :           Option = 1 and 10
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AO_Transaction_Headers_Unallocated_Select
    (
    	 @Choice tinyint, 
    	 @CompanyID int, 
    	 @SupplierID int = 0 
    )

AS

SET NOCOUNT ON

    DECLARE @Now datetime, 
    		@D1 dateTime, 
    		@D2 datetime, 
    		@D3 datetime, 
    		@D4 datetime, 
    		@D5 datetime, 
    		@D6 datetime, 
    		@D7 datetime 
    
--> (24/09/02) This ONLY return TIME RIGHT NOW,
--        and NOT UNTIL MIDNIGHT TONIGHT (the WHOLE DAY TODAY)
--    SET @Now = getdate()

--> (24/09/02) Truncates the decimal of today's date e.g.
--        '2002-09-24 13:33:45.076' as '2002-09-24 00:00:00.000',
--        and adds 1 day which equals midnite tonight
--        which returns '2002-09-25 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))

	EXEC sp_AW_Period_Procedures_Select
                            @Now,
                            @D1 OUTPUT,
                            @D2 OUTPUT,
                            @D3 OUTPUT,
                            @D4 OUTPUT,
                            @D5 OUTPUT,
                            @D6 OUTPUT,
                            @D7 OUTPUT,
                            4,            --4 = Suppliers    4 ??????????????????????????
                            @CompanyID

--> Ageing    --(REDUNDANT ??)
	IF @Choice = 1
		SELECT    
			t.AO_Transactions_ID AS [ID], 
			t.AO_Suppliers_ID AS SupplierID,
			t.Comment AS Comment,
			t.Total_Amount AS Balance,
			ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount,0) AS [Old Balance],
			t.Document_Number AS [No], 
			ISNULL(t.Total_Amount, 0) AS Amount, 
			ISNULL(t.Payment_Amount, 0) AS Payment, 
			t.Date_Captured AS [Date],
    		tt.[Description] AS [Type], 
			a.[Current],
			a.[30 Days],
			a.[60 Days],
			a.[90 Days],
			a.[120 Days],
			a.[150 Days],
			a.[180+ Days]
		FROM vw_AO_Transactions t
            LEFT JOIN dbo.fn_AO_Supplier_Ageing_Non_Grouped
                ( @SupplierID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a
                ON t.AO_Transactions_ID = a.[ID]
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
		WHERE t.AO_Suppliers_ID = @SupplierID AND
              t.AW_User_Companies_ID = @CompanyID AND
             (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
--                    (t.Sys_AW_Transaction_Types_ID = 8 OR
--                     t.Sys_AW_Transaction_Types_ID = 9 OR
--                     t.Sys_AW_Transaction_Types_ID = 10)
                   (t.Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement
                    t.Sys_AW_Transaction_Types_ID = 8 OR    --Supplier Invoice
                    t.Sys_AW_Transaction_Types_ID = 9 OR    --Supplier Refund
                    t.Sys_AW_Transaction_Types_ID = 10 OR   --Supplier Journal
                    t.Sys_AW_Transaction_Types_ID = 12)     --Supplier Payment
     		ORDER BY a.[Current], a.[30 Days], a.[60 Days], a.[90 Days],
                     a.[120 Days], a.[150 Days], a.[180+ Days]

--> Payment Transactions
	ELSE
	IF @Choice = 2
		SELECT    
			t.AO_Transactions_ID AS ID, 
			t.AO_Suppliers_ID AS SupplierID,
			t.Comment AS Comment,
			ISNULL(t.Total_Amount,0) as Balance,
			ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) as [Old Balance],
			t.Document_Number AS [No], 
			ISNULL(t.Total_Amount,0) AS Amount, 
			ISNULL(t.Payment_Amount,0) AS Payment, 
			t.Date_Captured AS [Date]
		FROM vw_AO_Transactions t 
		WHERE t.AO_Suppliers_ID = @SupplierID AND
                t.AW_User_Companies_ID = @CompanyID AND
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
                t.Sys_AW_Transaction_Types_ID = 12    --12 = Supplier Payments

--> Supplier Picklist
	ELSE
	IF @Choice = 3
		SELECT DISTINCT
			s.AO_Suppliers_ID AS SupplierID,
			s.Supplier_Name AS Supplier
		FROM AO_Suppliers s
		WHERE dbo.fn_Supplier_Has_Transaction(s.AO_Suppliers_ID, 1) = 1

	ELSE 
	IF @Choice = 4
		BEGIN
			SELECT * FROM dbo.fn_AO_Supplier_Ageing_Non_Grouped
                (
                    @SupplierID,
                    @Now,
                    @D1,
                    @D2,
                    @D3,
                    @D4,
                    @D5,
                    @D6,
                    @D7
                ) 
		END

	ELSE 
	IF @Choice = 5
		BEGIN
			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] 
            FROM dbo.fn_AO_Supplier_Ageing_Non_Grouped
                    (
                        @SupplierID,
                        @Now,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    ) 
			GROUP BY SupplierID
		END
	
	IF @Choice = 6
		SELECT Sys_AW_Payment_Methods_ID as [ID],
                [Description]  
		FROM Sys_AW_Payment_Methods 
		WHERE (Sys_AW_Payment_Methods_ID <> 4 AND 
			   Sys_AW_Payment_Methods_ID <> 5 AND
			   Sys_AW_Payment_Methods_ID <> 7 AND
			   Sys_AW_Payment_Methods_ID <> 8 AND
			   Sys_AW_Payment_Methods_ID <> 9 AND
			   Sys_AW_Payment_Methods_ID <> 10 AND
			   Sys_AW_Payment_Methods_ID <> 12 AND
			   Sys_AW_Payment_Methods_ID <> 11 )  

--> Card Institutions
	ELSE
	IF @Choice = 7
	   	SELECT Slu_AS_Card_Institutions_ID as [ID],
                [Description]  
		FROM Slu_AS_Card_Institutions

--> Bank Accounts
	IF @Choice = 8
	   	SELECT AW_Company_Banks_ID as [ID],
			 Account_Name as [Account Name] 
		FROM AW_Company_Banks
		WHERE AW_User_Companies_ID = @CompanyID

--> SUPPLIER CATALOG: Account Balances tab (Unallocated Ageing Transactions)
    IF @Choice = 10
		SELECT    
			t.AO_Transactions_ID AS [ID], 
			t.AO_Suppliers_ID AS [SupplierID],
    		ISNULL(tt.[Description], '') AS [Type], 
			t.Document_Date AS [Date],    --This won't work for Creditors
            m.[Description] AS [Month],
            y.[Description] AS [Year],
			ISNULL(t.Document_Number, '') AS [Ref No], 
			t.Date_Captured AS [Captured],
			ISNULL(t.Total_Amount, 0) AS [Amount], 
			ISNULL(t.Payment_Amount, 0) AS [Payment], 
			ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount,0) AS [Old Balance],
			t.Total_Amount AS [Balance],
			ISNULL(t.Comment, '') AS [Comment],
--NB: IF ANY COLUMNS ARE ADDED BEFORE AGEING BELOW, MODIFY HIDEROWS ORDINAL POSITION
			a.[Current],
			a.[30 Days],
			a.[60 Days],
			a.[90 Days],
			a.[120 Days],
			a.[150 Days],
			a.[180+ Days]
		FROM vw_AO_Transactions t
            LEFT JOIN dbo.fn_AO_Supplier_Ageing_Non_Grouped
                ( @SupplierID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a
                ON t.AO_Transactions_ID = a.[ID]
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
            LEFT JOIN Slu_AW_Months m
                ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
            LEFT JOIN Slu_AW_Years y
                ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
		WHERE t.AO_Suppliers_ID = @SupplierID AND
                t.AW_User_Companies_ID = @CompanyID AND
               (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
--                (t.Sys_AW_Transaction_Types_ID = 8 OR
--                 t.Sys_AW_Transaction_Types_ID = 9 OR
--                 t.Sys_AW_Transaction_Types_ID = 10)
               (t.Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement
                t.Sys_AW_Transaction_Types_ID = 8 OR    --Supplier Invoice
                t.Sys_AW_Transaction_Types_ID = 9 OR    --Supplier Refund
                t.Sys_AW_Transaction_Types_ID = 10 OR   --Supplier Journal
                t.Sys_AW_Transaction_Types_ID = 12)     --Supplier Payment
--     		ORDER BY a.[Current], a.[30 Days], a.[60 Days], a.[90 Days],
--                      a.[120 Days], a.[150 Days], a.[180+ Days]
        ORDER BY t.Document_Date DESC



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------
--Description   :sp_AO_Transaction_Headers_Select
--Purpose       :SELECT Transactions History for Supplier Catalog & Invoicing
--Functionality :
--Parameters    : 
--Date          :2002/01/18
--Authors       :TB
--Version       :1.0.0
--MODS          :28/10/02 - Modified some Column Headings to reduce size
--              :28/10/02 - Added @MonthsID & @YearsID for Reports
--              :12/12/04 - Added field [TranTypeID] for Payment Reversal
--              :16/12/04 - Renamed field t.Document_Number from [Ref No] to [Doc No]
--              :16/12/04 - Added field t.Supplier_Reference AS [Ref No]
--              :16/12/04 - Changed [Date] field format to CHAR(10)
--              :17/12/04 - Changed [Date] field format back to unformatted
--              :           because it is used when selecting CASHBOOK TranID
--              :           in Supplier Payment Reversals
--              :18/12/04 - Added field t.Settlement_Discount AS [Settlement]
--2004.3.5      :20/06/07 - Moved [Comment] after [Payment] field
--2004.3.8      :30/05/08 - Moved [Captured] after [Doc No] field
--              :30/05/08 - Moved [Settlement] after [Comment] field
--              :30/05/08 - Changed ORDER BY to t.Date_Captured DESC to enable
--              :           viewing WHEN BACK DATED transactions were posted
--              :30/05/08 - Added fetch transactions FROM an Accounting Period
--              :           instead of for ONE Accounting Period
--V6.4	RL	2018-04-19	:Hide Zero transaction payments that are created by the system!!!!
--------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Transaction_History_Select]
	(
    	@SupplierID int,
        @TransactionTypeID int = 0,
    	@StartDate datetime = NULL,
    	@EndDate datetime = NULL,
    	@Company_ID int,
    	@MonthsID int = NULL, 
    	@YearsID int = NULL
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @StartPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthsID, @YearsID)


    SET @sql = ' SELECT ' +
                    ' t.AO_Transactions_ID As [ID], ' +
                    ' t.AO_Suppliers_ID, ' +
                    ' tt.[Description] AS [Type], ' +
                    ' t.Supplier_Reference AS [Ref No], ' +
                    ' t.Date_Captured AS [Captured], ' +
                    ' t.Document_Number AS [Doc No], ' +
                    ' t.Document_Date AS [Date], ' +
                    ' m.[Description] AS [Month], ' +
                    ' y.[Description] AS [Year], ' +
                    ' t.Net_Amount AS [Amount], ' +
                    ' t.Total_Tax_Amount [Tax], ' +
                    ' t.Total_Amount AS [Total], ' +
                    ' t.Payment_Amount AS [Payment], ' +
                    ' t.Settlement_Discount AS [Settlement], ' +
                    ' t.Comment AS [Comment], ' +
--                    ' t.Settlement_Discount AS [Settlement], ' +
                    ' t.Trade_Discount_Total AS [Trade Disc], ' +
                    ' t.Rebate_Discount_Total AS [Rebate Disc], ' +
                    ' t.Other_Discount_Total AS [Other Disc], ' +
--                    ' t.Date_Captured AS [Captured], ' +
                    ' u.UserName AS [User], ' +
                    ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID] ' +

    			' FROM AO_Transactions t ' +
                    ' LEFT JOIN Sys_AW_Transaction_Types tt ' +
    				    ' ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID ' +
                    ' LEFT JOIN Slu_AW_Months m ' +
                        ' ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID ' +
                    ' LEFT JOIN Slu_AW_Years y ' +
                        ' ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID ' +
                    ' LEFT JOIN AW_Users u ' +
                        ' ON t.User_ID = u.AW_Users_ID '

--WHERE
    SET @sql = @sql +
                ' WHERE t.AO_Suppliers_ID = ' + CONVERT(VARCHAR(10), @SupplierID) + ' AND ' +
                '       t.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @Company_ID)

--Additional WHERE
    IF @TransactionTypeID <> 0    -- Specific TRANSACTION TYPE
        BEGIN
            SET @sql = @sql + ' AND t.Sys_AW_Transaction_Types_ID = ' + CONVERT(VARCHAR(10), @TransactionTypeID)
        END

    IF NOT @StartDate IS NULL OR NOT @EndDate IS NULL    --Between Dates
        BEGIN
            SET @sql = @sql + ' AND DATEDIFF(d, t.Document_Date, ''' + CONVERT(VARCHAR(20), @StartDate) + ''') <= 0 ' +
                              ' AND DATEDIFF(d, t.Document_Date, ''' + CONVERT(VARCHAR(20), @EndDate) + ''') >= 0 '
        END

    IF NOT @MonthsID IS NULL OR NOT @YearsID IS NULL     --Between Accounting Periods
        BEGIN
--             SET @sql = @sql + ' AND t.Slu_AW_Months_ID = ' + CONVERT(VARCHAR(20), @MonthsID) +
--                               ' AND t.Slu_AW_Years_ID = ' + CONVERT(VARCHAR(20), @YearsID)
            SET @sql = @sql + ' AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + '''' + ' '
        END

		--V6.4 RL Hide Zero transaction payments that are created by the system!!!!
		SET @sql = @sql + 'AND t.AO_Transactions_ID NOT IN (SELECT AO_Transactions_ID FROM AO_Transactions WHERE Sys_AW_Transaction_Types_ID = 12 And Total_Amount = 0)'

--    SET @sql = @sql + ' ORDER BY t.Document_Date DESC '
    SET @sql = @sql + ' ORDER BY t.Date_Captured DESC, t.AO_Transactions_ID DESC '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Transactions_Payments_Select
--Purpose       :Supplier Payments: Unpaid Remittance Transactions
--Date          :2002/01/12
--Authors       :TB 
--Mods          :13/06/02 - Added additional info for each transaction and
--              :           removed Date_Captured
--              :30/10/02 - Added Month & Year to Unpaid Transactions grid
--              :04/11/02 - Added retrieving only specific Transaction Types
--              :04/11/02 - Added Ageing parameters and Ageing retrieval
--              :           from fn_AO_Supplier_Period_Ageing
--              :16/12/03 - Added NEW Settlement_Discount to @Choice = 2
--2004.4.7      :17/09/09 - Added to select unallocated Payment transactions
--              :           (TranType = 12) for new Lumpsum Payments
--V6.2	RL	2016/07/14	:Added Document_Date to order by
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Transactions_Payments_Select]

    (
        @Choice tinyint,
        @SupplierID int,
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
    )

AS

SET NOCOUNT ON

--> SUPPLIER CATALOG: Account Balances tab (Ageing Totals)
	IF @Choice = 1
        BEGIN
            SELECT
             	[SupplierID],
            	[Payment],
            	[Amount],
            	[Current],
            	[30 Days],
            	[60 Days],
            	[90 Days],
            	[120 Days], 
            	[150 Days],
            	[180+ Days]
            FROM dbo.fn_AO_Supplier_Period_Ageing_Values
                    (
                    	@SupplierID, 
                    	@M1, @Y1,
                    	@M2, @Y2,
                    	@M3, @Y3,
                    	@M4, @Y4,
                    	@M5, @Y5,
                    	@M6, @Y6,
                    	@M7, @Y7
                    ) 
		END

---------------------------------------------------------------------------------------
--> SUPPLIER PAYMENTS: Unpaid Transactions
    IF @Choice = 2
        BEGIN

            SELECT
                t.AO_Transactions_ID AS [ID], 
                t.AO_Suppliers_ID AS [Supplier_ID], 
                t.To_Be_Paid AS [Pay], 
                t.To_Be_Paid_Amount AS [To Pay],
                t.Settlement_Discount AS [Settlement],
                t.Remittance_Balance AS [Balance], 
                ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) as [Owing], 
                tt.[Description] AS [Type],
                t.Document_Number AS [Ref No],
                t.Document_Date AS [Date], 
                m.[Description] AS [Month],
                y.[Description] AS [Year],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Paid],
                t.AO_GRV_ID AS [GRV],
                gr.AO_Orders_ID AS [Order],
                u.[UserName] AS [User],
        --NB: IF ANY COLUMNS ARE ADDED BEFORE AGEING BELOW, MODIFY HIDEROWS ORDINAL POSITION
        		a.[Current],
        		a.[30 Days],
        		a.[60 Days],
        		a.[90 Days],
        		a.[120 Days],
        		a.[150 Days],
        		a.[180+ Days]
        	FROM AO_Transactions t
                LEFT JOIN dbo.fn_AO_Supplier_Period_Ageing
                            (
                            	@SupplierID, 
                            	@M1, @Y1,
                            	@M2, @Y2,
                            	@M3, @Y3,
                            	@M4, @Y4,
                            	@M5, @Y5,
                            	@M6, @Y6,
                            	@M7, @Y7
                            ) a
                    ON t.AO_Transactions_ID = a.[ID]
                LEFT JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                LEFT JOIN AO_GRV gr
                    ON t.AO_GRV_ID = gr.AO_GRV_ID
                LEFT JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                LEFT JOIN Slu_AW_Months m
                    ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        	WHERE t.AO_Suppliers_ID = @SupplierID AND
                 (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
                 (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement
                  t.Sys_AW_Transaction_Types_ID = 8 OR        --Supplier Invoice
                  t.Sys_AW_Transaction_Types_ID = 9 OR        --Supplier Refund
                  t.Sys_AW_Transaction_Types_ID = 10 OR       --Supplier Journal
                  t.Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment
            ORDER BY t.Slu_AW_Years_ID, t.Slu_AW_Months_ID, t.Document_Date
        END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AO_Transactions_Periods_Ageing_Select
--Purpose       :NEW: Supplier Transaction by PERIOD and PERIOD AGEING
--Functionality :
--Parameters    :
--Date          :2002/10/29
--Authors       :TB
--Version       :1.0.0
--Mods          :01/11/02 - Added 'Payable' Column in Account Balances
--              :04/11/02 - Removed superfluous '@CompanyID int' parameter (position 2)
--              :17/04/03 - Added 'Net Amount' and 'Tax' columns in choice 2 for
--              :           Supplier Catalog 'Account Balances' tab
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AO_Transactions_Periods_Ageing_Select
    (
        @Choice tinyint,
    	@SupplierID int, 
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
    )

AS

SET NOCOUNT ON

--> SUPPLIER CATALOG: Account Balances tab (Ageing Totals)
	IF @Choice = 1
        BEGIN
            SELECT
             	[SupplierID],
            	[Payment],
            	[Amount],
            	[Current],
            	[30 Days],
            	[60 Days],
            	[90 Days],
            	[120 Days], 
            	[150 Days],
            	[180+ Days]
            FROM dbo.fn_AO_Supplier_Period_Ageing_Values
                    (
                    	@SupplierID, 
                    	@M1, @Y1,
                    	@M2, @Y2,
                    	@M3, @Y3,
                    	@M4, @Y4,
                    	@M5, @Y5,
                    	@M6, @Y6,
                    	@M7, @Y7
                    ) 
		END

---------------------------------------------------------------------------------------
--> SUPPLIER CATALOG: Account Balances tab (Unpaid Transactions)
    IF @Choice = 2
        BEGIN
    		SELECT    
    			t.AO_Transactions_ID AS [ID], 
    			t.AO_Suppliers_ID AS [SupplierID],
        		ISNULL(tt.[Description], '') AS [Type], 
    			t.Document_Date AS [Date],
                m.[Description] AS [Month],
                y.[Description] AS [Year],
    			ISNULL(t.Document_Number, '') AS [Ref No], 
    			t.Date_Captured AS [Captured],

                ISNULL(t.Net_Amount, 0) AS [Net Amount], 
                ISNULL(t.Total_Tax_Amount, 0) AS [Tax], 
    			ISNULL(t.Total_Amount, 0) AS [Amount], 
    			ISNULL(t.Payment_Amount, 0) AS [Payment],

    			ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount,0) AS [Old Balance],
    			t.Total_Amount AS [Balance],
                ISNULL(t.To_Be_Paid_Amount, 0) AS [Payable],
    			ISNULL(t.Comment, '') AS [Comment],
    --NB: IF ANY COLUMNS ARE ADDED BEFORE AGEING BELOW, MODIFY HIDEROWS ORDINAL POSITION
    			a.[Current],
    			a.[30 Days],
    			a.[60 Days],
    			a.[90 Days],
    			a.[120 Days],
    			a.[150 Days],
    			a.[180+ Days],
                a.[User]
    		FROM vw_AO_Transactions t
                LEFT JOIN dbo.fn_AO_Supplier_Period_Ageing
                            (
                            	@SupplierID, 
                            	@M1, @Y1,
                            	@M2, @Y2,
                            	@M3, @Y3,
                            	@M4, @Y4,
                            	@M5, @Y5,
                            	@M6, @Y6,
                            	@M7, @Y7
                            ) a
                    ON t.AO_Transactions_ID = a.[ID]
                LEFT JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                LEFT JOIN Slu_AW_Months m
                    ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
    		WHERE t.AO_Suppliers_ID = @SupplierID AND
                 (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
                 (t.Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement
                  t.Sys_AW_Transaction_Types_ID = 8 OR    --Supplier Invoice
                  t.Sys_AW_Transaction_Types_ID = 9 OR    --Supplier Refund
                  t.Sys_AW_Transaction_Types_ID = 10 OR   --Supplier Journal
                  t.Sys_AW_Transaction_Types_ID = 12)     --Supplier Payment
            ORDER BY t.Document_Date DESC

        END


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AO_Transactions_Select_Pre_Date
--Purpose       :Supplier Payments: Unpaid Remittance Transactions
--Functionality :
--Parameters    :
--Date          :2002/01/12
--Authors       :TB 
--Version       :1.0.0
--Mods          :13/06/02 - Added additional info for each transaction and
--              :           removed Date_Captured
--              :30/10/02 - Added Month & Year to Unpaid Transactions grid
--              :04/11/02 - Added retrieving only specific Transaction Types
--              :04/11/02 - Added Ageing parameters and Ageing retrieval
--              :           from fn_AO_Supplier_Period_Ageing
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AO_Transactions_Select_Pre_Date

    (
        @SupplierID int,
--         @BeforeDate datetime,
--         @Company_ID int 
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
    )

AS

SET NOCOUNT ON

    SELECT
        t.AO_Transactions_ID AS [ID], 
        t.AO_Suppliers_ID AS [Supplier_ID], 
        t.To_Be_Paid AS [Pay], 
        t.To_Be_Paid_Amount AS [To Pay],
        t.Remittance_Balance AS [Balance], 
        ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) as [Owing], 
        tt.[Description] AS [Type],
        t.Document_Number AS [Ref No],
        t.Document_Date AS [Date], 
        m.[Description] AS [Month],
        y.[Description] AS [Year],
        t.Total_Amount AS [Total],
        t.Payment_Amount AS [Paid],
        t.AO_GRV_ID AS [GRV],
--        gr.Delivery_Note_Number AS [D/N],
        gr.AO_Orders_ID AS [Order],
        u.[UserName] AS [User],
--NB: IF ANY COLUMNS ARE ADDED BEFORE AGEING BELOW, MODIFY HIDEROWS ORDINAL POSITION
		a.[Current],
		a.[30 Days],
		a.[60 Days],
		a.[90 Days],
		a.[120 Days],
		a.[150 Days],
		a.[180+ Days]
	FROM AO_Transactions t
        LEFT JOIN dbo.fn_AO_Supplier_Period_Ageing
                    (
                    	@SupplierID, 
                    	@M1, @Y1,
                    	@M2, @Y2,
                    	@M3, @Y3,
                    	@M4, @Y4,
                    	@M5, @Y5,
                    	@M6, @Y6,
                    	@M7, @Y7
                    ) a
            ON t.AO_Transactions_ID = a.[ID]
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AO_GRV gr
            ON t.AO_GRV_ID = gr.AO_GRV_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN Slu_AW_Months m
            ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years y
            ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
	WHERE t.AO_Suppliers_ID = @SupplierID AND
-- 		  t.Document_Date <= @BeforeDate AND
-- 		  (ISNULL(t.Total_Amount,0) + ISNULL(Payment_Amount,0)) <> 0 AND
-- 		  t.AW_User_Companies_ID = @Company_ID
         (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
         (t.Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement
          t.Sys_AW_Transaction_Types_ID = 8 OR    --Supplier Invoice
          t.Sys_AW_Transaction_Types_ID = 9 OR    --Supplier Refund
          t.Sys_AW_Transaction_Types_ID = 10)     --Supplier Journal
    ORDER BY t.Slu_AW_Years_ID, t.Slu_AW_Months_ID





SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--Description   :sp_AO_Update_Candidates_Supplier
--Purpose       :Use to update the Order candidates 
--Functionality :
--Parameters    :
--Date          : 2001/04/12
--Authors       : Charl
--Version       : 1.0.0

CREATE      PROCEDURE sp_AO_Update_Candidates_Supplier
(
    @AO_Order_Candidates_ID int,
    @AO_Suppliers_ID int ,
	@Qty decimal(6,3),
	@Notes	varchar(50)
)

AS
SET NOCOUNT ON
BEGIN
	UPDATE AO_Order_Candidates 
	SET AO_Suppliers_ID = @AO_Suppliers_ID,
		Qty = @Qty,
		Notes = @Notes
	WHERE AO_Order_Candidates_ID = @AO_Order_Candidates_ID

END 







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--Description   :sp_AO_Update_Forecast_Product_Detail
--Purpose       :
--Functionality :
--Parameters    :
--Date          : 2001/08/30
--Authors       : Charl
--Version       : 1.0.0

CREATE PROCEDURE [dbo].[sp_AO_Update_Forecast_Product_Detail]
(
    @AO_Suppliers_ID int ,
	@AP_Product_ID int,
	@Service_Level Decimal(9,3),
	@Min_Order_Qty Decimal(9,3),
	@Max_Order_Qty Decimal(9,3),
	@Lead_Time smallint,
    @UserID		int 
)

AS
SET NOCOUNT ON
BEGIN

	UPDATE AP_Products 
	SET Service_Level  = @Service_Level,
		Min_Order_Qty = @Min_Order_Qty,
		Max_Order_Qty = @Max_Order_Qty,
		[User_ID] = @UserID
	WHERE AP_Products_ID = @AP_Product_ID

	UPDATE AP_Products_Suppliers
	SET Lead_Time = @Lead_Time
	WHERE AP_Products_ID = @AP_Product_ID AND
		AO_Suppliers_ID = @AO_Suppliers_ID

END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AO_Update_Order_Candidates_Temp_Supplier
--Purpose       :Update Inventory Manager temp table supplier change
--Date          :05 OCT 2003
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AO_Update_Order_Candidates_Temp_Supplier
    (
       	@CandidateID int,
       	@SupplierID int,
       	@ProductID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProductSupplierID int,
            @ISNUMERICDiscPerc tinyint,
            @ISDATEDiscDate tinyint,
            @DiscPerc decimal(5,2),
            @DiscDate datetime,
            @DiscPercTemp decimal(5,2),
            @ReturnCode tinyint


    SET @ReturnCode = 0    --Unsuccessful

    SET @DiscPercTemp = 0

    SELECT @ProductSupplierID = AP_Products_Suppliers_ID,
           @ISNUMERICDiscPerc = ISNUMERIC(Trade_Disc_Perc),
           @ISDATEDiscDate = ISDATE(Trade_Disc_Date),
           @DiscPerc = Trade_Disc_Perc,
           @DiscDate = Trade_Disc_Date
    FROM AP_Products_Suppliers
    WHERE AP_Products_ID = @ProductID AND
          AO_Suppliers_ID = @SupplierID


    IF @ProductSupplierID IS NULL
        BEGIN
            SET @ReturnCode = 0             --Supplier not LINKED to Product
            RETURN @ReturnCode
        END

--    IF NOT @DiscPerc IS NULL AND ISNUMERIC(@DiscPerc)
    IF @ISNUMERICDiscPerc = 1        --TRUE
        BEGIN
            SET @DiscPercTemp = @DiscPerc
        END
    ELSE
        BEGIN
--            SET @DiscPercTemp = 0

            SET @ReturnCode = 1             --Invalid Discount %
            RETURN @ReturnCode
        END


--    IF NOT @DiscDate IS NULL AND ISDATE(@DiscDate)
    IF @ISDATEDiscDate = 1           --TRUE
        BEGIN
            IF @DiscDate <= getdate()
                BEGIN
                    SET @DiscPercTemp = @DiscPerc
                END
            ELSE
                BEGIN
                    SET @ReturnCode = 2    --Invalid Effective Date
                    RETURN @ReturnCode
                END
        END
    ELSE
        BEGIN
            SET @ReturnCode = 2            --Invalid Effective Date
            RETURN @ReturnCode
        END


    UPDATE AO_Order_Candidates_Temp
    SET AO_Suppliers_ID = @SupplierID,
        Trade_Discount = @DiscPercTemp
    WHERE AO_Order_Candidates_Temp_ID = @CandidateID


    SET @ReturnCode = 3                    --Success



RETURN @ReturnCode



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   :sp_AO_Update_Order_Details
--Purpose       :updates order details 
--Functionality :Update
--Parameters    :
--Date          : 2001/04/23
--Authors       : Charl 
--Version       :1.0.0

CREATE    PROCEDURE sp_AO_Update_Order_Details
(
	@AO_Order_Details_ID int,
	@Order_Qty decimal(6,3),
	@Unit_Price money,
	@Trade_Discount_Formula_ID smallint,
	@Trade_Discount_Amount money,
	@Rebate_Formula_ID smallint,
	@Rebate_Discount_Amount money,
	@Other_Discount_Formula_ID smallint,
	@Other_Discount_Amount money,
	@Net_Amount money,
    @Sys_AW_Tax_Codes_ID int,
	@Tax_Amount money,
	@Total_Cost money,
	@Back_Order_Qty Decimal(6,3),
	@Free_Qty Decimal(6,3),
	@Lead_Time smallint
)
AS
BEGIN
	UPDATE AO_Order_Details
		SET	Order_Qty = @Order_Qty,
		Unit_Price = @Unit_Price,
		Trade_Discount_Formula_ID = @Trade_Discount_Formula_ID,
		Trade_Discount_Amount = @Trade_Discount_Amount ,
		Rebate_Formula_ID = @Rebate_Formula_ID,
		Rebate_Discount_Amount = @Rebate_Discount_Amount,
		Other_Discount_Formula_ID = @Other_Discount_Formula_ID,
		Other_Discount_Amount = @Other_Discount_Amount,
		Net_Amount = @Net_Amount,
		Sys_AW_Tax_Codes_ID = @Sys_AW_Tax_Codes_ID,
		Tax_Amount = @Tax_Amount,
		Total_Cost = @Total_Cost,
		Back_Order_Qty = @Back_Order_Qty,
		Free_Qty = @Free_Qty,
		Lead_Time = @Lead_Time
	WHERE AO_Order_Details_ID = @AO_Order_Details_ID

	DECLARE @ProductID int,@SupplierID int
	
	SELECT @ProductID = AP_Products_ID FROM AO_Order_Details WHERE AO_Order_Details_ID = @AO_Order_Details_ID
	
	SELECT @SupplierID = AO_Suppliers_ID FROM AO_Orders WHERE AO_Orders_ID = (SELECT AO_Orders_ID FROM AO_Order_Details WHERE AO_Order_Details_ID = @AO_Order_Details_ID)
	
	UPDATE AP_Products_Suppliers SET Lead_Time = @Lead_Time WHERE AP_Products_ID = @ProductID AND AO_Suppliers_ID = @SupplierID

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   :sp_AO_Update_Order_No
--Purpose       :Gets the next Order no from Sys_AW_Transaction_Types
--Functionality :
--Parameters    :
--Date          : 2001/05/03
--Authors       : Charl
--Version       :1.0.0

CREATE  PROCEDURE sp_AO_Update_Order_No

AS
    SET NOCOUNT ON

DECLARE	@LastNumber decimal(7,0)

BEGIN	

	SELECT @LastNumber = Last_Number 
	FROM Sys_AW_Transaction_Numbers
	WHERE Sys_AW_Transaction_Types_ID = 14
	
	SET @LastNumber = @LastNumber + 1
	UPDATE Sys_AW_Transaction_Numbers SET Last_Number = @LastNumber WHERE Sys_AW_Transaction_Types_ID = 14

END 






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AO_Update_Remitance_Detail
--Purpose       :Updates AO_Transactions with Purchase Invoices marked for payment
--Functionality :
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--:             :16/12/03 - Added @Settlement parameter for NEW Settlement_Discount
-------------------------------------------------------------------------------

CREATE     PROCEDURE sp_AO_Update_Remittance_Detail

    (
        @AO_Transactions_ID int,
        @Pay bit,
        @Amount money,
        @Settlement money,
        @Balance money,
        @Company_ID int 
    )

AS

SET NOCOUNT ON

    UPDATE AO_Transactions
    SET To_Be_Paid = @Pay, 
        To_Be_Paid_Amount = @Amount,
        Settlement_Discount = @Settlement,
        Remittance_Balance = @Balance
    WHERE AO_Transactions_ID = @AO_Transactions_ID AND
          AW_User_Companies_ID = @Company_ID
 
SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Update_Sales_Orders
--Purpose       :
--Date          :2017-02-09
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Update_Sales_Orders]
    (
    	@AO_GRV_ID	int,
		@ProductID	int,
    	@Qty		Decimal(18,3),
       	@CompanyID	int
    )
AS

SET NOCOUNT ON

	DECLARE @AS_Transaction_Details_ID		Int,
			@Back_Order						Decimal(18,3),
			@Sales_Order_BO_Qty				Decimal(18,3),
			@Received_Qty					Decimal(18,3),
			@Apply_Qty						Decimal(18,3),
			@Transaction_Number				Varchar(19),
			@Notes							Varchar(500),
			@Found							Int

	SET @Received_Qty = @Qty

	DECLARE GetData CURSOR
	FOR
	SELECT 
			AS_Transaction_Details_ID, 
			Back_Order,
			Transaction_Number
	FROM AS_Transactions h
		INNER JOIN AS_Transaction_Details d
			ON h.AS_Transactions_ID = d.AS_Transactions_ID
	WHERE	h.Sys_AW_Transaction_Types_ID = 16 AND
			AP_Products_ID = @ProductID AND
			Back_Order <> 0 AND
			Lup_AP_Product_Bins_ID = 1	--Only Product Bin 1, GRV Defaults to 1
	ORDER BY h.Date_Captured ASC

	OPEN GetData

	FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @Back_Order, @Transaction_Number
	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @Notes = ''
		SET @Found = 0

		IF @Back_Order <= @Qty
		BEGIN
	
			SET @Apply_Qty = @Back_Order
		
			UPDATE AS_Transaction_Details
			SET Back_Order = 0,
				Quantity = Quantity + @Apply_Qty
			WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID
		
			SELECT @Notes = Notes
			FROM AO_GRV
			WHERE AO_GRV_ID = @AO_GRV_ID

			IF @Notes = ''
			BEGIN
				SET @Notes = 'Sales Order Replenished: ' + @Transaction_Number
			END
			ELSE
			BEGIN
				SELECT @Found = CHARINDEX(@Transaction_Number, @Notes)

				IF @Found = 0
					SELECT @Notes = @Notes + ', ' + @Transaction_Number
			END

			UPDATE AO_GRV
			SET Notes = @Notes
			WHERE AO_GRV_ID = @AO_GRV_ID

		END
		ELSE
		IF @Back_Order > @Qty
		BEGIN
	
			UPDATE AS_Transaction_Details
			SET Back_Order = Back_Order - @Qty,
				Quantity = Quantity + @Qty
			WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID
		
			SELECT @Notes = Notes
			FROM AO_GRV
			WHERE AO_GRV_ID = @AO_GRV_ID

			IF @Notes = ''
			BEGIN
				SET @Notes = 'Sales Order Replenished: ' + @Transaction_Number
			END
			ELSE
			BEGIN
				SELECT @Found = CHARINDEX(@Transaction_Number, @Notes)

				IF @Found = 0
					SELECT @Notes = @Notes + ', ' + @Transaction_Number
			END

			UPDATE AO_GRV
			SET Notes = @Notes
			WHERE AO_GRV_ID = @AO_GRV_ID

		END
	
		FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @Back_Order, @Transaction_Number
	END
	CLOSE GetData
	DEALLOCATE GetData

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   : sp_AO_Update_Supplier_Payment_Detail
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/10/11
--Authors       : Charl
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE PROCEDURE sp_AO_Update_Supplier_Payment_Detail

(
    @AO_Supplier_ID int,
	@Credit_Terms_ID tinyint,
	@Settlement_Disc Decimal(5,2),
    @Company_ID int 
)

AS

    SET NOCOUNT ON

UPDATE AO_Suppliers
	SET Slu_AW_Credit_Terms_ID = @Credit_Terms_ID, 
		Default_Settlement_Discount = @Settlement_Disc 
WHERE AO_Suppliers_ID = @AO_Supplier_ID AND
	  AW_User_Companies_ID = @Company_ID
 








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AP_2000
--Purpose       : Retrieves List of Products based on Search Filter for ProductAnalyst
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
---------------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_2000
    @CompanyID int, 
    @SearchFilter int,
    @FetchChoice int,
    @Value int,
    @StartDate as datetime,
    @EndDate as datetime

AS

SET NOCOUNT ON

-->ALL Products
    IF @SearchFilter = 0
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as [Code]
        FROM AP_Products
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
-->ALL Products with Sales
    IF @SearchFilter = 1
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as [Code]
        FROM AP_Products
        WHERE AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->ALL Products with No Sales
    IF @SearchFilter = 2
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE AP_Products_ID not in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->TOP 20%
    IF @SearchFilter = 3
        SELECT  ID, Product, [Code]
        FROM dbo.fn_AP_Top20Perc_Products_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate)
    ELSE
-->NEXT 30%
    IF @SearchFilter = 4
        SELECT  a.ID, a.Product, a.[Code]
        FROM dbo.fn_AP_Top50Perc_Products_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AP_Top20Perc_Products_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.ID = b.ID
        WHERE b.ID is null
    ELSE
-->LAST 50%
    IF @SearchFilter = 5        SELECT  a.ID, a.Product, a.[Code]
        FROM dbo.fn_AP_Top100Perc_Products_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AP_Top50Perc_Products_GP(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.ID = b.ID
        WHERE b.ID is null
    ELSE
-->TYPE
    IF @SearchFilter = 6
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Types_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->GROUP
    IF @SearchFilter = 7
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Groups_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->SUPPLIER
    IF @SearchFilter = 8
        SELECT p.AP_Products_ID as [ID], p.[Description] as Product, Product_Code as [Code]
        FROM AP_Products p
                 JOIN AO_Suppliers s
                     ON p.Default_Supplier_ID = s.AO_Suppliers_ID
                 JOIN AP_Products_Suppliers ps
                     ON p.AP_Products_ID = ps.AP_Products_ID 
        WHERE ps.AO_Suppliers_ID = @Value AND
              p.AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->DEPARTMENT
    IF @SearchFilter = 9
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Departments_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->MANUFACTURER
    IF @SearchFilter = 10
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Manufacturers_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->LOCATION
    IF @SearchFilter = 11
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Lup_AP_Product_Locations_ID = @Value AND
              AP_Products_ID in
                (SELECT DISTINCT AP_Products_ID
                 FROM AS_Transaction_Details
                 WHERE dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1)
        ORDER BY Description
    ELSE
-->Below MSL
    IF @SearchFilter = 12
        SELECT AP_Products_ID as [ID], [Description] as Product, Product_Code as Code
        FROM AP_Products
        WHERE Min_Stock_Level > 0 AND
              On_Hand <= Min_Stock_Level
        ORDER BY Description

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AP_2010
--Purpose       : Retrieves Sales for One Product from AS_Transactions for ProductAnalyst
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
---------------------------------------------------------------------------------------
--Returns a recordset of:
--    prior 24 WEEKS sales, aggregated by WEEK NUMBER 
--    prior 24 MONTH sales, aggregated by MONTH NUMBER
---------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE                     PROCEDURE sp_AP_2010
	@ProductID int,
    @DataChoice int,
	@StartDate datetime,
	@EndDate datetime,
	@StartWeekNo int OUTPUT,
	@EndWeekNo int OUTPUT 

AS

SET NOCOUNT ON

IF @DataChoice = 0    --Weeks
    BEGIN
        SET @StartWeekNo = CONVERT(int, @StartDate) / 7
        SET @EndWeekNo = CONVERT(int, @EndDate) / 7

        SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
               SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
               SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
               SUM(d.Discount_Amount) as Discount,
               SUM(d.Quantity * d.Unit_Cost) as Cost,
               SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
               SUM(d.Quantity) as Quantity
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
             (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
              CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4)
        GROUP BY CONVERT(int, h.Transaction_Date) / 7
        ORDER BY WeekNo DESC
    END

ELSE    --Months
    BEGIN
        SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
        SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
        
        SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
               SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
               SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
               SUM(d.Discount_Amount) as Discount,
               SUM(d.Quantity * d.Unit_Cost) as Cost,
               SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
               SUM(d.Quantity) as Quantity
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
             (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
              dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4)
        GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
        ORDER BY DateString DESC
    END

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   : sp_AP_2020
--Purpose       : Retrieves Quotes, Sales Orders, Job Cards
--              : for One Product from AS_Transactions for ProductAnalyst
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
--MODS          : 2002/04/21 - Changed Sales Orders to Invoices & Credit Notes
--              :24/06/04 - Added Status field to Job Cards in @DataChoice = 2
-------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE            PROCEDURE sp_AP_2020
    (
        @ProductID int,
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

-->Quotes
    IF @DataChoice = 0
        BEGIN
            SELECT h.Transaction_Number as [Number],
                   h.Transaction_Date as [Date],
                   h.Expiry_Date as [Expires],
                   CASE WHEN Firstnames IS NULL and Initials IS NULL
                            THEN ISNULL(Surname,'')
                            ELSE ISNULL(Surname,'') + ', ' + 
                                 LTRIM(ISNULL(Firstnames,'') + ' ' + 
                                       ISNULL(t.Description,'') + ' ' +
                                       ISNULL(Initials,''))
                            END AS [Customer],
                   d.Quantity as [Qty],
                   d.Extended_Amount as [Amount],
                   d.Tax_Amount as [Tax],
                  (d.Quantity * d.Unit_Cost) as [Total Cost],
                  (d.Unit_Price - d.Original_Price) * d.Quantity as [Price Disc],
                   d.Discount_Amount as [Sales Disc],
                  (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost) as [Income]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c ON h.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE d.AP_Products_ID = @ProductID AND
                  h.Sys_AW_Transaction_Types_ID = 1 AND    --Quote
                  h.Slu_AW_Active_ID <> 3 AND
                 (d.Date_captured >= @StartDate AND 
                  d.Date_captured <= @EndDate)
            ORDER BY [Date] DESC, [Number] 
        END
    ELSE
-->Invoices and Refunds        -- WAS: Sales Orders
    IF @DataChoice = 1
        BEGIN
            SELECT h.Transaction_Number as [Number],
                   h.Transaction_Date as [Date],
                   CASE WHEN Firstnames IS NULL and Initials IS NULL
                            THEN ISNULL(Surname,'')
                            ELSE ISNULL(Surname,'') + ', ' + 
                                 LTRIM(ISNULL(Firstnames,'') + ' ' + 
                                       ISNULL(t.Description,'') + ' ' +
                                       ISNULL(Initials,''))
                            END AS [Customer],
                   d.Quantity as [Qty],
                   d.Extended_Amount as [Amount],
                   d.Tax_Amount as [Tax],
                  (d.Quantity * d.Unit_Cost) as [Total Cost],
                  (d.Unit_Price - d.Original_Price) * d.Quantity as [Price Disc],
                   d.Discount_Amount as [Sales Disc],
                  (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost) as [Income]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c ON h.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE d.AP_Products_ID = @ProductID AND
--                  (h.Sys_AW_Transaction_Types_ID = 16 OR      --Sales Order
--                   h.Sys_AW_Transaction_Types_ID = 17) AND    --Sales Order Reversal
                 (h.Sys_AW_Transaction_Types_ID = 3 OR      --Tax Invoice
                  h.Sys_AW_Transaction_Types_ID = 4) AND    --Tax Credit Note
                 (d.Date_captured >= @StartDate AND 
                  d.Date_captured <= @EndDate)
            ORDER BY [Date] DESC, [Number]
        END
    ELSE
-->Job Cards
    IF @DataChoice = 2
        BEGIN
            SELECT h.Transaction_Number as [Number],
                   h.Transaction_Date as [Date],
                   CASE WHEN Firstnames IS NULL and Initials IS NULL
                            THEN ISNULL(Surname,'')
                            ELSE ISNULL(Surname,'') + ', ' + 
                                 LTRIM(ISNULL(Firstnames,'') + ' ' + 
                                       ISNULL(t.Description,'') + ' ' +
                                       ISNULL(Initials,''))
                            END AS [Customer],
                   d.Quantity as [Qty],
                   d.Extended_Amount as [Amount],
                   d.Tax_Amount as [Tax],
                  (d.Quantity * d.Unit_Cost) as [Total Cost],
                  (d.Unit_Price - d.Original_Price) * d.Quantity as [Price Disc],
                   d.Discount_Amount as [Sales Disc],
                  (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost) as [Income],
                   CASE WHEN h.Slu_AW_Active_ID = 1
                        THEN 'Open'
                        ELSE 'Closed'
                        END AS [Status]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c ON h.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE d.AP_Products_ID = @ProductID AND
                  h.Sys_AW_Transaction_Types_ID = 2 AND    --Job Cards
                 (d.Date_captured >= @StartDate AND 
                  d.Date_captured <= @EndDate)
            ORDER BY [Date] DESC, [Number]
        END
    ELSE
-->Orders (ALL Outstanding Orders)
    IF @DataChoice = 3
        BEGIN
        	SELECT s.Supplier_Name AS [Supplier],
                   oh.Date_Ordered AS [Ordered],
                   od.Lead_Time AS [LT],	
                   od.Order_Qty AS [Qty],	
                   od.Free_Qty AS [Free],
                   od.Back_Order_Qty AS [B/O],
                   od.Received_Qty AS [Received],
                   od.Receipt_Date AS [Date],	
                   od.Unit_Price AS [Unit Cost],
                   od.Trade_Discount_Amount AS [Trade Disc],
                   od.Rebate_Discount_Amount AS [Rebate Disc],
                   od.Other_Discount_Amount AS [Other Disc],
                   od.Net_Amount AS [Net Amount],
                   tc.[Description] AS [Tax Code],
                   od.Tax_Amount AS [Tax],
                   od.Total_Cost AS [Total Cost]
        	FROM AO_Order_Details od
                INNER JOIN AO_Orders oh
                    ON od.AO_Orders_ID = oh.AO_Orders_ID
                INNER JOIN AO_Suppliers s
                    ON oh.AO_Suppliers_ID = s.AO_Suppliers_ID
        	    LEFT JOIN Sys_AW_Tax_Codes tc
                    ON od.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        	WHERE od.AP_Products_ID = @ProductID AND
                  od.Received_Qty < (od.Order_Qty + od.Back_Order_Qty)
            ORDER BY [Ordered] DESC
        END
    ELSE
-->GRVs (Received between DatePicker dates) 
    IF @DataChoice = 4
        BEGIN
    		SELECT s.Supplier_Name AS [Supplier],
                   gh.Delivery_Note_Number AS [Del Note],
                   gh.Supplier_Reference AS [Supp Ref],
                   oh.Order_Number AS [Order No],
                   gd.Qty AS [Received],
                   gh.Date_Received AS [Date],
                   st.Document_Number AS [Invoice],
                   st.Document_Date AS [Inv Date],
                   st.Date_Captured AS [Processed],
                   st.Total_Amount AS [Inv Amount],
                  (st.Total_Amount - st.Payment_Amount) AS [Owing]
    		FROM AO_GRV_Details gd
                INNER JOIN AO_GRV gh
                    ON gd.AO_GRV_ID = gh.AO_GRV_ID
                LEFT JOIN AO_Orders oh
                    ON gh.AO_Orders_ID = oh.AO_Orders_ID
                INNER JOIN AO_Suppliers s
                    ON gh.AO_Suppliers_ID = s.AO_Suppliers_ID
                LEFT JOIN AO_Transactions st
                    ON gh.AO_GRV_ID = st.AO_GRV_ID
            WHERE gd.AP_Products_ID = @ProductID AND
                 (gh.Date_Received >= @StartDate AND 
                  gh.Date_Received <= @EndDate)
            ORDER BY [Date] DESC
        END


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AP_2030
--Purpose       : Retrieves One Product from Product Catalog for ProductAnalyst
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_2030
    (
        @ProductID int
    )

AS

SET NOCOUNT ON

SELECT
    p.AP_Products_ID AS [ID],    --1
    p.Product_Code AS [Product Code],    --2 (NO INDEX EXISTS !!!!)
    p.[Description] AS [Description],    --3
    p.SKU_Code AS [SKU Code],    --4
    pj.[Description] AS [SKU Description],    --5
    p.Print_Description AS [Print Description],    --6    
    p.Keywords AS [Keywords],    --7
    pt.[Description] AS [Type],    --8
    pg.[Description] AS [Group],    --9
    pd.[Description] AS [Department],    --10
    pl.[Description] AS [Location],    --11
    ds.Supplier_Name AS [Default Supplier],    --12
    pm.[Description] AS [Manufacturer],    --13
    p.Manufacturer_Code AS [Manuf Code],    --14
    p.Manufacturer_Description AS [Manuf Description],    --15
    p.Price1_Effective_Date AS [Price1 EffDate],    --16
    p.Price1_Price1 AS [Price1 Price1],    --17
    p.Price1_Price2 AS [Price1 Price2],    --18
    p.Price2_Effective_Date AS [Price2 EffDate],    --19
    p.Price2_Price1 AS [Price2 Price1],    --20
    p.Price2_Price2 AS [Price2 Price2],    --21
    rc.[Description] AS [Rounding Code],    --22
    p.Pack_Size AS [Pack Size],    --23
    p.Measure AS [Measure],    --24
    um.[Description] AS [Unit Of Measure],    --25
    p.Strength AS [Strength],    --26
    mc.[Description] AS [Mass Code],    --27
    p.Pack_Mass AS [Pack Mass],    --28
    p.Pack_Volume AS [Pack Volume],    --29
    p.Supercession AS [Supercession],    --30
    p.Alternate_Code1 AS [Alt1],    --31
    p.Alternate_Code2 AS [Alt2],    --32
    p.Serial_Number AS [Serial Number],    --33
    ac.[Description] AS [Active],    --34
    sm.[Description] AS [Self Managed],    --35
    p.PLU_Tab AS [PLUTab],    --36
    sb.[Description] AS [Sell By Code],    --37
    p.Last_Sale_Date AS [Last Sale Date],    --38
    sa.[Description] AS [Is Assembled Product],    --39
    p.Image_File_Name AS [Image File Name],    --40
    tc.[Description] AS [Tax Code],    --41
    dg.[Description] AS [Discount Group],    --42
    cg.[Description] AS [Commission Group],    --43
    ep.[Description] AS [Edit Price],    --44
    ed.[Description] AS [Edit Discount],    --45
--Numerics
    p.On_Hand AS [On Hand],    --46
   (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
          od.AP_Products_ID = @ProductID) AS [Qty on order],    --47
    p.Job_Reserved AS [Job Reserved],    --48
    p.Quote_Reserved AS [Quote Reserved],    --49
    p.Sales_Order_Reserved AS [Sales Order Reserved],    --50
    p.Last_Cost AS [Last Cost],    --51
    p.Average_Cost AS [Average Cost],    --52
    p.Average_Markup AS [Markup],    --53
    p.Service_Level AS [Service Level],    --54
    p.Max_Order_Qty AS [Max Order Qty],    --55
    p.Min_Order_Qty AS [Min Order Qty],    --56
    p.Min_Stock_Level AS [Min Stock Level],    --57
--Notes
    p.Memo AS [Memo]    --58

FROM AP_Products p
        LEFT JOIN AP_Products pj ON p.SKU_Code = pj.Product_Code
        LEFT JOIN Slu_AP_Units_Of_Measure um ON p.Slu_AP_Units_Of_Measure_ID = um.Slu_AP_Units_Of_Measure_ID
        LEFT JOIN Slu_AW_YesNo sm ON p.Slu_AW_YesNo_Self_Managed = sm.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AP_Product_Manufacturers pm ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID
        LEFT JOIN AO_Suppliers ds ON p.Default_Supplier_ID = ds.AO_Suppliers_ID
        LEFT JOIN Lup_AP_Product_Types pt ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
        LEFT JOIN Lup_AP_Product_Groups pg ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID
        LEFT JOIN Lup_AP_Product_Departments pd ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID
        LEFT JOIN Lup_AP_Product_Locations pl ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID
        LEFT JOIN Lup_AP_Sell_By_Codes sb ON p.Lup_AP_Sell_By_Codes_ID = sb.Lup_AP_Sell_By_Codes_ID
        LEFT JOIN Lup_AP_Rounding_Codes rc ON p.Lup_AP_Rounding_Codes_ID = rc.Lup_AP_Rounding_Codes_ID
        LEFT JOIN Sys_AW_Tax_Codes tc ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AP_Discount_Groups dg ON p.Lup_AP_Discount_Groups_ID = dg.Lup_AP_Discount_Groups_ID
        LEFT JOIN Lup_AP_Commission_Groups cg ON p.Lup_AP_Commission_Groups_ID = cg.Lup_AP_Commission_Groups_ID
        LEFT JOIN Lup_AP_Mass_Codes mc ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID
        LEFT JOIN Slu_AW_YesNo sa ON p.Slu_AW_YesNo_Assembly = sa.Slu_AW_YesNo_ID
        LEFT JOIN Slu_AW_YesNo ep ON p.Slu_AW_YesNo_Edit_Price = ep.Slu_AW_YesNo_ID
        LEFT JOIN Slu_AW_YesNo ed ON p.Slu_AW_YesNo_Edit_Discount = ed.Slu_AW_YesNo_ID
        LEFT JOIN Slu_AW_Active ac ON p.Slu_AW_Active_ID = ac.Slu_AW_Active_ID
WHERE p.AP_Products_ID = @ProductID 


SET NOCOUNT OFF





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-----------------------------------------------------------------------------------
--Description   : sp_AP_2040
--Purpose       : Retrieves the Customers of a Product for ActiveSCM - Product Analyst
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--              : Returns One Product from AS_Transactions
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
--MODS          :24/12/02 - Convert smallmoney cahnged to money to prevent overflow
-----------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE                    PROCEDURE sp_AP_2040
	@ProductID int,
	@StartDate datetime,
	@EndDate datetime

AS

SET NOCOUNT ON

    SELECT
        MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                 THEN ISNULL(Surname,'')
                 ELSE ISNULL(Surname,'') + ', ' + 
                      LTRIM(ISNULL(Firstnames,'') + ' ' + 
                            ISNULL(t.Description,'') + ' ' +
                            ISNULL(Initials,''))
                 END) AS [Customer],
        MAX(ISNULL(h.Transaction_Date,'')) AS [Last Date],
        CONVERT(money,SUM(d.Quantity)) AS [Qty],
        CONVERT(money,SUM(d.Extended_Amount)) AS [Amount],
        CONVERT(money,SUM(d.Tax_Amount)) AS [Tax],
        CONVERT(money,SUM((d.Quantity * d.Unit_Cost))) AS [Total Cost],
        CONVERT(money,SUM((d.Unit_Price - d.Original_Price) * d.Quantity)) AS [Price Disc],
        CONVERT(money,SUM(d.Discount_Amount)) AS [Sales Disc],
        CONVERT(money,SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost))) AS [Income],
        CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
             ELSE 0.00
             END AS [Act GP%],
        CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
             THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
             ELSE 0.00
             END AS [Std GP%]
    FROM AS_Transaction_Details d
        INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
        INNER JOIN AC_Customers c ON h.AC_Customers_ID = c.AC_Customers_ID
        INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
    WHERE d.AP_Products_ID = @ProductID AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4) AND
         (d.Date_Captured >= @StartDate AND
          d.Date_Captured <= @EndDate)
    GROUP BY c.AC_Customers_ID
    ORDER BY [Income] DESC

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AP_2050
--Purpose       : Retrieves the Product Interactions for Product Analyst
--              : for One Product from AW_Comments
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
---------------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE          PROCEDURE sp_AP_2050
	@CompanyID int,
	@ProductID int,
	@StartDate datetime,
	@EndDate datetime

AS

SET NOCOUNT ON

    SELECT i.AW_Comments_ID as [ID],
           i.Date_Captured AS [Date],
           CASE WHEN u.Firstname IS NULL
                THEN ISNULL(u.Surname,'')
                ELSE ISNULL(u.Surname,'') + ', ' + 
                     LTRIM(ISNULL(u.Firstname,''))
                END AS [User Name],
           i.[Comment] AS Message
    FROM AW_Comments i INNER JOIN AW_Users u
             ON i.User_ID = u.AW_Users_ID
    WHERE i.AW_User_Companies_ID = @CompanyID AND
          i.Sys_AT_Actor_Types_ID = -2 AND        --Products
          i.Actor_ID = @ProductID AND
         (i.Date_Captured >= @StartDate AND
          i.Date_Captured <= @EndDate)
    ORDER BY i.Date_Captured DESC

SET NOCOUNT OFF





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   : sp_AP_2060
--Purpose       : Retrieves List of constituent Sales Transactions in POPUP for ProductAnalyst
--              : that make up the aggregated SALES COMPONENTS
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    : Uses SHAPE and is part of sp_AP_2070
--Date          : 24 SEP 2001
--Authors       : TB
--MODS          :01/10/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :12/08/04 - Added h.Amount AS [Total], h.Comment AS [Notes]
--              :           and removed h.User_ID for Product Analyst
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_2060
	(
        @PeriodType tinyint,        --Typically 0 = WEEKS, 1 = MONTHS
        @PeriodString varchar(6),   --Typically WEEKNO or YEARMONTHNO (5297 or 200106)
        @Component_Type tinyint,    --0 = SALES, 1 = Price Discount, 2 = Sales Discount etc
	    @ProductID int
    )

AS

SET NOCOUNT ON

    ---------------------------------------------------------------------------------------------
    IF @PeriodType = 0    --WEEKS
    ---------------------------------------------------------------------------------------------
        BEGIN
        -->Sales
            IF @Component_Type = 0
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                      d.Extended_Amount - d.Tax_Amount <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC

            ELSE
        -->Price Discount
            IF @Component_Type = 1
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                    ((d.Original_Price - d.Unit_Price) * d.Quantity) <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC

            ELSE
        -->Sales Discount
            IF @Component_Type = 2
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                     (d.Discount_Amount) <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC

            ELSE
        -->Cost
            IF @Component_Type = 3
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                     (d.Quantity * d.Unit_Cost) <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC
        END
    ---------------------------------------------------------------------------------------------
    if @PeriodType = 1    --MONTHS
    ---------------------------------------------------------------------------------------------
        BEGIN
        -->Sales
            IF @Component_Type = 0
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                     (d.Extended_Amount - d.Tax_Amount) <> 0 AND
                     (MONTH(h.Transaction_Date) = CONVERT(int,SUBSTRING(@PeriodString,5,2)) AND
                      YEAR(h.Transaction_Date) = CONVERT(int,SUBSTRING(@PeriodString,1,4)))
                ORDER BY h.Transaction_Date ASC

            ELSE
        -->Price Discount
            IF @Component_Type = 1
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                    ((d.Original_Price - d.Unit_Price) * d.Quantity) <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC

            ELSE
        -->Sales Discount
            IF @Component_Type = 2
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                      d.Discount_Amount <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC

            ELSE
        -->Cost
            IF @Component_Type = 3
                SELECT h.AS_Transactions_ID as [ID],
                       ISNULL(c.Surname, '') +
                           ISNULL(' ' + c.Firstnames, '') +
                           ' (' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + ')' AS [Customer],
                       h.Amount AS [Total],
                       h.Transaction_Date AS [Date],
                       ISNULL(csh.FirstName, '') + ISNULL(' ' + csh.Surname, '') AS [Cashier],
                       h.Transaction_Number AS [No],
                       tt.Type_Code AS [Type],
                       h.Comment AS [Notes]

                FROM AS_Transactions h
                        INNER JOIN AS_Transaction_Details d
                            ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users csh
                            ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID
                WHERE d.AP_Products_ID = @ProductID AND
                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                      h.Sys_AW_Transaction_Types_ID = 4) AND
                     (d.Quantity * d.Unit_Cost) <> 0 AND
                      CONVERT(int, h.Transaction_Date) / 7 = CONVERT(int,@PeriodString)
                ORDER BY h.Transaction_Date ASC

        END


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   : sp_AP_2070
--Purpose       : Retrieves Sales Transaction Details in POPUP for ProductAnalyst
--              : that make up the aggregated SALES COMPONENTS
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    : Uses SHAPE and is part of sp_AP_2060
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_2070
	(
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID as [ID], 
           d.AS_Transactions_ID AS FKID, 
           p.Description as [Description                        ], 
          (d.Extended_Amount - d.Tax_Amount) AS [Sales    ],
         ((d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj],
          (d.Discount_Amount) AS [Discount ],
          (d.Quantity * d.Unit_Cost) AS [Cost    ],
         ((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [Income  ],
          (d.Quantity) AS [Qty ]
    FROM AS_Transaction_Details d
            LEFT JOIN AP_Products p
                ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








--Description   : sp_AP_2080
--Purpose       : Retrieves Products Lookups list based on Search Filter for ProductAnalyst
--              :
--Parameters    :
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AP_2080

   @Option varchar(30) = '',
   @CompanyID int = 1

AS

SET NOCOUNT ON

   IF @Option = 'Types'
      SELECT Lup_AP_Product_Types_ID as [ID], [Description] AS [Types]
      FROM Lup_AP_Product_Types
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Groups'
      SELECT Lup_AP_Product_Groups_ID as [ID], [Description] AS [Groups]
      FROM Lup_AP_Product_Groups
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Suppliers'
      SELECT AO_Suppliers_ID AS [ID], [Supplier_Name] AS [Suppliers]
      FROM AO_Suppliers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Departments'
      SELECT Lup_AP_Product_Departments_ID as [ID], [Description] AS [Departments]
      FROM Lup_AP_Product_Departments
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Manufacturers'
      SELECT Lup_AP_Product_Manufacturers_ID as [ID], [Description] AS [Manufacturers]
      FROM Lup_AP_Product_Manufacturers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Locations'
      SELECT Lup_AP_Product_Locations_ID as [ID], [Description] AS [Locations]
      FROM Lup_AP_Product_Locations
      WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AP_2090
--Purpose       : Retrieves Type, Group, Department Chart Data
--              : for all Product from AS_Transactions for ProductAnalyst
--Parameters    :
--Date          : 25 SEP 2001
--Authors       : TB
--Version       : 1.0.0
---------------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_2090
    (
        @CompanyID int,
        @Grouping int,
    	@StartDate datetime,
    	@EndDate datetime
    )
AS

SET NOCOUNT ON

-->Product Types
    IF @Grouping = 0
        BEGIN
            SELECT MAX(pt.[Description]) as [Type],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Types pt ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY pt.[Description]
            ORDER BY Income DESC
        END
    ELSE
-->Product Group
    IF @Grouping = 1
        BEGIN
            SELECT MAX(pg.[Description]) as [Group],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Groups pg ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY pg.[Description]
            ORDER BY Income DESC
        END
    ELSE
-->Product Department
    IF @Grouping = 2
        BEGIN
            SELECT MAX(pd.[Description]) as [Department],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Departments pd ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY pd.[Description]
            ORDER BY Income DESC
        END

SET NOCOUNT OFF





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







------------------------------------------------------------------------------
--Description   : sp_AP_2500
--Purpose       : Retrieves Category Lookup list based on Search Filter
--              : for Stock Valuation
--Parameters    :
--Date          : 14 JUL 2002
--Authors       : TB
--Version       : 1.0.0
------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_2500
    (
        @Option varchar(30) = '',
        @CompanyID int = 1
    )

AS

SET NOCOUNT ON

   IF @Option = 'All Stock'
      SELECT AW_User_Companies_ID as [ID], [Company_Name] AS [Stock]
      FROM AW_User_Companies
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Type'
      SELECT Lup_AP_Product_Types_ID as [ID], [Description] AS [Types]
      FROM Lup_AP_Product_Types
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Group'
      SELECT Lup_AP_Product_Groups_ID as [ID], [Description] AS [Groups]
      FROM Lup_AP_Product_Groups
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Supplier'
      SELECT AO_Suppliers_ID AS [ID], [Supplier_Name] AS [Suppliers]
      FROM AO_Suppliers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Department'
      SELECT Lup_AP_Product_Departments_ID as [ID], [Description] AS [Departments]
      FROM Lup_AP_Product_Departments
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Manufacturer'
      SELECT Lup_AP_Product_Manufacturers_ID as [ID], [Description] AS [Manufacturers]
      FROM Lup_AP_Product_Manufacturers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Location'
      SELECT Lup_AP_Product_Locations_ID as [ID], [Description] AS [Locations]
      FROM Lup_AP_Product_Locations
      WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--Get one Product Record
--for the AS_Transaction_Details record

CREATE     PROCEDURE sp_AP_2900
    (
    	@ProductID int,
    	@OnHand decimal(9,3)

    )
AS

SET NOCOUNT ON

    DECLARE @Selling money,
        	@LastCost money,
        	@AvgCost money,
        	@StdCost money

    SELECT @Selling = ISNULL(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()), 0)
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID

    SET @LastCost = ROUND((@Selling * .55), 2)
    SET @AvgCost = ROUND((@Selling * .52), 2)
    SET @StdCost = ROUND((@Selling * .45), 2)


    UPDATE AP_Products
    SET On_Hand = ISNULL(@OnHand, 0),
        Last_Cost = ISNULL(@LastCost, 0),
        Average_Cost = ISNULL(@AvgCost, 0),
        Standard_Cost = ISNULL(@StdCost, 0)
    WHERE AP_Products_ID = @ProductID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










CREATE    PROCEDURE sp_AP_2901
    (
        @Empty int
    )

AS

SET NOCOUNT ON


    UPDATE AP_Products
    SET On_Hand = 0,
        Last_Cost = 0,
        Average_Cost = 0,
        Standard_Cost = 0
    


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--Get one Product Record
--for the AS_Transaction_Details record

CREATE        PROCEDURE sp_AP_2910
    (
    	@ProductID int,
    	@Discount decimal(5,2),
        @Effective datetime
    )
AS

SET NOCOUNT ON

    UPDATE AP_Products_Suppliers
    SET Trade_Disc_Perc = ISNULL(@Discount, 0),
        Trade_Disc_Date = @Effective
    WHERE AP_Products_ID = @ProductID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










CREATE            PROCEDURE sp_AP_2911
    (
        @Empty int
    )

AS

SET NOCOUNT ON


    UPDATE AP_Products_Suppliers
    SET Trade_Disc_Perc = 0,
        Trade_Disc_Date = NULL


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Slow_Moving_Stock
--Purpose       :ADD COLUMNS to AP_Enterprise_Slow_Moving_Stock table
--Date          :2006/10/05
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AP_Add_Column_Enterprise_Slow_Moving_Stock
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Slow_Moving_Stock'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Slow_Moving_Stock ADD ' + @ColumnName + ' decimal(12, 3) NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Stock
--Purpose       :ADD COLUMNS to AP_Enterprise_Stock table
--Date          :2006/05/23
--Authors       :TB
--MODS          :
--2004.3.2      :20/09/06 - Changed datetype for column from int to decimal(12, 3)
--              :20/09/06 - Added EXPLICIT validation if @ColumnName (syscolumns.id)
--              :           exists for AP_Enterprise_Stock table
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AP_Add_Column_Enterprise_Stock
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Stock'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Stock ADD ' + @ColumnName + ' decimal(12, 3) NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Stock_Filter
--Purpose       :ADD COLUMNS to AP_Enterprise_Stock_Filter table
--Date          :2006/09/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Add_Column_Enterprise_Stock_Filter
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Stock_Filter'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Stock_Filter ADD ' + @ColumnName + ' decimal(12, 3) NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Stock_MSL
--Purpose       :ADD COLUMNS to AP_Enterprise_Stock_MSL table
--Date          :2008/12/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AP_Add_Column_Enterprise_Stock_MSL
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Stock_MSL'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Stock_MSL ADD ' + @ColumnName + ' decimal(12, 3) NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Stock_Replenish
--Purpose       :ADD COLUMNS to AP_Enterprise_Stock_Replenish table
--Date          :2008/12/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AP_Add_Column_Enterprise_Stock_Replenish
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Stock_Replenish'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Stock_Replenish ADD ' + @ColumnName + ' decimal(12, 3) NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Stock_Replenish_Max
--Purpose       :ADD COLUMNS to AP_Enterprise_Stock_Replenish_Max table
--Date          :2009/07/23
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AP_Add_Column_Enterprise_Stock_Replenish_Max
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Stock_Replenish_Max'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Stock_Replenish_Max ADD ' + @ColumnName + ' decimal(12, 3) NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Column_Enterprise_Valuation
--Purpose       :ADD COLUMNS to AP_Enterprise_Stock_Valuation table
--Date          :2006/09/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Add_Column_Enterprise_Stock_Valuation
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AP_Enterprise_Stock_Valuation'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AP_Enterprise_Stock_Valuation ADD ' + @ColumnName + ' money NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Product_To_Stock_Transfer
--Purpose       :Check if @ProductID EXISTS in Stock Transfer
--				:If EXISTS then UPDATE else ADD new Stock Transfer
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2	2016-10-03	RL	:Added Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Add_Product_To_Stock_Transfer]
    (
        @CustomerID int,
        @ProductID int,
        @Description varchar(50),
        @ProductCode varchar(20),
        @Quantity decimal(9, 3),
        @BackOrder decimal(9, 3),
        @OriginalPrice money,
        @UnitPrice money,
        @DiscountAmount money,
        @Amount money,
        @Tax_Rate decimal(9, 3),
        @TaxAmount money,
        @ExtendedAmount money,
        @UnitCost money,
        @Bin_ID	int,
        @DateCaptured datetime,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @ExistingID int,
            @Last_Qty decimal(9,3),
            @Last_Disc money,
            @New_Qty decimal(9,3),
            @New_Disc money,
            @SubTotal money,
            @Tax money,
            @Total money

    BEGIN

    	SELECT @ExistingID = AP_Stock_Transfer_Details_ID,
               @Last_Qty = Quantity,
               @Last_Disc = Discount_Amount
    	FROM AP_Stock_Transfer_Details
    	WHERE AP_Products_ID = @ProductID AND
    		  AC_Customers_ID = @CustomerID AND
    		  Lup_AP_Product_Bins_ID = @Bin_ID AND
    		  AW_User_Companies_ID = @CompanyID
   	

    	IF @ExistingID is NULL
    		EXEC sp_AP_Insert_Stock_Transfer_Details
                                        @CustomerID,
                                    	@ProductID,
                                    	@Description,
                                    	@ProductCode,
                                    	@Quantity,
                                        @BackOrder,
                                    	@OriginalPrice,
                                    	@UnitPrice,
                                    	@DiscountAmount,
                                    	@Amount,
                                        @Tax_Rate,
                                    	@TaxAmount,
                                    	@ExtendedAmount,
                                    	@UnitCost,
                                    	@Bin_ID,
                                    	@DateCaptured,
                                       	@UserID,
                                       	@CompanyID

    	ELSE


        --> COMBINE the new sales order with existing
            SET @New_Qty = @Last_Qty + @Quantity
            SET @New_Disc = ROUND(@Last_Disc + @DiscountAmount, 2)
            
            SET @SubTotal = ROUND((@UnitPrice * @New_Qty) - @New_Disc, 2)
            SET @Tax = ROUND((@SubTotal * (@Tax_Rate / 100)), 2)
            SET @Total = ROUND(@SubTotal + @Tax, 2)


    		UPDATE AP_Stock_Transfer_Details							
    		SET [Description] = @Description,
                Product_Code = @ProductCode,
                Quantity = @New_Qty,
                Back_Order = @BackOrder,
                Original_Price = @OriginalPrice,
                Unit_Price = @UnitPrice,
                Discount_Amount = @New_Disc,
                Amount = @SubTotal,
                Tax_Rate = @Tax_Rate,
                Tax_Amount = @Tax,
                Extended_Amount = @Total,
                Unit_Cost = @UnitCost,
                Lup_AP_Product_Bins_ID = @Bin_ID,
                Date_Captured = @DateCaptured,
                [User_ID] = @UserID,
                AW_User_Companies_ID = @CompanyID
    		WHERE AP_Stock_Transfer_Details_ID = @ExistingID

    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Allocation
--Purpose       :Allocates products to bins
--Functionality :
--Parameters    :
--Date          :2015-11-20
--Authors       :RL
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Bin_Allocation]
    (
		@Batch_No				int,
    	@AP_Products_ID			int,
    	@From_Bin_ID			int,
    	@From_Bin_On_Hand		decimal(9,3),
    	@Orig_From_Bin_On_Hand	decimal(9,3),
    	@To_Bin_ID				int,
		@Movement_Source		varchar(10),
		@Transfer_Qty			decimal(9,3),
    	@User_ID				int,
    	@Company_ID				int,
    	@ReturnMsg				varchar(200)
    )
AS

SET NOCOUNT ON

    DECLARE @From_Bin_Previous_On_Hand	decimal(9,3),
			@From_AP_Products_Bins_ID	int,
			@To_Bin_Previous_On_Hand	decimal(9,3),			
			@To_AP_Products_Bins_ID		int

	SET @From_Bin_Previous_On_Hand = 0
	SET @From_AP_Products_Bins_ID = 0
	SET @To_Bin_Previous_On_Hand = 0
	SET @To_AP_Products_Bins_ID = 0
	--SET @Transfer_Qty = 0
	SET @ReturnMsg = ''

	--SELECT @Transfer_Qty = @Orig_From_Bin_On_Hand - @From_Bin_On_Hand

	SELECT	@From_Bin_Previous_On_Hand = On_Hand,
			@From_AP_Products_Bins_ID = AP_Products_Bins_ID
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @AP_Products_ID
	AND Lup_AP_Product_Bins_ID = @From_Bin_ID

	SELECT	@To_Bin_Previous_On_Hand = On_Hand,
			@To_AP_Products_Bins_ID = AP_Products_Bins_ID
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @AP_Products_ID
	AND Lup_AP_Product_Bins_ID = @To_Bin_ID
	
	IF (@Transfer_Qty <> 0)
	BEGIN --Bin Allocation Changed
		--IF @From_Bin_Previous_On_Hand >= @Transfer_Qty
		--BEGIN --@From_Bin_On_Hand >= @Qty
			--V6.2 Update Bin Qty
			
				EXEC sp_AP_Products_Bins_Hist_Insert 
				@AP_Products_ID,--@ProductID int,
				@From_Bin_ID,--@ProductBinID int,
				@From_Bin_Previous_On_Hand,--@From_Bin_Previous_On_Hand
				@To_Bin_ID,--@ProductBinID int,
				@To_Bin_Previous_On_Hand,--From_Bin_Previous_On_Hand
    			@Transfer_Qty,--@Qty decimal(9,3)
    			'Bin Alloc',--@Source varchar(10),
    			@Batch_No,--int,
    			@User_ID,--@UserID int,
    			@Company_ID--@CompanyID int
    			
				--SELECT @Transfer_Qty = @Transfer_Qty * -1

				--EXEC sp_AP_Products_Bins_Update_Insert 
				--@AP_Products_ID,--@ProductID int,
				--@From_Bin_ID,--@ProductBinID int,
    --			@Transfer_Qty,--@Qty decimal(9,3)
    --			'Bin Alloc',--@Source varchar(10),
    --			@Batch_No,--int,
    --			@User_ID,--@UserID int,
    --			@Company_ID--@CompanyID int

		--END --@From_Bin_On_Hand >= @Qty
		--ELSE
		--BEGIN --@From_Bin_On_Hand < @Qty
		--	SELECT @ReturnMsg = Product_Code + ' - ' + [Description] + 'From Bin Quantity Was Changed By Another User. Please Redue Allocation'
		--	FROM AP_Products
		--	WHERe AP_Products_ID = @AP_Products_ID
		--END --@From_Bin_On_Hand < @Qty
	
	END --Bin Allocation Changed
	
	RETURN @ReturnMsg	

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Allocation_Select
--Purpose       :Fetch a list of Bin Allocation Batchs
--Date          :2016/04/06
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_Allocation_Select]
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT Distinct Batch_No AS [Batch_No],
           CONVERT(Varchar(20),Date_Captured,120) AS [Date]          
    FROM AP_Products_Bins_History
    WHERE AW_User_Companies_ID = 1 --@CompanyID
    AND Batch_No <> 0
    ORDER BY Batch_No DESC

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Allocation_Select_Filtered
--Purpose       :Fetch Bin Allocation Batch Details
--Date          :2016/04/06
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_Allocation_Select_Filtered]
    (
        @Batch_No	int,
        @CompanyID	int
    )

AS

SET NOCOUNT ON

    SELECT h.AP_Products_ID AS [ID],
          p.[Description] AS [Description],
          p.Product_Code AS [Code],
                    
          h.From_Bin_New_On_Hand AS [From Bin Qty],
          From_Lup_AP_Product_Bins_ID AS [From Bin],
          fb.[Description] AS [FromBin],
          fb.Email AS [From Bin Email],          
          h.From_Bin_Previous_On_Hand AS [Orig From Bin Qty],          
          
          h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand AS [Transfer],                    
          
          To_Lup_AP_Product_Bins_ID AS [To Bin],
          h.To_Bin_New_On_Hand AS [To Bin Qty],
          tb.[Description] AS [ToBin],
          tb.Email AS [To Bin Email],                    
          h.To_Bin_Previous_On_Hand AS [Orig To Bin Qty],
          
          h.From_Bin_Previous_On_Hand + h.To_Bin_Previous_On_Hand AS [All Bin Qty] ----h.On_Hand          
    FROM AP_Products_Bins_History h
		Inner Join AP_Products p
			On h.AP_Products_ID = p.AP_Products_ID
		Inner Join Lup_AP_Product_Bins fb
			On fb.Lup_AP_Product_Bins_ID = h.From_Lup_AP_Product_Bins_ID
		Inner Join Lup_AP_Product_Bins tb
			on tb.Lup_AP_Product_Bins_ID = h.To_Lup_AP_Product_Bins_ID
    WHERE h.AW_User_Companies_ID = @CompanyID
    AND Batch_No = @Batch_No
    ORDER BY [Description], h.AP_Products_ID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_History_Select
--Purpose       :Fetch a list of Bin Allocation Batchs
--Date          :2016/04/06
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_History_Select]
    (
        @AP_Products_ID		INT,
        @FromDate			DATETIME,
        @ToDate				DATETIME       
    )
AS

SET NOCOUNT ON

	SELECT	h.Date_Captured,
			h.Movement_Source,
			ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
			b.[Description],
			h.From_Bin_Previous_On_Hand As 'Previous Quantity',
			h.From_Bin_New_On_Hand As 'New Quantity',
			h.Batch_No
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins b
			ON h.From_Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID 
	WHERE h.AP_Products_ID = @AP_Products_ID
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	ORDER BY h.Date_Captured, h.From_Lup_AP_Product_Bins_ID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-- sp_AP_Bin_Select 1, 555

-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Select
--Purpose       :Filters Products Bin Allocations
--Joins         :Tables: AP_Products
--Date          :2015-11-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_Select]
	(
    	@CompanyID	int,
    	@ProductsID	int
	)

AS

SET NOCOUNT ON

	DECLARE @Include_Res_Stock_Validation	Varchar(5)
	
	SET @Include_Res_Stock_Validation = '1'
	
	SELECT @Include_Res_Stock_Validation = ISNULL(Control_Value,'0')
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkStockReservedJob'

	IF @Include_Res_Stock_Validation = '1'
	BEGIN
		SELECT 	b.[Description] AS [BIN],
				On_Hand - CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin(p.AP_Products_ID,p .Lup_AP_Product_Bins_ID)) AS [On_Hand],
				p.Lup_AP_Product_Bins_ID AS [ID]
		FROM AP_Products_Bins p
			INNER JOIN Lup_AP_Product_Bins b
				ON p.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		WHERE AP_Products_ID = @ProductsID
	END
	ELSE
	BEGIN
		SELECT 	b.[Description] AS [BIN],
				On_Hand AS [On_Hand],
				p.Lup_AP_Product_Bins_ID AS [ID]
		FROM AP_Products_Bins p
			INNER JOIN Lup_AP_Product_Bins b
				ON p.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		WHERE AP_Products_ID = @ProductsID
	END

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


----------------------------------------------------------------------------
--Description   :sp_AP_Bins_New_Batch_No
--Functionality :Create new batch number for product bin allocations
--Parameters    :
--Date          :2015/11/19
--Authors       :RL
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Bins_New_Batch_No]
    (
    	@CompanyID int,
    	@Batch_No int output
    )

AS

SET NOCOUNT ON

BEGIN

	SET @Batch_No = 0
	
	SELECT @Batch_No = ISNULL(MAX(Batch_No),0)
	FROM AP_Products_Bins_History
	
	SET @Batch_No = @Batch_No + 1
	
	RETURN @Batch_No
END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Branch_Inventory_Position
--Purpose       :Retrieves Branch Inventory position
--Functionality :    Conditional upon:
--              :        Stock < (Min_Stock_Level + On Order)
--              :        Stock > Max_Order_Qty <> 0
--              :        Is Active product
--Date          :2003/07/27
--Authors       :TB
--Version       :1.0.0
--MODS          :12/09/03 - Added CONVERT money to decimal, decimal to int
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Branch_Inventory_Position

    (
        @Filter varchar(30),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

--    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Description], '
    SET @sql = @sql + ' LEFT(ISNULL(p.Product_Code, ''''), 10) AS [Code], '

--> QTY to ORDER
    SET @sql = @sql + ' CASE WHEN  '
    SET @sql = @sql + ' (ISNULL(p.Min_Stock_Level, 0) - '
    SET @sql = @sql + '     (ISNULL(p.On_Hand, 0) + '
    SET @sql = @sql + '      ISNULL(( '
    SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '         FROM AO_Order_Details od '
    SET @sql = @sql + '             INNER JOIN AO_Orders o '
    SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '               o.Complete <> 1 AND '
    SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '            ), 0))) > 0 '
    SET @sql = @sql + ' THEN  '
    SET @sql = @sql + ' CONVERT(int, ISNULL(p.Min_Stock_Level, 0) - '
    SET @sql = @sql + '     (ISNULL(p.On_Hand, 0) + '
    SET @sql = @sql + '      ISNULL(( '
    SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '         FROM AO_Order_Details od '
    SET @sql = @sql + '             INNER JOIN AO_Orders o '
    SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '               o.Complete <> 1 AND '
    SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '            ), 0) )) '
    SET @sql = @sql + ' ELSE NULL '
    SET @sql = @sql + ' END '
    SET @sql = @sql + ' AS [To Order], '

    SET @sql = @sql + ' CONVERT(int, ISNULL(p.On_Hand, 0)) AS [Stock], '
    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL], '
    SET @sql = @sql + ' ISNULL(p.Min_Order_Qty, 0) AS [Min], '
    SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) AS [Max], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [On Order], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pend], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

--> SURPLUS STOCK
    SET @sql = @sql + ' CASE WHEN  '
    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) + '
    SET @sql = @sql + '     ISNULL(( '
    SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '         FROM AO_Order_Details od '
    SET @sql = @sql + '             INNER JOIN AO_Orders o '
    SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '               o.Complete <> 1 AND '
    SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     ), 0) > ISNULL(p.Max_Order_Qty, 0) '
    SET @sql = @sql + ' THEN  '
    SET @sql = @sql + ' CONVERT(int, ISNULL(p.On_Hand, 0) + '
    SET @sql = @sql + '     ISNULL(( '
    SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '         FROM AO_Order_Details od '
    SET @sql = @sql + '             INNER JOIN AO_Orders o '
    SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '               o.Complete <> 1 AND '
    SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     ), 0)) '
    SET @sql = @sql + ' ELSE 0 '
    SET @sql = @sql + ' END '
    SET @sql = @sql + ' AS [Surplus], '

    SET @sql = @sql + ' CONVERT(decimal(10,2), ISNULL(p.Last_Cost, 0)) AS [Last Cost], '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.[Supplier_Name] AS [' + rtrim(ltrim(@Filter)) + '] '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '
--     ELSE
--     IF @Filter = 'Sales Area'
--         SET @sql = @sql +
--             ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '
--     ELSE
--     IF @Filter = 'Sales Person'
--         SET @sql = @sql +
--             ' o.[Description] AS [' + rtrim(ltrim(@Filter)) + '] '


    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '

    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '

--------------------------------------------------------
--> (On-Hand + On-Order) > Max_Order_Qty (Surplus Stock)
--------------------------------------------------------
    SET @sql = @sql + '   AND (ISNULL(p.On_Hand, 0) + '
    SET @sql = @sql + '         ISNULL(( '
    SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '             FROM AO_Order_Details od '
    SET @sql = @sql + '                 INNER JOIN AO_Orders o '
    SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '             WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '                   o.Complete <> 1 AND '
    SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         ), 0)) > ISNULL(p.Max_Order_Qty, 0) '

--------------------------------------------------------
--> (MSL - (On-Hand + On-Order)) > 0 (Qty to Order)
--------------------------------------------------------
    SET @sql = @sql + '    OR (ISNULL(p.Min_Stock_Level, 0) - '
    SET @sql = @sql + '        (ISNULL(p.On_Hand, 0) + '
    SET @sql = @sql + '         ISNULL(( '
    SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '             FROM AO_Order_Details od '
    SET @sql = @sql + '                 INNER JOIN AO_Orders o '
    SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '             WHERE o.Date_Ordered IS NOT NULL AND '
    SET @sql = @sql + '                   o.Complete <> 1 AND '
    SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         ), 0))) > 0 '

-----------------------------------------------------

    SET @sql = @sql + ' ORDER BY [' + rtrim(ltrim(@Filter)) + '], [Description] '

--PRINT @sql

EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   :sp_AP_Cat_Select_Product_Selling_Price_History
--Purpose       :select's a specific products Selling proce history 
--Functionality :
--Parameters    : 
--Date          : 2001/06/21
--Authors       : Charl
--Version       : 1.0.0

CREATE     PROCEDURE sp_AP_Cat_Select_Product_Selling_Price_History
(
    @Product_ID int,
	@Company_ID int 
)

AS

SET NOCOUNT ON

SELECT AP_Product_Selling_Prices_ID AS ID, 
	AP_Products_ID AS [FK ID], 
	On_Hand AS [Stock On Hand],
	Prev_Price1_Effective_Date AS [Price1 Effective Date],
	Prev_Price1_Price1 AS [Price1 Price1],
	Prev_Price1_Price2 AS [Price1 Price2],
	Prev_Price2_Effective_Date AS [Price2 Effective Date],
	Prev_Price2_Price1 AS [Price2 Price1],	
	Prev_Price2_Price2 AS [Price2 Price2],
	New_Price1_Effective_Date AS [Price1 Effective Date],
	New_Price1_Price1 AS [Price1 Price1],
	New_Price1_Price2 AS [Price1 Price2],
	New_Price2_Effective_Date AS [Price2 Effective Date],
	New_Price2_Price1 AS [Price2 Price1],	
	New_Price2_Price2 AS [Price2 Price2],
	Slu_AW_Active_ID AS Active, 
	Date_Captured AS [Date Captured],
	[User_ID] AS [User ID], 
	AW_User_Companies_ID AS [Company ID] 
FROM AP_Product_Selling_Prices 
WHERE  AP_Products_ID = @Product_ID  AND 
	AW_User_Companies_ID = @Company_ID 
ORDER BY Date_Captured DESC









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   :sp_AP_Cat_Select_Product_SubAssemblies
--Purpose       :select's a specific Product's SubAssembly information 
--Functionality :
--Parameters    : 
--Date          : 2001/06/21
--Authors       : Charl
--Version       : 1.0.0

CREATE  PROCEDURE sp_AP_Cat_Select_Product_SubAssemblies
(
    @Product_ID int,
	@Company_ID int 
)

AS
SET NOCOUNT ON

SELECT AP_Products_Assemblies.AP_Products_Assemblies_ID AS [ID], 
	AP_Products_Assemblies.AP_Parent_Product_ID AS [FK ID], 
	AP_Products.[Description] AS [Description], 
	AP_Products_Assemblies.Units AS Units, 
	AP_Products_Assemblies.Slu_AW_Active_ID AS Active, 
	AP_Products_Assemblies.Date_Captured AS [Date Captured], 
	AP_Products_Assemblies.[User_ID] AS [User ID], 
	AP_Products_Assemblies.AW_User_Companies_ID AS [Company ID] 
FROM AP_Products_Assemblies INNER JOIN AP_Products 
ON AP_Products_Assemblies.AP_Parent_Product_ID = AP_Products.AP_Products_ID 
WHERE AP_Products_Assemblies.AP_Parent_Product_ID = @Product_ID AND 
	AP_Products_Assemblies.AW_User_Companies_ID = @Company_ID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   :sp_AP_Cat_Select_Product_SuperAssemblies
--Purpose       :select's a specific Product's Super Assembly information 
--Functionality :
--Parameters    : 
--Date          : 2001/06/21
--Authors       : Charl
--Version       : 1.0.0

CREATE   PROCEDURE sp_AP_Cat_Select_Product_SuperAssemblies
(
    @Product_ID int,
	@Company_ID int 
)

AS
SET NOCOUNT ON
SELECT AP_Products_Assemblies.AP_Products_Assemblies_ID AS [ID], 
	AP_Products_Assemblies.AP_Child_Product_ID AS [FK ID], 
	AP_Products.[Description] AS [Description], 
	AP_Products_Assemblies.Units AS Units, 
	AP_Products_Assemblies.Slu_AW_Active_ID AS Active, 
	AP_Products_Assemblies.Date_Captured AS [Date Captured], 
	AP_Products_Assemblies.[User_ID] AS [User ID], 
	AP_Products_Assemblies.AW_User_Companies_ID AS [Company ID] 
FROM AP_Products_Assemblies INNER JOIN AP_Products 
ON AP_Products_Assemblies.AP_Child_Product_ID = AP_Products.AP_Products_ID 
WHERE AP_Products_Assemblies.AP_Child_Product_ID = @Product_ID AND 
	AP_Products_Assemblies.AW_User_Companies_ID = @Company_ID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-----------------------------------------------------------------------------
--Description   :sp_AP_Cat_Select_Product_Suppliers
--Purpose       :Select one Product's Suppliers
--Functionality :
--Parameters    : 
--Date          :2001/12/21
--Authors       :TB
--Version       :1.0.0
--MODS          :04/10/03 - Added NEW Trade_Disc_Perc for Nett Billing and
--              :           NEW Inventory Manager's Discount column
--              :04/10/03 - Added NEW Trade_Disc_Date for NEW Discount above
-----------------------------------------------------------------------------

CREATE         PROCEDURE sp_AP_Cat_Select_Product_Suppliers
    (
        @Product_ID int,
    	@Company_ID int 
    )

AS

SET NOCOUNT ON

    SELECT
        ps.AP_Products_Suppliers_ID AS ID, 
        ps.AP_Products_ID AS [FK ID], 
        ps.AO_Suppliers_ID [Supplier ID],
        s.Supplier_Name AS [Supplier], 
        s.Supplier_Telephone AS [Tel No],
        ps.Trade_Disc_Perc AS [TradeDiscPerc], 
        ps.Trade_Disc_Date AS [TradeDiscDate], 
        ps.Lead_Time AS [Lead Time], 
        s.Supplier_Contact AS [Contact], 
        s.Contact_Cellphone AS [Cell No], 
        tdf.[Description] AS [Trade Formula],
        rdf.[Description] AS [Rebate Formula],
        ppt.[Description] AS [Price Type], 
        ogl.[Description] AS [Other Disc Acct],  
        rgl.[Description] AS [Rebate Disc Acct], 
        s.Start_Date AS [Start Date], 
        s.Credit_Limit AS [Credit Limit], 
        ct.[Description] AS [Terms], 
        st.[Description] AS [Acct status], 
        tc.[Description] AS [Tax Code], 
        s.Tax_Number AS [Tax No], 
        s.Supplier_Fax AS [Fax], 
        s.Web_Site_URL AS [Web Site], 
        s.Email_Address AS [e-Mail], 
        s.Orders_URL AS [Orders URL], 
        s.Supplier_Number AS [Supplier No], 
        act.[Description] AS [Active], 
        s.Date_Captured AS [Date Captured], 
        s.[User_ID] AS [User ID], 
        s.AW_User_Companies_ID AS [User Company] 
    FROM AP_Products_Suppliers ps 
        LEFT JOIN AO_Suppliers s 
            ON ps.AO_Suppliers_ID = s.AO_Suppliers_ID
        LEFT JOIN AW_Formulas tdf
            ON ps.AW_Trade_Discount_Formula_ID = tdf.AW_Formulas_ID
        LEFT JOIN AW_Formulas rdf
            ON ps.AW_Rebate_Discount_Formula_ID = rdf.AW_Formulas_ID
        LEFT JOIN Lup_AO_Purchase_Price_Types ppt
            ON s.Lup_AO_Purchase_Price_Types_ID = ppt.Lup_AO_Purchase_Price_Types_ID
        LEFT JOIN AB_Accounts ogl
            ON s.AB_Other_Discounts_Account_ID = ogl.AB_Accounts_ID
        LEFT JOIN AB_Accounts rgl
            ON s.AB_Rebate_Discount_Account_ID = rgl.AB_Accounts_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Account_Status st
            ON s.Sys_AC_Account_Status_ID = st.Sys_AC_Account_Status_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON s.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Slu_AW_Active act
            ON s.Slu_AW_Active_ID = act.Slu_AW_Active_ID
    WHERE ps.AP_Products_ID = @Product_ID AND 
          ps.AW_User_Companies_ID = @Company_ID
  

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-----------------------------------------------------------------------------
--Description   :sp_AP_Cat_Select_Product_Switches
--Purpose       :Select one Product's Links
--Functionality :
--Parameters    : 
--Date          :2001/12/21
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE   PROCEDURE sp_AP_Cat_Select_Product_Switches
    (
        @Product_ID int,
    	@Company_ID int 
    )

AS

SET NOCOUNT ON

    SELECT
        d.[Description] AS [Make], 
        c.[Description] AS [Model], 
        e.[Description] AS [Model Type], 
        b.[Description] AS [Model Year], 
        c.Rim_Front AS [Rim Front], 
        c.Rim_Rear AS [Rim Rear], 
        c.Tyre_Front AS [Tyre Front], 
        c.Tyre_Rear AS [Tyre Rear], 
        c.Front_Susp1 AS [Front Suspension 1], 
        c.Front_Susp2 AS [Front Suspension 2], 
        c.Rear_Susp1 AS [Rear Suspension 1], 
        c.Rear_Susp2 AS [Rear Suspension 2], 
        a.AP_Products_ID AS [FK ID] 
    FROM AP_Products_Switch3 a
        INNER JOIN AP_Switch3 b
            ON a.AP_Switch3_ID = b.AP_Switch3_ID 
        INNER JOIN AP_Switch2 c
            ON b.AP_Switch2_ID = c.AP_Switch2_ID 
        INNER JOIN AP_Switch1 d
            ON c.AP_Switch1_ID = d.AP_Switch1_ID 
        INNER JOIN Lup_AP_Switch2_Types e
            ON c.Lup_AP_Switch2_Types_ID = e.Lup_AP_Switch2_Types_ID 
    WHERE a.AP_Products_ID = @Product_ID AND 
            c.AW_User_Companies_ID = @Company_ID AND
            d.AW_User_Companies_ID = @Company_ID 


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Clear_Product_Catalog_Non_Stock
--Purpose       :CLEAR On Hand for all Non-Stock Products in Catalog
--Functionality :
--Date          :2009/04/30
--Authors       :TB
--MODS          :
--RL	V6.0	2014-12-05	:Added Product Audit Trail
--V6.2 RL	2015-11-29	:Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Clear_Product_Catalog_Non_Stock]
    (
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProductID				int,
            @ProductCode			varchar(20),
    		@User_Name				varchar(40),
            @LastCost				money,
            @AverageCost			money,
            @StandardCost			money,
            @OnHand					decimal(9,3),
            @AdjustmentType			tinyint,
            @AdjustDate				datetime,
            @Note					varchar(70),
            @RetCode				int,
            @Lup_AP_Product_Bins_ID int,
            @OppositeQty			decimal(9,3)


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    SET @RetCode = 0
    SET @AdjustmentType = 1    --Intialize as 'Adjustment' type
    SET @AdjustDate = getdate()
    SET @Note = LEFT('Non-Stock Qty Adjust by ' + @User_Name, 70)


    ------------------------------------------------------------------------------
    --> ZERO the Stock On Hand
    ------------------------------------------------------------------------------
	DECLARE Product_Cursor CURSOR FOR
        (
            SELECT p.AP_Products_ID,
                   p.Product_Code,
                   p.Last_Cost,
                   p.Average_Cost,
                   b.On_Hand,
                   b.Lup_AP_Product_Bins_ID
            FROM AP_Products p
				LEFT OUTER JOIN AP_Products_Bins b
					On p.AP_Products_ID = b.AP_Products_ID
            WHERE p.AW_User_Companies_ID =  @CompanyID AND
                  p.Slu_AW_YesNo_Non_Stock_Item = 1 AND
                  b.On_Hand <> 0
        )

	OPEN Product_Cursor

    	FETCH NEXT FROM Product_Cursor 
    	INTO
            @ProductID,
            @ProductCode,
            @LastCost,
            @AverageCost,
        	@OnHand,
        	@Lup_AP_Product_Bins_ID

    	WHILE @@FETCH_STATUS = 0
    	BEGIN

            UPDATE AP_Products
            SET On_Hand = 0,
				[User_ID] = @UserID            
            WHERE AP_Products_ID =  @ProductID
            AND On_Hand <> 0

			--Update Bin Qty
			IF @OnHand <> 0
			BEGIN
				SET @OppositeQty = @OnHand * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,					--@ProductID int,
					@Lup_AP_Product_Bins_ID,	--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'STOCK ADJ',				--@Source varchar(10),
    				0,							--@Batch_No
    				@UserID,					--@UserID int,
    				@CompanyID					--@CompanyID int
			END	

        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
		        	Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@LastCost,
                    @AverageCost,
        			@OnHand,
        		    0,
        			0,
        		    0,
        			@LastCost,
                    @AverageCost,
        			0,
        			0 ,
        			0,
        			0,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID,
        			@Lup_AP_Product_Bins_ID
                )

            SELECT @RetCode = SCOPE_IDENTITY()
    
    
        	FETCH NEXT FROM Product_Cursor 
        	INTO
                @ProductID,
                @ProductCode,
                @LastCost,
                @AverageCost,
            	@OnHand,
        		@Lup_AP_Product_Bins_ID

        END
    	
	CLOSE Product_Cursor

	DEALLOCATE Product_Cursor


RETURN @RetCode


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Clear_Stock_Exchange
--Purpose       :
--Date          :2004/01/13
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Clear_Stock_Exchange

AS

SET NOCOUNT ON


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Exchange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Exchange]

    
    CREATE TABLE [dbo].[AP_Stock_Exchange] (
    	[AP_Stock_Exchange_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[NodeName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[On_Order] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Count_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Stock_Exchange] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Exchange] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Exchange_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IDX_Product_Code_NodeName] ON [dbo].[AP_Stock_Exchange]([Product_Code], [NodeName]) ON [PRIMARY]

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Exchange].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Exchange].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Order]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Exchange].[User_ID]'

    
    setuser











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








---------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Contract_Product
--Purpose       :Deletes a selected Contract Product
--Functionality :
--Date          :2004/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Delete_Contract_Product
    (
        @ContractProductID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AC_Contract_Prices_ID
            FROM AC_Contract_Prices
            WHERE AC_Contract_Prices_ID = @ContractProductID
        )
        BEGIN
            DELETE AC_Contract_Prices
            WHERE AC_Contract_Prices_ID = @ContractProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Disabled_ProductID
--Purpose       :Delete UNUSED DISABLED Products in local DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Companion SP  :sp_AP_Select_Disabled_Products
--Date          :2008/08/01
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Disabled_ProductID]
	(
        @ProductID	int,
        @UserID		int        
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)


    SET @RetCode = 0

		SELECT	@Product_Code = ISNULL(Product_Code,''),
				@Description = ISNULL([Description],'')
		FROM AP_Products
		WHERE AP_Products_ID = @ProductID

        --> DELETE Product in RELATED tables
        DELETE AO_Order_Candidates
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Order_Candidates_Temp
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Contracts
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Product_Discounts
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Product_Selling_Prices
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Assemblies
        WHERE AP_Parent_Product_ID = @ProductID OR
              AP_Child_Product_ID = @ProductID

        DELETE AP_Products_History
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Stock_Takes
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Suppliers
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Switch3
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Promotion_Products
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Stock_Exchange
        WHERE AP_Products_ID = @ProductID


        --> NOW delete Product
        DELETE AP_Products
        WHERE AP_Products_ID = @ProductID

		INSERT INTO AP_Products_Audit
		(
			Record_Action, 
			Action_Date, 
			[User_ID],
			AP_Products_ID, 
			Field, 
			Prev_Value, 
			New_Value
		)
		VALUES
		(
			'Delete', 
			GetDate(), 
			@UserID,
			@ProductID, 
			'', 
			@Product_Code,
			@Description
		)

    SET @RetCode = 1

RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Duplicate_Product_Code
--Purpose       :DELETE DUPLICATE ProductID with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Companion SP  :sp_AP_Select_Duplicate_Product_Codes
--Date          :2007/05/03
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Duplicate_Product_Code]
	(
        @ProductCode varchar(20),
        @CompanyID int,
        @UserID		int
	)
AS

SET NOCOUNT ON

	DECLARE @ProductID int,
            @DeleteCNT int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)           


    SET @DeleteCNT = 0


	DECLARE Delete_Dups CURSOR FOR
        (
            SELECT a.AP_Products_ID
            FROM AP_Products a
                FULL OUTER JOIN AS_Transaction_Details b
                    ON a.AP_Products_ID = b.AP_Products_ID
                FULL OUTER JOIN AO_GRV_Details c
                    ON a.AP_Products_ID = c.AP_Products_ID
                FULL OUTER JOIN AO_Order_Details d
                    ON a.AP_Products_ID = c.AP_Products_ID
            WHERE b.AP_Products_ID IS NULL AND
                  c.AP_Products_ID IS NULL AND
                  d.AP_Products_ID IS NULL AND
                  a.AW_User_Companies_ID = @CompanyID AND
                  a.Product_Code = @ProductCode AND
                  a.On_Hand = 0
        )

	OPEN Delete_Dups

    	FETCH NEXT FROM Delete_Dups 
    	INTO
            @ProductID
    	
    	WHILE @@FETCH_STATUS = 0
    	BEGIN

			SELECT	@Product_Code = ISNULL(Product_Code,''),
					@Description = ISNULL([Description],'')
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID

            --> DELETE Product in RELATED tables
            DELETE AO_Order_Candidates
            WHERE AP_Products_ID = @ProductID

            DELETE AO_Order_Candidates_Temp
            WHERE AP_Products_ID = @ProductID

            DELETE AO_Supplier_Contracts
            WHERE AP_Products_ID = @ProductID

            DELETE AO_Supplier_Product_Discounts
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Inventory_Adjustments
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Product_Selling_Prices
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Assemblies
            WHERE AP_Parent_Product_ID = @ProductID OR
                  AP_Child_Product_ID = @ProductID

            DELETE AP_Products_History
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Stock_Takes
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Suppliers
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Switch3
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Promotion_Products
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Stock_Exchange
            WHERE AP_Products_ID = @ProductID


            --> NOW delete Product
            DELETE AP_Products
            WHERE AP_Products_ID = @ProductID

			INSERT INTO AP_Products_Audit
			(
				Record_Action, 
				Action_Date, 
				[User_ID],
				AP_Products_ID, 
				Field, 
				Prev_Value, 
				New_Value
			)
			VALUES
			(
				'Delete', 
				GetDate(), 
				@UserID,
				@ProductID, 
				'', 
				@Product_Code,
				@Description
			)

            SET @DeleteCNT = @DeleteCNT + 1


        	FETCH NEXT FROM Delete_Dups 
        	INTO
                @ProductID

    	END

	CLOSE Delete_Dups

	DEALLOCATE Delete_Dups

RETURN @DeleteCNT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Duplicate_Products
--Purpose       :DELETE duplicate UNUSED Product Codes with ZERO STOCK in target DB
--Functionality :    DELETE duplicate Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--              :    Uses CURSOR
--Date          :2007/05/03
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Delete_Duplicate_Products
	(
        @CompanyID int,
        @DeleteCNT int OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @ProductCode varchar(20),
            @ProductID int,
            @Dups int


    SET @DeleteCNT = 0


    --> SELECT duplicate Product Codes    
    	DECLARE Select_Dups CURSOR FOR
            (
                SELECT Product_Code,
                       count(*)
                FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand = 0
                GROUP BY Product_Code
                HAVING count(*) > 1
            )
    
    	OPEN Select_Dups
    
        	FETCH NEXT FROM Select_Dups 
        	INTO
                @ProductCode,
                @Dups
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN


            --> DELETE duplicate Product Codes ----------------------------------------
            	DECLARE Delete_Dups CURSOR FOR
                    (
                        SELECT a.AP_Products_ID
                        FROM AP_Products a
                            FULL OUTER JOIN AS_Transaction_Details b
                                ON a.AP_Products_ID = b.AP_Products_ID
                            FULL OUTER JOIN AO_GRV_Details c
                                ON a.AP_Products_ID = c.AP_Products_ID
                            FULL OUTER JOIN AO_Order_Details d
                                ON a.AP_Products_ID = c.AP_Products_ID
                        WHERE b.AP_Products_ID IS NULL AND
                              c.AP_Products_ID IS NULL AND
                              d.AP_Products_ID IS NULL AND
                              a.Product_Code = @ProductCode AND
                              a.On_Hand = 0
                    )
            
            	OPEN Delete_Dups
            
                	FETCH NEXT FROM Delete_Dups 
                	INTO
                        @ProductID
                	
                	WHILE @@FETCH_STATUS = 0
                	BEGIN

                        --> DELETE Product in RELATED tables
                        DELETE AO_Order_Candidates
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AO_Order_Candidates_Temp
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AO_Supplier_Contracts
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AO_Supplier_Product_Discounts
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Inventory_Adjustments
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Product_Selling_Prices
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Products_Assemblies
                        WHERE AP_Parent_Product_ID = @ProductID OR
                              AP_Child_Product_ID = @ProductID
        
                        DELETE AP_Products_History
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Products_Stock_Takes
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Products_Suppliers
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Products_Switch3
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Promotion_Products
                        WHERE AP_Products_ID = @ProductID
        
                        DELETE AP_Stock_Exchange
                        WHERE AP_Products_ID = @ProductID
        
        
                        --> NOW delete Product
                        DELETE AP_Products
                        WHERE AP_Products_ID = @ProductID


                        SET @DeleteCNT = @DeleteCNT + 1


                    	FETCH NEXT FROM Delete_Dups 
                    	INTO
                            @ProductID

                	END

            	CLOSE Delete_Dups

            	DEALLOCATE Delete_Dups
            --> END DELETE duplicate Product Codes ------------------------------------


            	FETCH NEXT FROM Select_Dups 
            	INTO
                    @ProductCode,
                    @Dups
    
        	END
    	
    	CLOSE Select_Dups
    
    	DEALLOCATE Select_Dups


    RETURN @DeleteCNT















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Inactive_Product
--Purpose       :DELETE ONE Redundant UNUSED Product with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE, GRV, ORDER, ADJUSTMENT exists and
--              :        Product has ZERO ON HAND
--Date          :2008/05/19
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Inactive_Product]
	(
		@ProductID int,
        @ActivityCNT tinyint,
        @OnHand decimal(9, 3),
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode		int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)

    SET @ReturnCode = 0


    --> If ZERO Sale, GRV, Order, Adjustment rows AND On_Hand
    IF @ActivityCNT = 0 AND @OnHand = 0

        BEGIN

            --> Apart from Sale, GRV, Order, and Adjustment tables
            --> DELETE Product in OTHER RELATED tables
            BEGIN TRAN Delete_Product
        
            	BEGIN
        
					SELECT	@Product_Code = ISNULL(Product_Code,''),
							@Description = ISNULL([Description],'')
					FROM AP_Products
					WHERE AP_Products_ID = @ProductID
        
                    DELETE AO_Order_Candidates
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AO_Order_Candidates_Temp
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AO_Supplier_Contracts
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AO_Supplier_Product_Discounts
                    WHERE AP_Products_ID = @ProductID
        
                    DELETE AP_Inventory_Adjustments
                    WHERE AP_Products_ID = @ProductID
        
                    DELETE AP_Product_Selling_Prices
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Assemblies
                    WHERE AP_Parent_Product_ID = @ProductID OR
                          AP_Child_Product_ID = @ProductID
                
                    DELETE AP_Products_History
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Stock_Takes
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Suppliers
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Switch3
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Promotion_Products
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Stock_Exchange
                    WHERE AP_Products_ID = @ProductID
                
					DELETE AP_Products_Audit
					WHERE AP_Products_ID = @ProductID
					
					DELETE AP_Products_Bins
					WHERE AP_Products_ID = @ProductID
                
                    --> NOW delete Product
                    DELETE AP_Products
                    WHERE AP_Products_ID = @ProductID
                
					INSERT INTO AP_Products_Audit
					(
						Record_Action, 
						Action_Date, 
						[User_ID],
						AP_Products_ID, 
						Field, 
						Prev_Value, 
						New_Value
					)
					VALUES
					(
						'Delete', 
						GetDate(), 
						@UserID,
						@ProductID, 
						'', 
						@Product_Code,
						@Description
					)
                
                    SET @ReturnCode = 1
        
                END

            COMMIT TRAN Delete_Product

        END

RETURN @ReturnCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Inactive_Prospect
--Purpose       :DELETE ONE Redundant UNUSED Prospect in target DB
--Functionality :    DELETES Prospect in AC_Prospects and all RELATED tables
--              :        WHERE transactions exists
--Date          :2011/09/14
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Delete_Inactive_Prospect
	(
		@ProspectID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int

    SET @ReturnCode = 0


	BEGIN
        DELETE AC_Prospects
        WHERE AC_Prospects_ID = @ProspectID

        SET @ReturnCode = 1
    END



RETURN @ReturnCode











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_NonActive_Products
--Purpose       :DELETE NON Active UNUSED Products with ZERO STOCK
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Date          :2013/07/23
--Authors       :RL
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_NonActive_Products]
	(
        @ProductID	int,
        @UserID		int,
        @CompanyID	int
	)
AS

SET NOCOUNT ON

	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)
	DECLARE @Count			int
	
	SET @Count = 0
						
	SELECT @Count = Count(*)
	FROM AP_Products a
	FULL OUTER JOIN AS_Transaction_Details b
		ON a.AP_Products_ID = b.AP_Products_ID
	FULL OUTER JOIN AO_GRV_Details c
		ON a.AP_Products_ID = c.AP_Products_ID
	FULL OUTER JOIN AO_Order_Details d
		ON a.AP_Products_ID = c.AP_Products_ID
	WHERE	a.AP_Products_ID = @ProductID AND
			a.AW_User_Companies_ID = @CompanyID AND
			a.Slu_AW_Active_ID <> 1 AND
			b.AP_Products_ID IS NULL AND
			c.AP_Products_ID IS NULL AND
			d.AP_Products_ID IS NULL AND
			a.On_Hand = 0 AND
			a.AP_Products_ID NOT IN (SELECT ISNULL(Levy_AP_Product_ID,0) FROM AP_Products)

	IF @Count > 0
	BEGIN

		SELECT	@Product_Code = ISNULL(Product_Code,''),
				@Description = ISNULL([Description],'')
		FROM AP_Products
		WHERE AP_Products_ID = @ProductID

		--> DELETE Product in RELATED tables
		DELETE AO_Order_Candidates
		WHERE AP_Products_ID = @ProductID

		DELETE AO_Order_Candidates_Temp
		WHERE AP_Products_ID = @ProductID

		DELETE AO_Supplier_Contracts
		WHERE AP_Products_ID = @ProductID

		DELETE AO_Supplier_Product_Discounts
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Inventory_Adjustments
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Product_Selling_Prices
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Products_Assemblies
		WHERE AP_Parent_Product_ID = @ProductID OR
			AP_Child_Product_ID = @ProductID

		DELETE AP_Products_History
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Products_Stock_Takes
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Products_Suppliers
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Products_Switch3
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Promotion_Products
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Stock_Exchange
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Products_Bins
		WHERE AP_Products_ID = @ProductID

		DELETE AP_Products_Bins_History
		WHERE AP_Products_ID = @ProductID

		--> NOW delete Product
		DELETE AP_Products
		WHERE AP_Products_ID = @ProductID

		INSERT INTO AP_Products_Audit
		(
			Record_Action, 
			Action_Date, 
			[User_ID],
			AP_Products_ID, 
			Field, 
			Prev_Value, 
			New_Value
		)
		VALUES
		(
			'Delete', 
			GetDate(), 
			@UserID,
			@ProductID, 
			'', 
			@Product_Code,
			@Description
		)

	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







---------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Promotion
--Purpose       :Deletes a selected Promotion
--Functionality :
--Date          :2004/02/18
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Delete_Promotion
    (
        @PromotionID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AP_Promotions_ID
            FROM AP_Promotions
            WHERE AP_Promotions_ID = @PromotionID
        )
        BEGIN
            DELETE AP_Promotions
            WHERE AP_Promotions_ID = @PromotionID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







---------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Promotion_Product
--Purpose       :Deletes a selected Promotion Product
--Functionality :
--Date          :2004/02/18
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Delete_Promotion_Product
    (
        @PromoProductID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AP_Promotion_Products_ID
            FROM AP_Promotion_Products
            WHERE AP_Promotion_Products_ID = @PromoProductID
        )
        BEGIN
            DELETE AP_Promotion_Products
            WHERE AP_Promotion_Products_ID = @PromoProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Redundant_ProductID
--Purpose       :DELETE Redundant UNUSED ProductID with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Companion SP  :sp_AP_Select_Redundant_Products
--Date          :2007/04/27
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Redundant_ProductID]
	(
        @ProductID	int,
        @UserID		int
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)


    SET @RetCode = 0

        
		SELECT	@Product_Code = ISNULL(Product_Code,''),
				@Description = ISNULL([Description],'')
		FROM AP_Products
		WHERE AP_Products_ID = @ProductID

        --> DELETE Product in RELATED tables
        DELETE AO_Order_Candidates
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Order_Candidates_Temp
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Contracts
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Product_Discounts
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Product_Selling_Prices
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Assemblies
        WHERE AP_Parent_Product_ID = @ProductID OR
              AP_Child_Product_ID = @ProductID

        DELETE AP_Products_History
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Stock_Takes
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Suppliers
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Switch3
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Promotion_Products
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Stock_Exchange
        WHERE AP_Products_ID = @ProductID


        --> NOW delete Product
        DELETE AP_Products
        WHERE AP_Products_ID = @ProductID

		INSERT INTO AP_Products_Audit
		(
			Record_Action, 
			Action_Date, 
			[User_ID],
			AP_Products_ID, 
			Field, 
			Prev_Value, 
			New_Value
		)
		VALUES
		(
			'Delete', 
			GetDate(), 
			@UserID,
			@ProductID, 
			'', 
			@Product_Code,
			@Description
		)

    SET @RetCode = 1

RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Redundant_Products
--Purpose       :DELETE Redundant UNUSED Products with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--              :    Uses CURSOR
--Date          :2007/04/27
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Delete_Redundant_Products
	(
        @CompanyID int,
        @DeleteCNT int OUTPUT
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode int,
            @ProductID int


    SET @RetCode = 0
    SET @DeleteCNT = 0


	DECLARE Delete_Product CURSOR FOR
        (
            SELECT a.AP_Products_ID
            FROM AP_Products a
                FULL OUTER JOIN AS_Transaction_Details b
                    ON a.AP_Products_ID = b.AP_Products_ID
                FULL OUTER JOIN AO_GRV_Details c
                    ON a.AP_Products_ID = c.AP_Products_ID
                FULL OUTER JOIN AO_Order_Details d
                    ON a.AP_Products_ID = c.AP_Products_ID
            WHERE b.AP_Products_ID IS NULL AND
                  c.AP_Products_ID IS NULL AND
                  d.AP_Products_ID IS NULL AND
                  a.On_Hand = 0
        )

	OPEN Delete_Product

    	FETCH NEXT FROM Delete_Product 
    	INTO
            @ProductID
    	
    	WHILE @@FETCH_STATUS = 0
        	BEGIN

                --> DELETE Product in RELATED tables
                DELETE AO_Order_Candidates
                WHERE AP_Products_ID = @ProductID

                DELETE AO_Order_Candidates_Temp
                WHERE AP_Products_ID = @ProductID

                DELETE AO_Supplier_Contracts
                WHERE AP_Products_ID = @ProductID

                DELETE AO_Supplier_Product_Discounts
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Inventory_Adjustments
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Product_Selling_Prices
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Products_Assemblies
                WHERE AP_Parent_Product_ID = @ProductID OR
                      AP_Child_Product_ID = @ProductID

                DELETE AP_Products_History
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Products_Stock_Takes
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Products_Suppliers
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Products_Switch3
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Promotion_Products
                WHERE AP_Products_ID = @ProductID

                DELETE AP_Stock_Exchange
                WHERE AP_Products_ID = @ProductID


                --> NOW delete Product
                DELETE AP_Products
                WHERE AP_Products_ID = @ProductID


                SET @DeleteCNT = @DeleteCNT + 1


            	FETCH NEXT FROM Delete_Product 
            	INTO
                    @ProductID

        	END
	
	CLOSE Delete_Product

	DEALLOCATE Delete_Product


    SET @RetCode = 1


RETURN @RetCode














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Stock_Take
--Purpose       :Deletes a selected Stock Take
--Date          :2003/08/17
--Authors       :TB
--MODS          :
--2004.4.3      :20/02/09 - Reworked with new table definitions
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Delete_Stock_Take
    (
        @StockTakeProcedureID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Stock_Take_Procedures_ID
            FROM AP_Products_Stock_Takes
            WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID

        )
        BEGIN
            DELETE AP_Products_Stock_Takes
            WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID

            SET @ReturnValue = 1
        END


    IF EXISTS
        (
            SELECT AP_Stock_Take_Procedures_ID
            FROM AP_Stock_Take_Procedures
            WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID

        )
        BEGIN
            DELETE AP_Stock_Take_Procedures
            WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID

            SET @ReturnValue = 2
        END


RETURN @ReturnValue



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Stock_Transfer_Item
--Purpose       :Delete a Stock Transfer item from AP_Stock_Transfer_Details
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE              Procedure sp_AP_Delete_Stock_Transfer_Item
    (
        @TransferID int
    )

AS

SET NOCOUNT ON


	DELETE 
	FROM AP_Stock_Transfer_Details
	WHERE AP_Stock_Transfer_Details_ID = @TransferID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Slow_Moving_Stock
--Purpose       :Drops and re-creates AP_Enterprise_Slow_Moving_Stock table
--Date          :2006/10/05
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Drop_Enterprise_Slow_Moving_Stock

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Slow_Moving_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Slow_Moving_Stock]

        
        CREATE TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] (
        	[AP_Enterprise_Slow_Moving_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [decimal](12, 3) NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Slow_Moving_Stock_Search] ON [dbo].[AP_Enterprise_Slow_Moving_Stock]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Slow_Moving_Stock] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Slow_Moving_Stock_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Slow_Moving_Stock].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Stock
--Purpose       :Drops and re-creates AP_Enterprise_Stock table
--Date          :2006/05/22
--Authors       :TB
--MODS          :
--2004.3.2      :20/09/06 - Modified [Total] datatype from [int] to [decimal](12, 3)
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Drop_Enterprise_Stock

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Stock]

        
        CREATE TABLE [dbo].[AP_Enterprise_Stock] (
        	[AP_Enterprise_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [decimal](12, 3) NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Search] ON [dbo].[AP_Enterprise_Stock]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Stock] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Stock] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Stock_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Stock_Filter
--Purpose       :Drops and re-creates AP_Enterprise_Stock_Filter_Filter table
--Date          :2006/09/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Drop_Enterprise_Stock_Filter

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Filter]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Stock_Filter]

        
        CREATE TABLE [dbo].[AP_Enterprise_Stock_Filter] (
        	[AP_Enterprise_Stock_Filter_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [decimal](12, 3) NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Filter] ON [dbo].[AP_Enterprise_Stock_Filter]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Stock_Filter] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Stock_Filter] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Stock_Filter_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Filter].[Pack_Size]'

        
        setuser




    SET @ReturnValue = 1


RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Stock_MSL
--Purpose       :Drops and re-creates AP_Enterprise_Stock_MSL table
--Date          :2008/12/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Drop_Enterprise_Stock_MSL

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_MSL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Stock_MSL]

        
        CREATE TABLE [dbo].[AP_Enterprise_Stock_MSL] (
        	[AP_Enterprise_Stock_MSL_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [decimal](12, 3) NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_MSL_Search] ON [dbo].[AP_Enterprise_Stock_MSL]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Stock_MSL] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Stock_MSL] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Stock_MSL_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_MSL].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Stock_Replenish
--Purpose       :Drops and re-creates AP_Enterprise_Stock_Replenish table
--Date          :2008/12/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Drop_Enterprise_Stock_Replenish

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Replenish]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Stock_Replenish]

        
        CREATE TABLE [dbo].[AP_Enterprise_Stock_Replenish] (
        	[AP_Enterprise_Stock_Replenish_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [decimal](12, 3) NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Replenish_Search] ON [dbo].[AP_Enterprise_Stock_Replenish]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Stock_Replenish] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Stock_Replenish] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Stock_Replenish_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Replenish].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Stock_Replenish_Max
--Purpose       :Drops and re-creates AP_Enterprise_Stock_Replenish_Max table
--Date          :2009/07/23
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AP_Drop_Enterprise_Stock_Replenish_Max

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Replenish_Max]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Stock_Replenish_Max]

        
        CREATE TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] (
        	[AP_Enterprise_Stock_Replenish_Max_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [decimal](12, 3) NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Replenish_Max_Search] ON [dbo].[AP_Enterprise_Stock_Replenish_Max]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Stock_Replenish_Max] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Stock_Replenish_Max_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Replenish_Max].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Stock_Valuation
--Purpose       :Drops and re-creates AP_Enterprise_Stock_Valuation table
--Date          :2006/09/19
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Drop_Enterprise_Stock_Valuation

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Valuation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Enterprise_Stock_Valuation]

        
        CREATE TABLE [dbo].[AP_Enterprise_Stock_Valuation] (
        	[AP_Enterprise_Stock_Valuation_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [money] NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Valuation_Search] ON [dbo].[AP_Enterprise_Stock_Valuation]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Enterprise_Stock_Valuation] ADD 
        	CONSTRAINT [PK_AP_Enterprise_Stock_Valuation] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Enterprise_Stock_Valuation_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Valuation].[Pack_Size]'

        
        setuser



    SET @ReturnValue = 1


RETURN @ReturnValue












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Drop_Enterprise_Trial_Balance
--Purpose       :Drops and re-creates AB_Enterprise_Trial_Balance table
--Date          :2007/08/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Drop_Enterprise_Trial_Balance

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Trial_Balance]

        
        CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
        	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AB_Enterprise_Trial_Balance_Search] ON [dbo].[AB_Enterprise_Trial_Balance]([Filter], [Account_Number]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] ADD 
        	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AB_Enterprise_Trial_Balance_ID]
        	)  ON [PRIMARY] 



    SET @ReturnValue = 1


RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Enterprise_Product_Search_Lups
--Purpose       :Returns ONLY ACTIVE Lookups
--Date          :2006/10/14
--Authors       :TB
--MODS:         :
--2004.3.4      :27/02/07 - Added Option 10 Lup_AP_Purchase_Categories
--2004.3.8      :15/04/08 - Added Profit Protector lookup fields
--              :           [Edit Price], [Edit Disc], [Apply Max]
--2004.3.8      :09/05/08 - Replaced [Apply Max] with [Min GP%]
--2004.5.7 RGL  :2012-11-01 - Added 14 - Levy, 15 Weight
--2016.6.3 RL	:2017-03-30 - Removed check to see if lookup field is enabled. 
--				 It is irrelevant. Product should be loaded even if lookup value is disabled
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Enterprise_Product_Search_Lups]
    (
    	@Option int
    )

AS

SET NOCOUNT ON

    --> Supplier
    	IF @Option = 1
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name as [Description]
    		FROM AO_Suppliers
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name

    
    --> Manufacturer
    	ELSE 
    	IF @Option = 2
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Manufacturers
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Type
    	ELSE 
    	IF @Option = 3
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Types
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Group
    	ELSE 
    	IF @Option = 4
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Groups
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Department
    	ELSE 
    	IF @Option = 5
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Product_Departments
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Location
    	ELSE 
    	IF @Option = 6
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Locations
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Active
    	ELSE 
    	IF @Option = 7
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_Active

    --> Model Types
    	ELSE 
    	IF @Option = 8
    		SELECT Lup_AP_Switch2_Types_ID AS [ID],
    		   [Description] 
    		FROM Lup_AP_Switch2_Types

    --> GL Accounts
        ELSE 
    	IF @Option = 9
        	SELECT AB_Accounts_ID AS [ID], 
               [Description]
        	FROM AB_Accounts 
--        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Purchase Category
    	ELSE 
    	IF @Option = 10
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Purchase_Categories
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Edit Price
    	ELSE 
    	IF @Option = 11
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo

    --> Edit Disc
    	ELSE 
    	IF @Option = 12
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo

    --> Apply Min GP%
    	ELSE 
    	IF @Option = 13
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo
    		
    --> Levy
    	ELSE 
    	IF @Option = 14
            SELECT AP_Products_ID AS [ID],
    		      [Description]
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            ORDER BY [Description] ASC

    --> Weight
    	ELSE             
    	IF @Option = 15
        	SELECT Lup_AP_AW_Weight_ID AS [ID], 
               [Description]
        	FROM Lup_AP_AW_Weight
--        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
            

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















---------------------------------------------------------------------------
--Description	:sp_AP_Fetch_Online_Stock_Exchange
--Purpose	    :Fetches Online Stock On Hand as at NOW for POS
--Date		    :2006/09/09
--Authors	    :TB
--MODS          :
--2004.3.2      :03/11/06 - Added @ShowCost parameter
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote - Commented
--2004.4.9      :21/09/10 - Added deduct RESERVED STOCK as [On Hand]
---------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Fetch_Online_Stock_Exchange
	(
        @DBCounter int,
        @ProductCode varchar(20),
        @Database varchar(100),
        @CountDate datetime,
        @ShowCost tinyint
	)

AS

SET NOCOUNT ON

	SELECT @DBCounter AS [Branch ID],
           @Database AS [Branch],
           p.[Description] AS [Product],
           p.Product_Code AS [Code],
--           p.On_Hand AS [On Hand],
           CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [On Hand],
           (
               ISNULL( (
                    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 = p.AP_Products_ID), 0)
           ) AS [On Order],

            CASE WHEN @ShowCost = 1
                 THEN p.Last_Cost
                 ELSE 0
            END AS [Last Cost],

            CASE WHEN @ShowCost = 1
                 THEN p.Average_Cost
                 ELSE 0
            END AS [Average Cost],

           @CountDate AS [Count Date]
	FROM AP_Products p
    WHERE p.Product_Code = @ProductCode AND
          p.On_Hand <> 0
--          AND ISNULL(p.Slu_AW_YesNo_Hide_Remote, 0) = 0
    ORDER BY p.[Description]


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description	:sp_AP_Fetch_Price_Update_Products
--Purpose       :Gets ALL @chkActiveOnly Products that match @ProductCode
--              :Used in Product Price Updates
--Date			:2006/06/14
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Fetch_Price_Update_Products
	(
		@ProductCode varchar(20),
        @chkActiveOnly tinyint,
        @chkManufacturer tinyint,
        @ManufacturerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON


    IF @chkActiveOnly = 1
        BEGIN    
            IF @chkManufacturer = 1
                BEGIN
                    SELECT AP_Products_ID AS [ProductID],
                          [Description] AS [Description]
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode AND
                          AW_User_Companies_ID = @CompanyID AND
                          Lup_AP_Product_Manufacturers_ID = @ManufacturerID AND
                          Slu_AW_Active_ID = 1
                END
            ELSE
                BEGIN
                    SELECT AP_Products_ID AS [ProductID],
                          [Description] AS [Description]
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode AND
                          AW_User_Companies_ID = @CompanyID AND
                          Slu_AW_Active_ID = 1
                END
        END
    ELSE
        BEGIN    
            IF @chkManufacturer = 1
                BEGIN
                    SELECT AP_Products_ID AS [ProductID],
                          [Description] AS [Description]
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode AND
                          AW_User_Companies_ID = @CompanyID AND
                          Lup_AP_Product_Manufacturers_ID = @ManufacturerID
                END
            ELSE
                BEGIN
                    SELECT AP_Products_ID AS [ProductID],
                          [Description] AS [Description]
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode AND
                          AW_User_Companies_ID = @CompanyID
                END
        END







SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------
--Description	:sp_AP_Fetch_Stock_Exchange
--Purpose	    :Fetches Stock On Hand as at NOW for Stock Exchange
--Date		    :2004/01/13
--Authors	    :TB
--MODS          :
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote - Commented
---------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Fetch_Stock_Exchange
	(
    	@CompanyID int
	)

AS

SET NOCOUNT ON

	DECLARE @NodeName varchar(20),
            @RemoteID int,
            @CountDate datetime


    SET @CountDate = getdate()


    SELECT TOP 1 @RemoteID = AW_Remote_Access_ID,
                 @NodeName = ISNULL(NodeName, '')
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          Default_Connection = 1


	SELECT @RemoteID AS [Branch ID],
           @NodeName AS [Branch],
           p.AP_Products_ID AS [Product ID],
           p.[Description] AS [Product],
           p.Product_Code AS [Code],
           p.On_Hand AS [On Hand],
           (
               ISNULL( (
                    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 = p.AP_Products_ID), 0)
           ) AS [On Order],
           p.Last_Cost AS [Last Cost],
           p.Average_Cost AS [Average Cost],
           @CountDate AS [Count Date]
	FROM AP_Products p
    WHERE p.AW_User_Companies_ID = @CompanyID AND
          p.On_Hand <> 0
--          AND ISNULL(p.Slu_AW_YesNo_Hide_Remote, 0) = 0
    ORDER BY p.Description


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-- sp_AP_Filter_Bin_Allocations 1, -1, -1, -1, -1, -1, -1, 1, 1, '', 0
--exec sp_AP_Filter_Bin_Allocations 1, -1, -1, -1, -1, -1, -1, 1, '31500', 1 
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Bin_Allocations
--Purpose       :Filters Products Bin Allocations
--Joins         :Tables: AP_Products
--Date          :2015-11-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Filter_Bin_Allocations]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@FromBinID int = -1,
--      	@ToBinID int = -1,
      	@Product	varchar(50) = '',
        @OnHandOnly int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter			varchar(4000),
            @sql			varchar(8000),
            @FromBin		varchar(50),
            @FromBinEmail	varchar(100),
            @ToBin			varchar(50),
            @ToBinEmail		varchar(100),
            @ToBinID		int
            
	SET @ToBinID = 1
    SET @Filter = ''
    SET @sql = ''

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + 'AP_Products_ID		int, '
	SET @sql = @sql + '[Description]		varchar(50), '
	SET @sql = @sql + 'Product_Code			varchar(20), '
	SET @sql = @sql + 'On_Hand				decimal(9,3), '
	SET @sql = @sql + 'FromBinID			int, '	
	SET @sql = @sql + 'FromBin				varchar(50), '
	SET @sql = @sql + 'FromBinEmail			varchar(100), '
	SET @sql = @sql + 'FromBinQty			decimal(9,3), '
	SET @sql = @sql + 'OrigFromBinQty		decimal(9,3), '
	SET @sql = @sql + '[Transfer]			decimal(9,3), '
	SET @sql = @sql + 'OrigToBinID			int, '		
	SET @sql = @sql + 'ToBinID				int, '			
	SET @sql = @sql + 'ToBin				varchar(50), '
	SET @sql = @sql + 'ToBinEmail			varchar(100), '
	SET @sql = @sql + 'ToBinQty				decimal(9,3), '
	SET @sql = @sql + 'OrigToBinQty			decimal(9,3) '	
	SET @sql = @sql + ') '

	SET @FromBin = ''
	SET @FromBinEmail = ''
	SET @ToBin = ''
	SET @ToBinEmail = ''

	IF @FromBinID <> - 1
	BEGIN
		SELECT  @FromBin = [Description],
				@FromBinEmail = ISNULL(Email,'')
		FROM Lup_AP_Product_Bins
		WHERE Lup_AP_Product_Bins_ID = @FromBinID
	END
	ELSE
	BEGIN
		SELECT  @FromBin = [Description],
				@FromBinEmail = ISNULL(Email,'')
		FROM Lup_AP_Product_Bins
		WHERE Lup_AP_Product_Bins_ID = 1	
	END			

	--IF @ToBinID <> - 1
	--BEGIN
		SELECT  TOP 1 
				@ToBinID = Lup_AP_Product_Bins_ID,
				@ToBin = [Description],
				@ToBinEmail = ISNULL(Email,'')
		FROM Lup_AP_Product_Bins
		WHERE Lup_AP_Product_Bins_ID <> @FromBinID
	--END
	--ELSE
	--BEGIN
	--	SELECT  @ToBin = [Description],
	--			@ToBinEmail = ISNULL(Email,'')
	--	FROM Lup_AP_Product_Bins
	--	WHERE Lup_AP_Product_Bins_ID = 1	
	--END
	
--Select @FromBin, @FromBinEmail, @ToBin, @ToBinEmail

    --> Products_Suppliers
    IF @SupplierID > 0 
	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' + CONVERT(varchar(20), @SupplierID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' + CONVERT(varchar(20), @SupplierID)
	END
    --> Manufacturer
	IF @ManufacturerID > 0 
	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' + CONVERT(varchar(20), @ManufacturerID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' + CONVERT(varchar(20), @ManufacturerID)
	END
    --> Type
	IF @TypeID > 0 
	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' + CONVERT(varchar(20), @TypeID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' + CONVERT(varchar(20), @TypeID)
	END
    --> Group
	IF @GroupID > 0 
	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' + CONVERT(varchar(20), @GroupID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' + CONVERT(varchar(20), @GroupID)
	END
    --> Department
	IF @DepartmentID > 0 
	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' + CONVERT(varchar(20), @DepartmentID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' + CONVERT(varchar(20), @DepartmentID)
	END
    --> Location
	IF @LocationID  > 0 
	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' + CONVERT(varchar(20), @LocationID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' + CONVERT(varchar(20), @LocationID)
   	END

 	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 @Filter = @Filter + ' AND ' + ' b.Lup_AP_Product_Bins_ID = ' + CONVERT(varchar(20), @FromBinID)
		
		SET @sql = @sql + ' INSERT INTO @Tbl'
		SET @sql = @sql + '		(AP_Products_ID,'		
		SET @sql = @sql + '		[Description],'
		SET @sql = @sql + '		Product_Code,'
		SET @sql = @sql + '		On_Hand,'
		SET @sql = @sql + '		FromBinID,'
		SET @sql = @sql + '		FromBin,'
		SET @sql = @sql + '		FromBinEmail,'
		SET @sql = @sql + '		FromBinQty,'
		SET @sql = @sql + '		OrigFromBinQty,'
		SET @sql = @sql + '		[Transfer],'
		SET @sql = @sql + '		ToBinID,'
		SET @sql = @sql + '		OrigToBinID,'		
		SET @sql = @sql + '		ToBin,'
		SET @sql = @sql + '		ToBinEmail,'
		SET @sql = @sql + '		ToBinQty,'
		SET @sql = @sql + '		OrigToBinQty)'
    	SET @sql = @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.On_Hand AS [On Hand], '
        SET @sql = @sql + '		b.Lup_AP_Product_Bins_ID AS [From Bin ID], '
        SET @sql = @sql + '''' + @FromBin + '''' + ' AS [From Bin], '
        SET @sql = @sql + '''' + @FromBinEmail + '''' + ' AS [From Bin Email], '
        SET @sql = @sql + '		CONVERT(DECIMAL(9,3),ISNULL(dbo.fn_AP_Get_Product_Bin_Qty(p.AP_Products_ID, ' + '''' + Convert(varchar(10),@FromBinID) + '''' + ',' + '''' + Convert(varchar(10),@CompanyID) + '''' + '),0)) AS [From Bin Qty], '
        SET @sql = @sql + '		CONVERT(DECIMAL(9,3),ISNULL(dbo.fn_AP_Get_Product_Bin_Qty(p.AP_Products_ID, ' + '''' + Convert(varchar(10),@FromBinID) + '''' + ',' + '''' + Convert(varchar(10),@CompanyID) + '''' + '),0)) AS [Orig From Bin Qty], '        
        SET @sql = @sql + '		0 AS [Transfer], '        

        --SET @sql = @sql + '		t.Lup_AP_Product_Bins_ID AS [To Bin ID], '
        --SET @sql = @sql + '		t.Description AS [To Bin], '
        --SET @sql = @sql + '		t.Email AS [To Bin Email], '
        SET @sql = @sql + '' + Convert(varchar(10),@ToBinID) + '' + ' AS [Orig To Bin ID], '        
        SET @sql = @sql + '' + Convert(varchar(10),@ToBinID) + '' + ' AS [To Bin ID], '        
        SET @sql = @sql + '''' + @ToBin + '''' + ' AS [To Bin], '
        SET @sql = @sql + '''' + @ToBinEmail + '''' + ' AS [To Bin Email], '
        SET @sql = @sql + '		CONVERT(DECIMAL(9,3),ISNULL(dbo.fn_AP_Get_Product_Bin_Qty(p.AP_Products_ID, ' + '''' + Convert(varchar(10),@ToBinID) + '''' + ',' + '''' + Convert(varchar(10),@CompanyID) + '''' + '),0)) AS [To Bin Qty], '
        SET @sql = @sql + '		CONVERT(DECIMAL(9,3),ISNULL(dbo.fn_AP_Get_Product_Bin_Qty(p.AP_Products_ID, ' + '''' + Convert(varchar(10),@ToBinID) + '''' + ',' + '''' + Convert(varchar(10),@CompanyID) + '''' + '),0)) AS [Orig To Bin Qty] '        
        --SET @sql = @sql + ' p.On_Hand AS [To Bin Qty] '        
        
        SET @sql = @sql + ' FROM AP_Products p '
        
        SET @sql = @sql + ' 	Inner Join AP_Products_Bins b '
        SET @sql = @sql + ' 		On p.AP_Products_ID = b.AP_Products_ID '
        --SET @sql = @sql + ' 	Right Outer Join Lup_AP_Product_Bins t '
        --SET @sql = @sql + ' 		On b.Lup_AP_Product_Bins_ID <> t.Lup_AP_Product_Bins_ID	 '
                                
                        
        SET @sql = @sql + @Filter

        IF @OnHandOnly = 1
            BEGIN
                --SET @sql = @sql + ' AND ' + ' p.On_Hand > 0 '
                SET @sql = @sql + ' AND ' + ' CONVERT(DECIMAL(9,3),ISNULL(dbo.fn_AP_Get_Product_Bin_Qty(p.AP_Products_ID, ' + '''' + Convert(varchar(10),@FromBinID) + '''' + ',' + '''' + Convert(varchar(10),@CompanyID) + '''' + '),0)) > 0 '
                
            END

		If @Product <> ''
		Begin
			SET @Product = '%' +  @Product + '%'
			SET @sql = @sql + ' AND (p.Product_Code Like ' + '''' + CONVERT(varchar(50), @Product) + ''''
			SET @sql = @sql + ' Or p.Description Like ' + '''' + CONVERT(varchar(50), @Product) + ''')'
			
--			WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' + CONVERT(varchar(20), @DepartmentID)
		End

        SET @sql = @sql + ' ORDER BY p.[Description], p.AP_Products_ID '
		
		SET @sql = @sql + 'SELECT '
		SET @sql = @sql + '	AP_Products_ID AS [ID], '
		SET @sql = @sql + '	[Description] AS [Description], '
		SET @sql = @sql + '	Product_Code AS [Code], '
		
		SET @sql = @sql + '	FromBinQty AS [From Bin Qty], '
		SET @sql = @sql + '	FromBinID AS [From Bin], '		
		SET @sql = @sql + '	FromBin AS [FromBin], '
		SET @sql = @sql + '	FromBinEmail AS [From Bin Email], '

		SET @sql = @sql + '	[Transfer] AS [Transfer], '		

		SET @sql = @sql + '	ToBinID AS [To Bin], '						
		SET @sql = @sql + '	ToBinQty AS [To Bin Qty], '		
		SET @sql = @sql + '	OrigFromBinQty AS [Orig From Bin Qty], '				
		SET @sql = @sql + '	OrigToBinID AS [Orig To Bin], '						
		SET @sql = @sql + '	ToBin AS [ToBin], '
		SET @sql = @sql + '	ToBinEmail AS [To Bin Email], '

		SET @sql = @sql + '	OrigToBinQty AS [Orig To Bin Qty], '
		SET @sql = @sql + '	On_Hand AS [All Bin Qty] '		
		SET @sql = @sql + 'FROM @Tbl '
		SET @sql = @sql + 'ORDER BY [Description], AP_Products_ID '		

        EXEC (@sql)
        --Select @sql

	END

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















--sp_AP_Filter_Cost_Adjustments 1, -1, -1, -1, -1, -1, -1, 0, 0, 0

-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Cost_Adjustments
--Purpose       :Filters Products to adjust Costs
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2007/02/15
--Authors       :TB
--MODS          :
--2004.5.0      :17/04/11 - Added fetch stock On_Hand
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Filter_Cost_Adjustments
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(4000),
            @sql varchar(8000)

    SET @Filter = ''
    SET @sql = ''

    --> Products_Suppliers
    IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
    	END

	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.Pack_Size AS [Size], '
        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.On_Hand AS [On Hand] '

        SET @sql = @sql + ' FROM AP_Products p '
        SET @sql = @sql + @Filter



        IF @OnHandOnly = 1
            BEGIN
                SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
            END


        IF @NonStock = 1
            BEGIN
                SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


        IF @Sort = 1
            BEGIN
                SET @sql = @sql + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN
                SET @sql = @sql + ' ORDER BY p.[Description] '
            END



        EXEC (@sql)

	END

SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















--sp_AP_Filter_Enterprise_Stock 1, 'BF Goodrich', 'EARTHMOVER XPLY', 'B F GOODRICH', , , , 1, 1, 1, 1 
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Enterprise_Stock
--Purpose       :FILTER Enterprise Stock II
--Functionality :Uses filter DESCRIPTIONS
--Date          :2006/09/14
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Filter_Enterprise_Stock
	(
        @CompanyID int,
        @Manuf varchar(50) = '',
        @Type varchar(50) = '',
        @Group varchar(50) = '',
        @Department varchar(50) = '',
        @Supplier varchar(50) = '',
        @Location varchar(50) = '',
        @OnHandOnly int,
        @Sort int,
        @NonStock int,
    	@chkActiveOnly tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @ManufID int,
            @TypeID int,
            @GroupID int,
            @DepartmentID int,
            @SupplierID int,
            @LocationID int,
            @Filter varchar(4000),
            @sql varchar(8000),
            @RetCode int


	SET @Filter = ''
    SET @sql = ''


--> Manufacturer
	IF @Manuf <> ''
		BEGIN
            --> Get Manufacturer ID
            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
        
            IF @ManufID IS NULL OR @ManufID = 0
                BEGIN
                    SET @Manuf = ''
                END
        END

--> Supplier
	IF @Supplier <> ''
		BEGIN
            --> Get Supplier ID
            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
        
            IF @SupplierID IS NULL OR @SupplierID = 0
                BEGIN
                    SET @Supplier = ''
                END
        END

--> Type
	IF @Type <> ''
		BEGIN
            --> Get Product Type ID
            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
        
            IF @TypeID IS NULL OR @TypeID = 0
                BEGIN
                    SET @Type = ''
                END
        END

--> Group
	IF @Group <> ''
		BEGIN
            --> Get Product Group ID
            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
        
            IF @GroupID IS NULL OR @GroupID = 0
                BEGIN
                    SET @Group = ''
                END
        END

--> Department
	IF @Department <> ''
		BEGIN
            --> Get Product Department ID
            SELECT TOP 1 @DepartmentID = Lup_AP_Product_Departments_ID
            FROM Lup_AP_Product_Departments
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Department AND
                  Slu_AW_Active_ID = 1
        
            IF @DepartmentID IS NULL OR @DepartmentID = 0
                BEGIN
                    SET @Department = ''
                END
        END

--> Location
	IF @Location <> ''
		BEGIN
            --> Get Product Location ID
            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
        
            IF @LocationID IS NULL OR @LocationID = 0
                BEGIN
                    SET @Location = ''
                END
        END



--> Manufacturer
	IF @Manuf <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufID)
		END
--> Type
	IF @Type <> ''
		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 @Group <> ''
		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 @Department <> ''
		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 @Supplier <> ''
		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 @Location <> ''
		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


--> 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.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '
    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '

    SET @sql = @sql + ' m.[Description] AS [Manuf], '
    SET @sql = @sql + ' t.[Description] AS [Type], '
    SET @sql = @sql + ' g.[Description] AS [Group], '
    SET @sql = @sql + ' d.[Description] AS [Department], '
    SET @sql = @sql + ' s.[Supplier_Name] AS [Supplier], '
    SET @sql = @sql + ' l.[Description] AS [Location] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Types t '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Groups g '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Groups_ID = g.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Departments d '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Departments_ID = d.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON p.Default_Supplier_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Locations l '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Locations_ID = l.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + @Filter


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
        END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Manuf], [Type], [Group], [Department], [Supplier], [Location], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Manuf], [Type], [Group], [Department], [Supplier], [Location], [Product] '
        END

    ----------------------------------
    -- If NO FILTERS FOUND the EXIT    
    ----------------------------------
    IF @Manuf = '' AND
       @Type = '' AND
       @Group = '' AND
       @Department = '' AND
       @Supplier = '' AND
       @Location = ''

        RETURN
    ----------------------------------


--PRINT @sql

EXEC (@sql)



SET NOCOUNT OFF	












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Inventory_Adjustments
--Purpose       :Retrieves filtered list of Inventory Adjustments
--              :
--Parameters    :
--Date          :2002/02/13
--Authors       :TB
--Version       :1.0.0
--MODS          :24/04/02 - Reduced number of columns to improve printing
--              :27/04/02 - Replaced User Firstname, Surname with UserName
--              :16/10/02 - Added Start and End date filter when retieving ALL adj
--              :31/05/03 - Added NEW and PREVIOUS Average_Cost fields & Calcs
--              :08/01/04 - Fixed Search Filter sequence
--              :09/01/04 - Added filter by Adjustment Type with @AdjustType
--V6.2	RL		:2016-04-25 - Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Filter_Inventory_Adjustments]
    (
        @CompanyID int, 
        @AdjustType tinyint,
        @SearchFilter int,
        @Value int,
        @SearchDescription varchar(50),
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON


    IF @AdjustType = 0
        BEGIN
            --> ALL Adjustements
            IF @SearchFilter = 0
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> SUPPLIERS
            IF @SearchFilter = 1
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    JOIN AO_Suppliers s
                        ON p.Default_Supplier_ID = s.AO_Suppliers_ID
        		WHERE s.AO_Suppliers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> MANUFACTURER
            IF @SearchFilter = 2
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Manufacturers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> TYPES
            IF @SearchFilter = 3
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Types_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> GROUPS
            IF @SearchFilter = 4
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Groups_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> DEPARTMENTS
            IF @SearchFilter = 5
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Departments_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> LOCATIONS
            IF @SearchFilter = 6
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Locations_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> PRODUCT DESCRIPTION SEARCH
            IF @SearchFilter = 7
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                     (p.[Description] LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%' OR
                      p.Product_Code LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%') AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

            ELSE
            --> LOCATIONS
            IF @SearchFilter = 10
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    LEFT OUTER JOIN AP_Products_Bins b
        		        ON p.AP_Products_ID = b.AP_Products_ID
        		    LEFT OUTER JOIN Lup_AP_Product_Bins pb
        				ON pb.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID    
        		WHERE pb.Lup_AP_Product_Bins_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

        END

    --> Adjustment Type Selected
    ELSE
        BEGIN
            --> ALL Adjustements
            IF @SearchFilter = 0
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> SUPPLIERS
            IF @SearchFilter = 1
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    JOIN AO_Suppliers s
                        ON p.Default_Supplier_ID = s.AO_Suppliers_ID
        		WHERE s.AO_Suppliers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> MANUFACTURER
            IF @SearchFilter = 2
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Manufacturers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> TYPES
            IF @SearchFilter = 3
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Types_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> GROUPS
            IF @SearchFilter = 4
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Groups_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> DEPARTMENTS
            IF @SearchFilter = 5
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Departments_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> LOCATIONS
            IF @SearchFilter = 6
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Locations_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> PRODUCT DESCRIPTION SEARCH
            IF @SearchFilter = 7
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (p.[Description] LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%' OR
                      p.Product_Code LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%') AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

            ELSE
            --> BINS
            IF @SearchFilter = 10
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (ISNULL(a.New_Last_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Last_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Last Cost Val],
                   (ISNULL(a.New_Average_Cost,0) * ISNULL(a.New_On_Hand,0)) -
                       (ISNULL(a.Previous_Average_Cost,0) * ISNULL(a.Previous_On_Hand,0)) AS [Ave. Cost Val],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    LEFT OUTER JOIN AP_Products_Bins b
        		        ON p.AP_Products_ID = b.AP_Products_ID
        		    LEFT OUTER JOIN Lup_AP_Product_Bins pb
        				ON pb.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID            		        
        		WHERE p.Lup_AP_Product_Locations_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

        END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Link_Discount_Formulas
--Purpose       :Filters Products to Link Discount Formulas
--              :
--Functionality :Tables: AP_Products, AP_Products_Suppliers, AO_Suppliers,
--              :        AW_Formulas, 
--Date          :2002/02/14
--Authors       :TB
--Version       :1.0.0
--MODS          :04/10/03 - Removed Price2_Price1 and Price2_Effective_Date
--              :           These column are superflous because discounts only
--              :           calculated on Price1_Price1 for Inventory Manager
--              :04/10/03 - Added Trade_Disc_Perc and Trade_Disc_Date from
--              :           AP_Products_Suppliers for Inventory Manager
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Filter_Link_Discount_Formulas
	(
    	@CompanyID int,
        @Option bit,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(1000),
            @SQL varchar(1200)

	SET @Filter = ''
    SET @SQL = ''

--> ALL SUPPLIERS
    IF @Option = 1
    	SELECT
            p.AP_Products_ID AS [ID],
            s.Supplier_Name AS [Supplier],
            p.Product_Code AS [Code],
            p.[Description] AS [Description],
            p.Price1_Price1 AS [Price1],
            p.Price1_Effective_Date AS [Date1],
            ps.Trade_Disc_Perc AS [Disc %],
            ps.Trade_Disc_Date AS [Disc Date],
            tf.[Description] AS [Trade],
            rf.[Description] AS [Rebate],
--             p.Price2_Price1 AS Price2,
--             p.Price2_Effective_Date AS Date2,
            p.On_Hand AS [On Hand],
            p.Pack_Size AS [Size],
            ps.AP_Products_Suppliers_ID AS [PSID],
            tf.AW_Formulas_ID AS [TradeID],
            rf.AW_Formulas_ID AS [RebateID]
        FROM AP_Products p
            INNER JOIN AP_Products_Suppliers ps
                ON p.AP_Products_ID = ps.AP_Products_ID
            INNER JOIN AO_Suppliers s
                ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
            LEFT JOIN AW_Formulas tf
                ON ps.AW_Trade_Discount_Formula_ID = tf.AW_Formulas_ID
            LEFT JOIN AW_Formulas rf
                ON ps.AW_Rebate_Discount_Formula_ID = rf.AW_Formulas_ID
        ORDER BY [Supplier], [Description]

--> A SUPPLIER selected
    ELSE
        BEGIN
        --> 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

    		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 + 's.Supplier_Name AS [Supplier], '
                SET @SQL = @SQL + 'p.Product_Code AS [Code], '
                SET @SQL = @SQL + 'p.[Description] AS [Description], '
                SET @SQL = @SQL + 'p.Price1_Price1 AS [Price1], '
                SET @SQL = @SQL + 'p.Price1_Effective_Date AS [Date1], '
                SET @SQL = @SQL + 'ps.Trade_Disc_Perc AS [Disc %], '
                SET @SQL = @SQL + 'ps.Trade_Disc_Date AS [Disc Date], '
                SET @SQL = @SQL + 'tf.[Description] AS [Trade], '
                SET @SQL = @SQL + 'rf.[Description] AS [Rebate], '
--                 SET @SQL = @SQL + 'p.Price2_Price1 AS Price2, '
--                 SET @SQL = @SQL + 'p.Price2_Effective_Date AS Date2, '
                SET @SQL = @SQL + 'p.On_Hand AS [On Hand], '
                SET @SQL = @SQL + 'p.Pack_Size AS [Size], '
                SET @SQL = @SQL + 'ps.AP_Products_Suppliers_ID AS [PSID], '
                SET @SQL = @SQL + 'tf.AW_Formulas_ID AS [TradeID], '
                SET @SQL = @SQL + 'rf.AW_Formulas_ID AS [RebateID] '
                SET @SQL = @SQL + 'FROM AP_Products p '
                SET @SQL = @SQL + 'INNER JOIN AP_Products_Suppliers ps '
                SET @SQL = @SQL + '    ON p.AP_Products_ID = ps.AP_Products_ID '
                SET @SQL = @SQL + 'INNER JOIN AO_Suppliers s '
                SET @SQL = @SQL + '    ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID '
                SET @SQL = @SQL + 'LEFT JOIN AW_Formulas tf '
                SET @SQL = @SQL + '    ON ps.AW_Trade_Discount_Formula_ID = tf.AW_Formulas_ID '
                SET @SQL = @SQL + 'LEFT JOIN AW_Formulas rf '
                SET @SQL = @SQL + '    ON ps.AW_Rebate_Discount_Formula_ID = rf.AW_Formulas_ID '
                SET @SQL = @SQL + @Filter
                SET @SQL = @SQL + ' ORDER BY [Supplier], [Description] '
        
        		EXEC (@SQL)
        	END
        END

SET NOCOUNT OFF	
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-- sp_AP_Filter_Price_Adjustments 1, -1, 11, -1, -1, -1, -1

-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Price_Adjustments
--Purpose       :Filters Products to Apply Markup Percentage
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2002/07/29
--Authors       :TB
--Version       :1.0.0
--MODS          :07/07/03 - Added Average Cost field to rs
--              :04/10/03 - Removed Average Cost field. Only be updated with GRV
--              :20/07/04 - Removed @Option parameter and UI Supplier OptionBox
--2004.3.2      :20/10/06 - Removed AO_Suppliers JOIN to make RS UPDATEABLE
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Filter_Price_Adjustments
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID 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 Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)

		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
    	END

	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)
		ELSE
			SET @Filter = @Filter + ' AND AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)

    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + 'AP_Products_ID AS [ID], '
        SET @SQL = @SQL + '[Description] AS [Description], '
        SET @SQL = @SQL + 'Product_Code AS [Code], '
        SET @SQL = @SQL + 'Last_Cost AS [Last Cost], '
        SET @SQL = @SQL + 'Pack_Size AS [Size], '
        SET @SQL = @SQL + 'Price1_Price1 AS [Selling1-1], '
        SET @SQL = @SQL + 'Price1_Price2 AS [Selling1-2], '
        SET @SQL = @SQL + 'Price1_Effective_Date AS [Date1], '
        SET @SQL = @SQL + 'Price2_Price1 AS [Selling2-1], '
        SET @SQL = @SQL + 'Price2_Price2 AS [Selling2-2], '
        SET @SQL = @SQL + 'Price2_Effective_Date AS [Date2] '
        SET @SQL = @SQL + ' FROM AP_Products '
        SET @SQL = @SQL + @Filter
        SET @SQL = @SQL + ' ORDER BY [Description] '



        EXEC (@SQL)

	END

SET NOCOUNT OFF	












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Price_Markups
--Purpose       :Filters Products to Apply Markup Percentage Formulas
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2002/07/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Filter_Price_Markups
	(
    	@CompanyID int,
        @Option bit,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(1000),
            @SQL varchar(1200)

	SET @Filter = ''
    SET @SQL = ''

--> ALL SUPPLIERS
    IF @Option = 1
    	SELECT
            p.AP_Products_ID AS [ID],
            p.Description,
            p.Product_Code AS [Code],
            p.Last_Cost AS [Last Cost],
            p.Pack_Size AS [Size],
            p.Price1_Price1 AS [Selling1-1],
            p.Price1_Price2 AS [Selling1-2],
            p.Price1_Effective_Date AS [Date1],
            p.Price2_Price1 AS [Selling2-1],
            p.Price2_Price1 AS [Selling2-2],
            p.Price2_Effective_Date AS [Date2]
        FROM AP_Products p
            INNER JOIN AO_Suppliers s
                ON s.AO_Suppliers_ID = p.Default_Supplier_ID
        ORDER BY p.Description

--> A SUPPLIER selected
    ELSE
        BEGIN
        --> 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

    		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.Last_Cost AS [Last Cost], '
                SET @SQL = @SQL + ' p.Pack_Size AS [Size], '
                SET @SQL = @SQL + ' p.Price1_Price1 AS [Selling1-1], '
                SET @SQL = @SQL + ' p.Price1_Price2 AS [Selling1-2], '
                SET @SQL = @SQL + ' p.Price1_Effective_Date AS [Date1], '
                SET @SQL = @SQL + ' p.Price2_Price1 AS [Selling2-1], '
                SET @SQL = @SQL + ' p.Price2_Price2 AS [Selling2-2], '
                SET @SQL = @SQL + ' p.Price2_Effective_Date AS [Date2] '
                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
        END

SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Price_Update_Export
--Purpose       :Filters Price Update Products to Export
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2003/12/31
--Authors       :TB
--MODS          :18/06/04 - Replaced [Comment] with [Last Cost]
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Filter_Price_Update_Export
	(
    	@CompanyID int,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @sql varchar(6000)


	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


	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 [ProdID], '
    SET @sql = @sql + ' p.Product_Code AS [Product Code], '
    SET @sql = @sql + ' p.[Description] AS [Product Description], '
    SET @sql = @sql + ' p.Price1_Effective_Date AS [Effective Date], '
    SET @sql = @sql + ' p.Price1_Price1 AS [Price 1], '
    SET @sql = @sql + ' p.Price1_Price2 AS [Price 2], '
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost] '
    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + @Filter
    SET @sql = @sql + ' ORDER BY p.[Description] '

	EXEC (@sql)

SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Product_CostPlus_Groups
--Purpose       :Filters Products to set Product Cost+Plus Groups globally
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2007/07/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Filter_Product_CostPlus_Groups
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID 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


		IF @Filter = ''
            BEGIN
    			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                CONVERT(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
    			SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                CONVERT(varchar(20), @CompanyID)
            END


	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.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 + ' CONVERT(money, dbo.GetCostPlusMargin(p.Last_Cost)) AS [GP %], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Cost_Plus_Item AS [Is Cost+Plus], '
    SET @sql = @sql + ' p.Lup_AP_Markup_Groups_ID AS [Cost+Plus Group] '

    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)




SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Product_Discount_Groups
--Purpose       :Filters Products to set Product Discount Groups globally
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2006/10/07
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Filter_Product_Discount_Groups
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID 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


		IF @Filter = ''
            BEGIN
    			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                CONVERT(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
    			SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                CONVERT(varchar(20), @CompanyID)
            END


	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.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' CONVERT(money, dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate())) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), p.Last_Cost)) AS [GP %], '

    SET @SQL = @SQL + ' p.Lup_AP_Discount_Groups_ID AS [Discount Group] '

    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)




SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



-------------------------------------------------------------------------------
--Description   :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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Product_Update_Export
--Purpose       :Filters Product Update Products to Export
--Date          :2006/05/11
--Authors       :TB
--MODS          :
--2004.3.2      :11/09/06 - Added @LocationID input parameter and [Location] field
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :29/12/06 - Uncommented AP_Products_ID in SELECT to enable UPDATE RS
--              :           of sugFilterProducts in UI
--              :27/02/07 - Added input parameters for Lup_AP_Purchase_Categories
--2004.3.8      :15/04/08 - Added Profit Protector fields [Edit Price], [Edit Disc]
--              :           [Max Disc], [Apply Max]
--              :09/05/08 - Replaced [Max Disc] with [Min GP%] and [Apply Max] with [Apply Min%]
--              :09/05/08 - Added ALIAS to Profit Protector fields - unaliased caused wrong
--              :           values to be fetched !!!
--2004.4.0      :19/07/08 - Added NOT EDITABLE p.Last_Sale_Date AS [Last Sale] AS LAST COLUMN
--              :19/07/08 - Added @chkSortOrder input parameter to sort by [Last Sale]
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
--2004.5.7 RGL  :2012-11-01 - Added [Levy], [Weight Type], [Weight]
--V6.3	RL	2017/04/06	:Added single product search
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Filter_Product_Update_Export]
	(
    	@CompanyID int,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
    	@SupplierID int = -1,
    	@LocationID int = -1,
    	@PurchaseCatID int = -1,
    	@chkDateCaptured tinyint = -1,
    	@DateCaptured datetime,
    	@chkActiveOnly tinyint = -1,
    	@chkSortOrder tinyint = 0,
    	@Product	varchar(50) = ''
	)
AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @sql varchar(8000)


	SET @Filter = ''
    SET @sql = ''


--> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
--> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
--> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
--> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
--> Supplier
	IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
--> Location
	IF @LocationID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
		END
--> Purchase Category
	IF @PurchaseCatID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseCatID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseCatID)
		END
--> Product
	IF @Product <> '' 
		BEGIN
			SET @Product =  '%' +  @Product + '%'
			IF @Filter = ''
				SET @Filter = ' WHERE ' + '( p.Description Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Product_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.SKU_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Supercession Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code1 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code2 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Keywords Like ' + '''' + @Product + '''' + ' )' 
			ELSE
				SET @Filter = @Filter + ' AND ' + '( p.Description Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Product_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.SKU_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Supercession Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code1 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code2 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Keywords Like ' + '''' + @Product + '''' + ' )' 
		END

                          --' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
                          
                          
                          
--> Company
	IF @Filter = ''
		SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)
	ELSE
		SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)


--> Fetch only Products from this Date Captured and later
    IF @chkDateCaptured = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Date_Captured >= ' + '''' + CONVERT(varchar(30), @DateCaptured) + '''' + ' '
            ELSE
                SET @Filter = @Filter + '  AND p.Date_Captured >= ' + '''' + CONVERT(varchar(30), @DateCaptured) + '''' + ' '
        END


--> Fetch only ACTIVE Products
    IF @chkActiveOnly = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Slu_AW_Active_ID = 1 '
            ELSE
                SET @Filter = @Filter + '  AND p.Slu_AW_Active_ID = 1 '
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Product Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '
    SET @sql = @sql + ' p.Date_Captured AS [Date Captured], '
    SET @sql = @sql + ' p.SKU_Code AS [SKU Code], '
    SET @sql = @sql + ' p.Alternate_Code1 AS [Alt Code], '
    SET @sql = @sql + ' p.Alternate_Code2 AS [Bar Code], '
    SET @sql = @sql + ' p.Lup_AP_Product_Manufacturers_ID AS [Manufacturer], '
    SET @sql = @sql + ' p.Manufacturer_Code AS [Manuf Code], '
    SET @sql = @sql + ' p.Manufacturer_Description AS [Manuf Desc], '
    SET @sql = @sql + ' p.Default_Supplier_ID AS [Supplier], '
    SET @sql = @sql + ' p.Lup_AP_Product_Types_ID AS [Type], '
    SET @sql = @sql + ' p.Lup_AP_Product_Groups_ID AS [Group], '
    SET @sql = @sql + ' p.Lup_AP_Product_Departments_ID AS [Department], '
    SET @sql = @sql + ' p.Lup_AP_Product_Locations_ID AS [Location], '
--    SET @sql = @sql + ' p.Lup_AP_Purchase_Categories_ID AS [Purchase Cat], '
    SET @sql = @sql + ' p.Lup_AP_Purchase_Categories_ID AS [PurchaseCat], '    
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg Cost], '
    SET @sql = @sql + ' p.Standard_Cost AS [Std Cost], '
    SET @sql = @sql + ' p.Price1_Effective_Date AS [Price1 Date], '
    SET @sql = @sql + ' p.Price1_Price1 AS [Price 1-1], '
    SET @sql = @sql + ' p.Price1_Price2 AS [Price 1-2], '
    SET @sql = @sql + ' p.Price2_Effective_Date AS [Price2 Date], '
    SET @sql = @sql + ' p.Price2_Price1 AS [Price 2-1], '
    SET @sql = @sql + ' p.Price2_Price2 AS [Price 2-2], '
    SET @sql = @sql + ' p.Pack_Volume AS [Volume], '
    SET @sql = @sql + ' p.Pack_Mass AS [Mass], '
    SET @sql = @sql + ' p.Slu_AW_Active_ID AS [Active], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Price AS [Edit Price], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Discount AS [Edit Disc], '
    SET @sql = @sql + ' p.Max_Discount_Perc AS [Min GP%], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Max_Discount_Perc AS [Apply Min%], '
    SET @sql = @sql + ' p.Last_Sale_Date AS [Last Sale], '
    SET @sql = @sql + ' p.Levy_AP_Product_ID AS [Levy], '
    SET @sql = @sql + ' p.Lup_AP_AW_Weight_ID AS [WeightType], '
    SET @sql = @sql + ' p.Product_Weight AS [Weight] '        
    
    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + @Filter

    IF @chkSortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY p.[Description] '
        END

    IF @chkSortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY p.Last_Sale_Date DESC '
        END


	EXEC (@sql)
--Select @sql
SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Profit_Protector
--Purpose       :Filters Products to set Product flags globally
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2004/02/14
--Authors       :TB
--Version       :1.0.0
--MODS          :30/07/04 - Removed @Option parameter and UI Supplier OptionBox
--2004.3.8      :30/11/07 - Added new @optShowGP input parameter to calc GP% and
--              :           also show relavent Cost Price as [Cost]
--              :09/04/08 - Added [Retail] field (Selling - Max Disc%)
--              :10/04/08 - Added elimate all products not Active
--              :09/05/08 - Replaced Maximum Discount% field functionality with
--              :           Minimum GP% functionality and replaced existing columns
--              :           with [Min Retail] and [Max Disc%]
--2004.4.1      :29/09/08 - Added Purchase Category
--V6.3	RL	2017-03-14	:Added check to see if Max_Discount_Perc = 100. Changed to 0. Gives divide by Zero error
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Filter_Profit_Protector]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
    	@PurchCatID int = -1,
        @optShowGP tinyint = 1
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(8000),
            @sql varchar(8000)

	SET @Filter = ''
    SET @sql = ''


    --> Products_Suppliers
	IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Purchase Category
	IF @PurchCatID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchCatID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchCatID)
		END


	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)


-- NEW 2004.3.8
        SET @Filter = @Filter + ' AND p.Slu_AW_Active_ID = 1 '


    	SET @sql = 'SELECT '
        SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
        SET @sql = @sql + ' p.[Description] AS [Description], '
        SET @sql = @sql + ' p.Product_Code AS [Code], '

        -----------------------------------------------------------------
        -- Cost
        -----------------------------------------------------------------
        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
                SET @sql = @sql + ' ISNULL(p.Average_Cost, 0) AS [Cost], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
                SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [Cost], '
            END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
            BEGIN
                SET @sql = @sql + ' ISNULL(p.Standard_Cost, 0) AS [Cost], '
            END

        -----------------------------------------------------------------
        -- Std GP%
        -----------------------------------------------------------------
        SET @sql = @sql + ' CONVERT(money, dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate())) AS [Selling], '

        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
                SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), ISNULL(p.Average_Cost, 0))) AS [Std GP%], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
                SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), ISNULL(p.Last_Cost, 0))) AS [Std GP%], '
            END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
            BEGIN
                SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), ISNULL(p.Standard_Cost, 0))) AS [Std GP%], '
            END


        SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Price AS [Edit Price], '
        SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Discount AS [Edit Disc], '
        SET @sql = @sql + ' p.Max_Discount_Perc AS [Min GP%], '

        -----------------------------------------------------------------
        -- Min Retail
        -----------------------------------------------------------------
        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
 				SET @sql = @sql + ' CASE ' 
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Average_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0))))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' ELSE '
                SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Average_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0)))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' END AS [Min Retail], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
 				SET @sql = @sql + ' CASE ' 
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Last_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0))))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' ELSE '
                SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Last_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0)))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' END AS [Min Retail], '
           END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
            BEGIN
 				SET @sql = @sql + ' CASE ' 
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Standard_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0))))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' ELSE '
                SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Standard_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0)))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' END AS [Min Retail], '
            END

        -----------------------------------------------------------------
        -- Max Discount %
        -----------------------------------------------------------------
        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
				SET @sql = @sql + ' CASE '
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0)))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' ELSE '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' END AS [Max Disc%], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
				SET @sql = @sql + ' CASE '
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0)))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' ELSE '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' END AS [Max Disc%], '
            END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
			BEGIN
				SET @sql = @sql + ' CASE '
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0)))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' ELSE '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' END AS [Max Disc%], '
            END
        -----------------------------------------------------------------

        SET @sql = @sql + ' p.Slu_AW_YesNo_Max_Discount_Perc AS [Apply Min%] '

        SET @sql = @sql + ' FROM AP_Products p '
        SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
        SET @sql = @sql + '         ON s.AO_Suppliers_ID = p.Default_Supplier_ID '
        SET @sql = @sql + @Filter
        SET @sql = @sql + ' ORDER BY p.[Description] '

		EXEC (@sql)
--SELECT @sql
	END

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














--sp_AP_Filter_Std_Cost_Adjustments 1, -1, -1, -1, -1, -1, -1, 0, 0, 0

-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Std_Cost_Adjustments
--Purpose       :Filters Products to calculate Standard Cost
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2006/06/05
--Authors       :TB
--MODS          :
--2004.3.3      :09/11/06 - Added Standard_Disc1 and Standard_Disc2 fields
--              :09/11/06 - Modified to fetch Default_Supplier_ID from AP_Products
--              :           if Supplier has been removed
--2004.3.8      :10/04/08 - Added elimate all products not Active
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Filter_Std_Cost_Adjustments
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(4000),
            @sql varchar(8000)

    SET @Filter = ''
    SET @sql = ''

    --> Products_Suppliers
    IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
    	END

	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)


-- NEW 2004.3.8
        SET @Filter = @Filter + ' AND p.Slu_AW_Active_ID = 1 '


    	SET @sql = 'SELECT '
        SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
        SET @sql = @sql + ' p.[Description] AS [Description], '
        SET @sql = @sql + ' p.Product_Code AS [Code], '
        SET @sql = @sql + ' p.Pack_Size AS [Size], '
        SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Selling 1], '
        SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Selling 2], '
        SET @sql = @sql + ' p.Standard_Disc1 AS [Std. Disc1], '
        SET @sql = @sql + ' p.Standard_Disc2 AS [Std. Disc2], '
        SET @sql = @sql + ' p.Standard_Cost AS [Std. Cost] '

        SET @sql = @sql + ' FROM AP_Products p '
        SET @sql = @sql + @Filter



        IF @OnHandOnly = 1
            BEGIN
                SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
            END


        IF @NonStock = 1
            BEGIN
                SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


        IF @Sort = 1
            BEGIN
                SET @sql = @sql + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN
                SET @sql = @sql + ' ORDER BY p.[Description] '
            END



        EXEC (@sql)

	END

SET NOCOUNT OFF	














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Stock_Level_Settings
--Purpose       :Filters Products to calculate Stock Reorder Levels
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2007/06/10
--Authors       :TB
--MODS          :
--2004.3.8      :24/05/08 - Added SELECT Service_Level field as [SL]
--2004.4.1      :29/09/08 - Added Purchase Category
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Filter_Stock_Level_Settings
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@PurchCatID int = -1,
        @Sales tinyint,
        @OnHand tinyint,
        @Orders tinyint,
        @Levels tinyint,
        @FilterAll tinyint,
        @NonStock tinyint,
        @Sort tinyint,
        @EndDate datetime,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
	)

AS

SET NOCOUNT ON

	DECLARE @filter varchar(8000),
            @sql varchar(8000),
            @StartDate datetime


    ---------------------------------------------
    --> Select TOUCHED Products using TABLE datatype
    ---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AP_Product_Levels]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AP_Product_Levels]
    ---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AP_Product_Level_Details]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AP_Product_Level_Details]
    ---------------------------------------------


    SET @StartDate = DATEADD(yy, -1, @EndDate)


    ---------------------------------------------
    --> Company
    SET @Filter = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(20), @CompanyID)
    SET @Filter = @Filter + '   AND p.Slu_AW_Active_ID = 1 '

    ---------------------------------------------
    IF @NonStock = 1
        BEGIN
            SET @Filter = @Filter + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END
    ---------------------------------------------


    ---------------------------------------------
    -- MULTIPLE filter SELECT
    ---------------------------------------------
    --> Products_Suppliers
    IF @SupplierID > 0 
        BEGIN
    		SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                        convert(varchar(20), @SupplierID)
        END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                        convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                        convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                        convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                        convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @PurchCatID  > 0 
		BEGIN
			SET @Filter = @Filter + ' AND p.Lup_AP_Purchase_Categories_ID = ' +
                                        convert(varchar(20), @PurchCatID)
    	END
    ---------------------------------------------


    ---------------------------------------------
	SET @sql = ' DECLARE @ActiveProducts table '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     [AP_Products_ID] int '
    SET @sql = @sql + ' ) '

    IF @Sales = 1
        BEGIN
            SET @sql = @sql + ' INSERT INTO @ActiveProducts '
            SET @sql = @sql + ' SELECT DISTINCT d.AP_Products_ID '
            SET @sql = @sql + ' FROM AS_Transaction_Details d '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + @filter
            SET @sql = @sql + '   AND dbo.fn_AS_Product_Has_Sales(' + 
                                                   convert(varchar(20), @CompanyID) + ', ' +
                                            '''' + convert(varchar(20), @StartDate) + '''' + ', ' +
                                            '''' + convert(varchar(20), @EndDate) + '''' + ') = 1 '
        END

    IF @OnHand = 1
        BEGIN
            SET @sql = @sql + ' INSERT INTO @ActiveProducts '
            SET @sql = @sql + ' SELECT DISTINCT p.AP_Products_ID '
            SET @sql = @sql + ' FROM AP_Products p '
            SET @sql = @sql + @filter
            SET @sql = @sql + '   AND p.On_Hand <> 0 '
        END

    IF @Orders = 1
        BEGIN
            SET @sql = @sql + ' INSERT INTO @ActiveProducts '
            SET @sql = @sql + ' SELECT DISTINCT od.AP_Products_ID '
            SET @sql = @sql + ' FROM AO_Order_Details od '
            SET @sql = @sql + '     INNER JOIN AO_Orders oh '
            SET @sql = @sql + '         ON od.AO_Orders_ID = oh.AO_Orders_ID '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + @filter
            SET @sql = @sql + '   AND oh.Date_Ordered IS NOT NULL '
            SET @sql = @sql + '   AND oh.Complete <> 1 '
            SET @sql = @sql + '   AND (ISNULL(od.Order_Qty, 0) + ISNULL(od.Back_Order_Qty, 0) - ISNULL(od.Received_Qty, 0)) > 0 '
        END

    IF @Levels = 1
        BEGIN
            SET @sql = @sql + ' INSERT INTO @ActiveProducts '
            SET @sql = @sql + ' SELECT DISTINCT p.AP_Products_ID '
            SET @sql = @sql + ' FROM AP_Products p '
            SET @sql = @sql + @filter
            SET @sql = @sql + '   AND ( '
            SET @sql = @sql + '           p.Min_Stock_Level <> 0 OR '
            SET @sql = @sql + '           p.Min_Order_Qty <> 0 OR '
            SET @sql = @sql + '           p.Max_Order_Qty <> 0 '
            SET @sql = @sql + '       ) '
        END

    IF @FilterAll = 1 OR (@Sales = 0 AND @OnHand = 0 AND @Orders = 0 AND @Levels = 0)
        BEGIN
            SET @sql = @sql + ' INSERT INTO @ActiveProducts '
            SET @sql = @sql + ' SELECT DISTINCT p.AP_Products_ID '
            SET @sql = @sql + ' FROM AP_Products p '
            SET @sql = @sql + @filter
        END

    ---------------------------------------------
    SET @sql = @sql + ' SELECT DISTINCT AP_Products_ID '
    SET @sql = @sql + ' INTO AP_Product_Levels '
    SET @sql = @sql + ' FROM @ActiveProducts '
    SET @sql = @sql + ' ORDER BY AP_Products_ID '
    ---------------------------------------------


    EXEC (@sql)
    ---------------------------------------------


	SET @sql = ' SELECT '
    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Description], '
    SET @sql = @sql + ' ISNULL(p.Product_Code, '''') AS [Code], '
    SET @sql = @sql + ' ISNULL(p.Service_Level, 1) AS [SL], '
    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL], '
    SET @sql = @sql + ' ISNULL(p.Min_Order_Qty, 0) AS [Min], '
    SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) AS [Max], '
    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jan + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jan], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Feb + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Feb], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Mar + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Mar], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Apr + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Apr], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @May + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [May], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jun + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jun], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jul + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jul], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Aug + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Aug], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Sep + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Sep], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Oct + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Oct], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Nov + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Nov], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Dec + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Dec] '

    ---------------------------------------------
    SET @sql = @sql + ' INTO AP_Product_Level_Details '
    ---------------------------------------------

    SET @sql = @sql + ' FROM AP_Product_Levels pl '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON pl.AP_Products_ID = p.AP_Products_ID '

    ---------------------------------------------

    ---------------------------------------------


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY p.Product_Code '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY p.[Description] '
        END
    ---------------------------------------------


    EXEC (@sql)


    SELECT *
    FROM AP_Product_Level_Details



    ---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AP_Product_Levels]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AP_Product_Levels]
    ---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AP_Product_Level_Details]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AP_Product_Level_Details]
    ---------------------------------------------





SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Stock_Take_Filters
--Purpose       :Filters Products from Stock Takes
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2009/02/19
--Authors       :TB
--MODS          :
--2004.4.4      :29/04/09 - Added @ProcedureID input parameter !!!!
--              :30/04/09 - Added User_ID field to assign ID of editing user
--              :30/04/09 - Added also to include fetch items with NON-ZERO COUNT if @OnHandOnly = 1
--V6.2	RL	2015-12-01	:Added Product Bins and Consignment
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Filter_Stock_Take_Filters]
	(
    	@CompanyID int,
    	@ProcedureID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
        @LocationID int = -1,
        @PurchaseID int = -1,
        @BinID int = -1,
        @OnHandOnly tinyint,
        @Sort tinyint,
        @NonStock tinyint,
        @VarianceOnly tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(8000),
            @SQL varchar(8000)

	SET @Filter = ''
    SET @SQL = ''


    SET @Filter = ' WHERE ' + ' st.AP_Stock_Take_Procedures_ID = ' +
                                convert(varchar(20), @ProcedureID)

    --> Products_Suppliers
	IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
		END

    --> Purchase Category
	IF @PurchaseID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseID)
		END

    --> Product Bins
	IF @BinID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' st.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND st.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END

	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)
		ELSE
			SET @Filter = @Filter + ' AND p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' st.AP_Products_Stock_Takes_ID AS [ID], '
        SET @SQL = @SQL + ' st.AP_Stock_Take_Procedures_ID AS [StockTakeProcedureID], '
        SET @SQL = @SQL + ' st.AP_Products_ID AS [Product_ID], '
        SET @SQL = @SQL + ' ISNULL(p.[Description], '''') AS [Product], '
        SET @SQL = @SQL + ' ISNULL(p.Product_Code, '''') AS [Code], '
        SET @SQL = @SQL + ' st.Total_On_Hand AS [Total On Hand], '
        SET @SQL = @SQL + ' st.Consignment_Qty AS [Cons Qty], '                        
        SET @SQL = @SQL + ' ISNULL(b.[Description], '''') AS [Bin], '
        SET @SQL = @SQL + ' ISNULL(st.Lup_AP_Product_Bins_ID, 1) AS [BinID], '
        SET @SQL = @SQL + ' st.Count1 AS [Count1], '
        SET @SQL = @SQL + ' st.Count2 AS [Count2], '
        SET @SQL = @SQL + ' st.Count3 AS [Count3], '
        SET @SQL = @SQL + ' st.Total_Count AS [Total], '
        SET @SQL = @SQL + ' st.On_Hand AS [On Hand], '
        SET @SQL = @SQL + ' st.Variance AS [Variance], '
        SET @SQL = @SQL + ' st.Unit_Cost AS [Unit Cost], '        
        SET @SQL = @SQL + ' st.User_ID AS [User] '
        SET @SQL = @SQL + ' FROM AP_Products_Stock_Takes st '
        SET @SQL = @SQL + '     LEFT JOIN AP_Products p '
        SET @SQL = @SQL + '         ON st.AP_Products_ID = p.AP_Products_ID '
        SET @SQL = @SQL + '     LEFT OUTER JOIN LUP_AP_Product_Bins b '
        SET @SQL = @SQL + '         ON st.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID '        
        SET @SQL = @SQL + @Filter


        IF @OnHandOnly = 1
            BEGIN
                SET @sql = @sql + ' AND (st.On_Hand <> 0 OR st.Total_Count <> 0) '
            END


        IF @NonStock = 1
            BEGIN
                SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


        IF @VarianceOnly = 1
            BEGIN
                SET @sql = @sql + ' AND st.Variance <> 0 '
            END


        IF @Sort = 1
            BEGIN
                SET @sql = @sql + ' ORDER BY p.Product_Code, b.[Description] '
            END
        ELSE
            BEGIN
                SET @sql = @sql + ' ORDER BY p.[Description], b.[Description] '
            END



		EXEC (@SQL)

	END



SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------------
--Description   :sp_AP_Get_Commission_Groups
--Purpose       :
--Functionality :Tables: Lup_AP_Commission_Groups
--Parameters    :
--Date          :08 FEB 2002
--Authors       :TB
--Version       :1.0.0
----------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Get_Commission_Groups
(
	@Company_ID int
)

AS

SET NOCOUNT ON

-- MOD by TB but joins cannot update RS ?
	SELECT a.Lup_AP_Commission_Groups_ID AS [ID],
		a.Description AS [Commission Group],
		a.Date_Captured AS [Date],
        CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
                 THEN ISNULL(b.Surname,'')
             WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
                 THEN ISNULL(b.Surname,'')
             ELSE ISNULL(b.Surname,'') + ', ' + 
                  LTRIM(ISNULL(b.FirstName,''))
             END AS [User],
        c.Description AS [Active]
	FROM dbo.Lup_AP_Commission_Groups a
		INNER JOIN AW_users b
            ON a.User_ID = b.AW_Users_ID
        INNER JOIN dbo.Slu_AW_Active c
            ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
	WHERE AW_User_Companies_ID = @Company_ID

-- 	SELECT Lup_AP_Commission_Groups_ID AS [ID],
-- 		  [Description] AS [Commission Group],
-- 		   Date_Captured AS [Date],
-- 		  [User_ID] AS [User ID],
-- 		   Slu_AW_Active_ID AS [Active]
-- 	FROM dbo.Lup_AP_Commission_Groups
-- 	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------------
--Description   :sp_AP_Get_Discount_Groups
--Purpose       :
--Functionality :Tables: Lup_AP_Discount_Groups
--Parameters    :
--Date          :2002/02/08
--Authors       :TB
--MODS          :
--2004.4.0      :28/07/07 - Added ORDER BY [Description]
--              :28/07/07 - Reworked using [User], [Active] ID's to allow ListBindGrid
----------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Get_Discount_Groups
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT Lup_AP_Discount_Groups_ID AS [ID],
           [Description] AS [Discount Group],
           Date_Captured AS [Date],
           [User_ID] AS [User],
           Slu_AW_Active_ID AS [Active]
	FROM Lup_AP_Discount_Groups
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]


-- 	SELECT a.Lup_AP_Discount_Groups_ID AS [ID],
--            a.[Description] AS [Discount Group],
--            a.Date_Captured AS [Date],
--            CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
--                     THEN ISNULL(b.Surname,'')
--                 WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
--                     THEN ISNULL(b.Surname,'')
--                 ELSE ISNULL(b.Surname,'') + ', ' + 
--                      LTRIM(ISNULL(b.FirstName,''))
--                 END AS [User],
--            c.Description AS [Active]
-- 	FROM Lup_AP_Discount_Groups a
-- 		INNER JOIN AW_users b
--             ON a.User_ID = b.AW_Users_ID
--         INNER JOIN dbo.Slu_AW_Active c
--             ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
-- 	WHERE AW_User_Companies_ID = @Company_ID
--     ORDER BY a.[Description]



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description	:sp_AP_Get_Manufacturer_ProductID
--Purpose       :Gets AP_Products_ID from Product_Code for SPECIFIC Manufacturer
--              :used in Product Price Updates
--Date			:2005/04/05
--Authors		:TB
--MODS          :05/04/05 - Added fetch of EXISTING Product Description to show
--              :            in Price Update Laod grid
--2004.2.9      :08/05/06 - Added fetch TOP 1 ACTIVE ProductID
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Get_Manufacturer_ProductID
	(
		@ProductCode varchar(20),
        @chkManufacturer tinyint,
        @ManufacturerID int,
        @CompanyID int,
        @ProductID int OUTPUT,
        @ProductDesc varchar(50) OUTPUT
	)

AS

SET NOCOUNT ON

    IF @chkManufacturer = 1
        BEGIN
            SELECT TOP 1 @ProductID = AP_Products_ID,
                         @ProductDesc = Description
            FROM AP_Products
            WHERE Product_Code = @ProductCode AND
                  AW_User_Companies_ID = @CompanyID AND
                  Lup_AP_Product_Manufacturers_ID = @ManufacturerID AND
                  Slu_AW_Active_ID = 1
        END
    ELSE
        BEGIN
            SELECT TOP 1 @ProductID = AP_Products_ID,
                         @ProductDesc = Description
            FROM AP_Products
            WHERE Product_Code = @ProductCode AND
                  AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
        END



--     IF @chkManufacturer = 1
--         BEGIN
--             SELECT @ProductID = AP_Products_ID,
--                    @ProductDesc = Description
--             FROM AP_Products
--             WHERE Product_Code = @ProductCode AND
--                   AW_User_Companies_ID = @CompanyID AND
--                   Lup_AP_Product_Manufacturers_ID = @ManufacturerID
--         END
--     ELSE
--         BEGIN
--             SELECT @ProductID = AP_Products_ID,
--                    @ProductDesc = Description
--             FROM AP_Products
--             WHERE Product_Code = @ProductCode AND
--                   AW_User_Companies_ID = @CompanyID
--         END











SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










----------------------------------------------------------------------------------
--Description   :sp_AP_Get_Markup_Groups
--Purpose       :
--Functionality :Tables: Lup_AP_Markup_Groups
--Parameters    :
--Date          :2007/07/23
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Get_Markup_Groups
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT a.Lup_AP_Markup_Groups_ID AS [ID],
		a.Description AS [Markup Group],
		a.Date_Captured AS [Date],
        CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
                 THEN ISNULL(b.Surname,'')
             WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
                 THEN ISNULL(b.Surname,'')
             ELSE ISNULL(b.Surname,'') + ', ' + 
                  LTRIM(ISNULL(b.FirstName,''))
             END AS [User],
        c.Description AS [Active]
	FROM Lup_AP_Markup_Groups a
		INNER JOIN AW_users b
            ON a.User_ID = b.AW_Users_ID
        INNER JOIN dbo.Slu_AW_Active c
            ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AP_Get_Non_Stock_Value
--Purpose       :Gets Non-Stock field setting from a AP_Products_ID
--Date			:2005/03/26
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Get_On_Hand
	(
		@ProductID int,
        @CompanyID int,
        @NonStock tinyint OUTPUT,
        @OnHand decimal(9, 3) OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @NonStock = Slu_AW_YesNo_Non_Stock_Item,
           @OnHand = On_Hand
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID AND
          AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description	:sp_AP_Get_On_Hand_Bin
--Purpose       :Gets Non-Stock field setting from a AP_Products_ID and Bin
--Date			:2016/04/08
--Authors		:RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_On_Hand_Bin]
	(
		@ProductID int,
		@ProductBinID int,
        @CompanyID int,
        @NonStock tinyint OUTPUT,
        @OnHand decimal(9, 3) OUTPUT
	)
AS

SET NOCOUNT ON

    SELECT @NonStock = Slu_AW_YesNo_Non_Stock_Item,
           @OnHand = b.On_Hand
    FROM AP_Products p
		INNER JOIN AP_Products_Bins b
			ON p.AP_Products_ID = b.AP_Products_ID
    WHERE p.AP_Products_ID = @ProductID AND
          p.AW_User_Companies_ID = @CompanyID AND
          b.Lup_AP_Product_Bins_ID = @ProductBinID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Opening_Closing_On_Hand
--Purpose       :Retrieve the opening and closing Inventory balances from a date
--Parameters    :
--Date          :2004/10/10
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Get_Opening_Closing_On_Hand
    (
        @StartDate as datetime,
        @ProductID int,
        @BFWD float OUTPUT,
        @OnHand float OUTPUT
    )

AS

SET NOCOUNT ON


   SELECT @BFWD = ISNULL(dbo.fn_AP_BFWD_Inventory_On_Hand(@ProductID, @StartDate), 0),
          @OnHand = ISNULL(On_Hand, 0)
   FROM AP_Products
   WHERE AP_Products_ID = @ProductID



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   :sp_AP_Get_Post_Code_Shipping_Rate
--Purpose       :Get the Shipping Rate for the selected Shipping Code
--Date          :21 AUG 2009
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Get_Post_Code_Shipping_Rate
    (
        @PostCode varchar(10),
        @ShipRateKG money OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @ShipRateKG = ISNULL(Rate_Per_Kg, 0)
    FROM Slu_AW_Shipping_Rates
    WHERE Post_Code = @PostCode















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AP_Get_ProductID
--Purpose       :Gets AP_Products_ID from Product_Code
--              :
--Date			:2003/10/08
--Authors		:TB
--MODS          :30/12/03 - Added @CompanyID input parameter to validate that
--              :           ProductID belongs to this Company. This negates
--              :           duplicated Product Codes that can potentially exist
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Get_ProductID
	(
		@ProductCode varchar(20),
        @CompanyID int,
        @ProductID int OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @ProductID = AP_Products_ID
    FROM AP_Products
    WHERE Product_Code = @ProductCode AND
          AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description	:sp_AP_Get_Product_Activity_Count
--Purpose       :Gets primary DB table activity for ONE AP_Products_ID
--Date			:2008/05/19
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Get_Product_Activity_Count
	(
		@ProductID int,
        @CompanyID int,
        @Sale int OUTPUT,
        @GRV int OUTPUT,
        @Order int OUTPUT,
        @ADJ int OUTPUT,
        @OnHand decimal(9, 3) OUTPUT
	)

AS

SET NOCOUNT ON

    SET @Sale = 0
    SET @GRV = 0
    SET @Order = 0
    SET @ADJ = 0
    SET @OnHand = 0
    
    
    SELECT @Sale = count(*)
    FROM AS_Transaction_Details
    WHERE AP_Products_ID = @ProductID AND
          AW_User_Companies_ID = @CompanyID
    
    SELECT @GRV = count(*)
    FROM AO_GRV_Details
    WHERE AP_Products_ID = @ProductID AND
          AW_User_Companies_ID = @CompanyID
    
    SELECT @Order = count(*)
    FROM AO_Order_Details
    WHERE AP_Products_ID = @ProductID AND
          AW_User_Companies_ID = @CompanyID
    
    SELECT @ADJ = count(*)
    FROM AP_Inventory_Adjustments
    WHERE AP_Products_ID = @ProductID AND
          AW_User_Companies_ID = @CompanyID

    SELECT @OnHand = On_Hand
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID AND
          AW_User_Companies_ID = @CompanyID




SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_Reserved
--Purpose       :Fetch the JOB RESERVED Qty for ONE Product on ALL OPEN Jobcards
--Functionality :Returns the value from a SCALAR function
--Date          :2007/05/11
--Authors       :TB
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Get_Product_Job_Reserved
    (
        @ProductID int,
        @Reserved float OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @Reserved = dbo.fn_AP_SUM_Product_Job_Reserved(@ProductID)



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_Reserved_Bin
--Purpose       :Fetch the JOB RESERVED Qty for ONE Product and Bin on ALL OPEN Jobcards
--Date          :2016/04/08
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_Product_Job_Reserved_Bin]
    (
        @ProductID int,
        @ProductBinID int,
        @Reserved float OUTPUT
    )
AS

SET NOCOUNT ON

        SELECT @Reserved = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
			  d.Lup_AP_Product_Bins_ID = @ProductBinID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
 
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_SO_Reserved_Bin_NO_BO
--Purpose       :Fetch the JOB RESERVED Qty for ONE Product and Bin on ALL OPEN Jobcards
--Date          :2017/10/10
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_Product_Job_SO_Reserved_Bin_NO_BO]
    (
        @ProductID int,
        @ProductBinID int,
        @Reserved float OUTPUT
    )
AS

SET NOCOUNT ON

        SELECT @Reserved = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
			  d.Lup_AP_Product_Bins_ID = @ProductBinID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
 
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_SO_Reserved_NO_BO
--Purpose       :Fetch the JOB RESERVED and Sales Orders Qty Excluding Back Orders
--Functionality :Returns the value from a SCALAR function
--Date          :2017/10/10
--Authors       :RL
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AP_Get_Product_Job_SO_Reserved_NO_BO]
    (
        @ProductID int,
        @Reserved float OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @Reserved = dbo.fn_AP_SUM_Product_Job_SO_Reserved_NO_BO(@ProductID)



SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Lookup_ID
--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
--2004.5.8 RGL  :2013-02-05 - Added a check to make sure blank (NULL) descriptions are not added
-------------------------------------------------------------------------------

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
			IF @Manuf <> ''
				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] = '<None>' AND
						Slu_AW_Active_ID = 1			
				END	
        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
			IF @Supplier <> ''
				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 = '<None>' AND
						Slu_AW_Active_ID = 1				
				END		
		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
			IF @Type <> ''
				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] = '<None>' AND
						Slu_AW_Active_ID = 1				
				END	
		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
			IF @Group <> ''
				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] = '<None>' AND
						Slu_AW_Active_ID = 1							
				END
		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
			IF @Dept <> ''
				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] = '<None>' AND
						Slu_AW_Active_ID = 1				
				END
		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
			IF @Location <> ''
				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] = '<None>' AND
						Slu_AW_Active_ID = 1				
				END		
		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
			IF @PurchaseCat <> ''
				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] = '<None>' AND
						Slu_AW_Active_ID = 1		
				END		
		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 NOT EXISTS
		(
			SELECT Lup_AP_AW_Weight_ID
			FROM Lup_AP_AW_Weight
			WHERE AW_User_Companies_ID = @CompanyID AND
				[Description] = @WeightType AND
				Slu_AW_Active_ID = 1
		)
		BEGIN
			IF @WeightType <> ''
				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
						[Description] = '<None>' AND
						Slu_AW_Active_ID = 1				
				END		
		END
	ELSE
		BEGIN
			SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
			FROM Lup_AP_AW_Weight
			WHERE AW_User_Companies_ID = @CompanyID AND
				[Description] = @WeightType AND
				Slu_AW_Active_ID = 1		
		END	

    SET @RetCode = 1

    RETURN @RetCode


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-----------------------------------------------------------------------------
--Description   :sp_AP_Stock_Bonded_Lups
--Purpose       :Agent and Bonded Stock Interface info
--Date          :2010/10/07
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Get_Shipping_Agent_File
    (
        @AgentID smallint,
        @AgentFileID smallint,
    	@CompanyID int,
        @Agent varchar(50) OUTPUT,
        @Customer_Code varchar(50) OUTPUT,
        @Warehouse_No varchar(50) OUTPUT,
        @FileDesc varchar(50) OUTPUT,
        @Server_Name varchar(50) OUTPUT,
        @Login_Name varchar(50) OUTPUT,
        @Login_Password varchar(50) OUTPUT,
        @Folder varchar(50) OUTPUT
    )

AS

SET NOCOUNT ON


    --> Shipping Agent
    	SELECT @Agent = Description,
               @Customer_Code = Customer_Code,
               @Warehouse_No = Warehouse_No
    	FROM Lup_AP_Shipping_Agents
    	WHERE AW_User_Companies_ID = @CompanyID AND
              Lup_AP_Shipping_Agents_ID = @AgentID AND
              Slu_AW_Active_ID = 1


    --> Shipping Agent File (Bonded Stock Interfaces)
    	SELECT @FileDesc = Description,
               @Server_Name = Server_Name,
               @Login_Name = Login_Name,
               @Login_Password = Login_Password,
               @Folder = Folder
    	FROM Lup_AP_Shipping_Agent_Files
    	WHERE AW_User_Companies_ID = @CompanyID AND
              Lup_AP_Shipping_Agents_ID = @AgentID AND
              Lup_AP_Shipping_Agent_Files_ID = @AgentFileID AND
              Slu_AW_Active_ID = 1




SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Stock_Take_Status
--Purpose       :Check if Stock Procedure Stock Adjustments Posted
--Date          :2009/02/21
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Get_Stock_Take_Status
	(
        @StockTakeProcedureID int,
        @Month varchar(10) OUTPUT,
        @Year varchar(10) OUTPUT,
        @GLJournalID int OUTPUT,
        @GLJournalRef varchar(30) OUTPUT,
        @AdjustmentTotal money OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    SELECT @Month = ISNULL(m.Description, ''),
           @Year = ISNULL(y.Description, ''), 
           @GLJournalID = ISNULL(p.AB_Journals_ID, 0),
           @GLJournalRef = ISNULL(j.Journal_Reference, ''),
           @AdjustmentTotal = ISNULL(p.Stock_Adjustment_Total, 0)
    FROM AP_Stock_Take_Procedures p
        LEFT JOIN Slu_AW_Months m
            ON p.Slu_AW_Months_ID = m.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years y
            ON p.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        LEFT JOIN AB_Journals j
            ON p.AB_Journals_ID = j.AB_Journals_ID
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID


    SET @ReturnValue = 1


RETURN @ReturnValue














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Stock_Take_Variance
--Purpose       :
--Date          :2009/02/19
--Authors       :TB
--MODS          :
----V6.3	RL	2017-02-01	:Changed On_Hand_Calc Back to On_Hand - Original Inventory Value
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_Stock_Take_Variance]
	(
        @StockTakeProcedureID int,
        @StockTotal money OUTPUT,
        @Variance money OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    SELECT @StockTotal = SUM(ISNULL(On_Hand, 0) * ISNULL(Unit_Cost, 0)),
           @Variance = SUM(ISNULL(Variance_Calc, 0) * ISNULL(Unit_Cost, 0))
    FROM AP_Products_Stock_Takes
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID


    SET @ReturnValue = 1


RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Bond_Stock_Log
--Purpose       :Insert Bond Stock Log
--Date          :2010/09/09
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Insert_Bond_Stock_Log
	(
        @FileType varchar(200),
        @Status varchar(30),
        @FileLocation varchar(250),
        @Computer varchar(50),
        @FTPLoginURL varchar(250),
        @FTPUserName varchar(250),
        @FTPPassword varchar(250),
        @FTPFolder varchar(250),
        @FileDate varchar(20),
        @FileTime varchar(20),
        @RowCNT varchar(20),
        @UserID int, 
        @CompanyID int, 
        @TrfLogID int OUTPUT
	)

AS

SET NOCOUNT ON

	INSERT AP_Bond_Stock_Log
        (
            File_Type,
            Status,
            File_Location,
            Computer,
            FTP_Login_URL,
            FTP_User_Name,
            FTP_Password,
            FTP_Folder,
            File_Date,
            File_Time,
            Row_CNT,
            User_ID,
            AW_User_Companies_ID
        )
	VALUES
		(
            @FileType,
            @Status,
            @FileLocation,
            @Computer,
            @FTPLoginURL,
            @FTPUserName,
            @FTPPassword,
            @FTPFolder,
            @FileDate,
            @FileTime,
            @RowCNT,
            @UserID,
            @CompanyID
		)

    SELECT @TrfLogID = Scope_Identity()


RETURN @TrfLogID







SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   : sp_AP_Insert_Commission_Groups
--Purpose       : Inserts a newly added Lup_AS_Commission_Groups record into
--              : Lup_AP_Commission_Groups
--Functionality : Tables: Lup_AP_Commission_Groups
--Parameters    : 
--Date          : 2002/02/07
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE   PROCEDURE  sp_AP_Insert_Commission_Groups
    (
        @Description varchar(50),
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    INSERT Lup_AP_Commission_Groups
        (
            [Description],
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT @Description,
           getdate(),
           @UserID,
           @CompanyID,
           1            -- Enabled

    RETURN scope_identity()

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Contract_Products
--Purpose       :INSERT Customer Contract Prices
--Parameters    :
--Date          :2004/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	:MinSaleQty - Contract price if minimum quantity sold 
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_Contract_Products]
	(
        @CustomerID int,
        @ProductID int,
        @Product varchar(50),
        @ProductCode varchar(20),
        @StartDate datetime,
        @EndDate datetime,
        @PackSize [decimal](9, 3),
        @UnitPrice money,
        @DiscountPerc decimal(9,3),
        @DiscountAmount money,
        @MinSaleQty decimal(9,3),
        @Active tinyint,
        @UserID int,
        @CompanyID int
	)
AS

SET NOCOUNT ON

    DECLARE @ContractProductID int

    INSERT AC_Contract_Prices
        (
            AC_Customers_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Start_Date,
            End_Date,
            Pack_Size,
            Unit_Price,
            Discount_Perc,
            Discount_Amount,
            MinSaleQty,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    VALUES
        (
            @CustomerID,
            @ProductID,
            @Product,
            @ProductCode,
            @StartDate,
            @EndDate,
            @PackSize,
            @UnitPrice,
            @DiscountPerc,
            @DiscountAmount,
            @MinSaleQty,
            @UserID,
            @CompanyID,
            @Active
        )

	SELECT @ContractProductID = Scope_Identity() 

RETURN @ContractProductID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   : sp_AP_Insert_Discount_Groups
--Purpose       : Inserts a newly added Lup_AS_Discount_Groups record into
--              : Lup_AP_Discount_Groups
--Functionality : Tables: Lup_AP_Discount_Groups
--Parameters    : 
--Date          : 2002/02/09
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE    PROCEDURE  sp_AP_Insert_Discount_Groups
    (
        @Description varchar(50),
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    INSERT Lup_AP_Discount_Groups
        (
            [Description],
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT @Description,
           getdate(),
           @UserID,
           @CompanyID,
           1            -- Enabled

    RETURN scope_identity()

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













--sp_AP_Insert_Enterprise_Slow_Moving_Stock 'ADV2004', '"A" FRAME', 'TAC156', 1, 'Bosal', 5

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock
--Purpose       :INSERT Enterprise Stock
--Date          :2006/10/05
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Insert_Enterprise_Slow_Moving_Stock
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @OnHand int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Slow_Moving_Stock_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Slow_Moving_Stock '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Slow_Moving_Stock '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @OnHand) + ', '
--    SET @sql = @sql + '         Total = Total + ' + CONVERT(varchar(20), @OnHand)
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @OnHand)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Slow_Moving_Stock '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @OnHand) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @OnHand) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












--sp_AP_Insert_Enterprise_Stock 'ADV200430', '"A" FRAME', 'TAC156', 1, 'Bosal', 5

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock
--Purpose       :INSERT Enterprise Stock
--Date          :2006/05/22
--Authors       :TB
--MODS:         :
--2004.3.2      :20/09/06 - Modified CONVERT(varchar(10) to CONVERT(varchar(20)
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Insert_Enterprise_Stock
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @OnHand int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Stock_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Stock '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Stock '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @OnHand) + ', '
--    SET @sql = @sql + '         Total = Total + ' + CONVERT(varchar(20), @OnHand)
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @OnHand)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Stock '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @OnHand) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @OnHand) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














--sp_AP_Insert_Enterprise_Stock 'ADV200430', '"A" FRAME', 'TAC156', 1, 'Bosal', 5

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock_Filter
--Purpose       :INSERT Enterprise Stock
--Date          :2006/09/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Insert_Enterprise_Stock_Filter
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @OnHand int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Stock_Filter_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Stock_Filter '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Stock_Filter '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @OnHand) + ', '
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @OnHand)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Stock_Filter '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @OnHand) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @OnHand) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock_MSL
--Purpose       :INSERT Enterprise Stock
--Date          :2008/12/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Insert_Enterprise_Stock_MSL
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @MSL int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Stock_MSL_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Stock_MSL '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Stock_MSL '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @MSL) + ', '
--    SET @sql = @sql + '         Total = Total + ' + CONVERT(varchar(20), @MSL)
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @MSL)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Stock_MSL '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @MSL) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @MSL) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock_Replenish
--Purpose       :INSERT Enterprise Stock Replenishment
--Date          :2008/12/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Insert_Enterprise_Stock_Replenish
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @ToOrder int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Stock_Replenish_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Stock_Replenish '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Stock_Replenish '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @ToOrder) + ', '
--    SET @sql = @sql + '         Total = Total + ' + CONVERT(varchar(20), @ToOrder)
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @ToOrder)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Stock_Replenish '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @ToOrder) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @ToOrder) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock_Replenish_Max
--Purpose       :INSERT Enterprise Stock Replenishment Max Order Qty
--Date          :2009/07/23
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AP_Insert_Enterprise_Stock_Replenish_Max
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @ToOrder int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Stock_Replenish_Max_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Stock_Replenish_Max '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Stock_Replenish_Max '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @ToOrder) + ', '
--    SET @sql = @sql + '         Total = Total + ' + CONVERT(varchar(20), @ToOrder)
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @ToOrder)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Stock_Replenish_Max '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @ToOrder) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @ToOrder) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













--sp_AP_Insert_Enterprise_Stock_Valuation 'ADV200430', '"A" FRAME', 'TAC156', 1, 'Bosal', 5

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Enterprise_Stock_Valuation
--Purpose       :INSERT Enterprise Stock Valuation
--Date          :2006/05/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Insert_Enterprise_Stock_Valuation
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @Cost money
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' IF EXISTS '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT AP_Enterprise_Stock_Valuation_ID '
    SET @sql = @sql + '     FROM AP_Enterprise_Stock_Valuation '
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' + '''' + @Filter + '''' + ')))'
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     UPDATE AP_Enterprise_Stock_Valuation '
    SET @sql = @sql + '     SET ' + @ColumnName + ' = ' + CONVERT(varchar(20), @Cost) + ', '
--    SET @sql = @sql + '         Total = Total + ' + CONVERT(varchar(20), @Cost)
    SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(20), @Cost)
    SET @sql = @sql + '     WHERE Product_Code = ' + '''' + @Code + ''''
    SET @sql = @sql + '       AND Pack_Size = ' + CONVERT(varchar(20), @Size)
    SET @sql = @sql + '       AND Filter = UPPER(RTRIM(LTRIM(' +  + '''' + @Filter + '''' + ')))'

    SET @sql = @sql + ' END '

    SET @sql = @sql + ' ELSE '
    SET @sql = @sql + ' BEGIN '
    SET @sql = @sql + '     INSERT AP_Enterprise_Stock_Valuation '
    SET @sql = @sql + '     ( '
    SET @sql = @sql + '         Description, '
    SET @sql = @sql + '         Product_Code, '
    SET @sql = @sql + '         Pack_Size, '
    SET @sql = @sql + '         Filter, '
    SET @sql = @sql + '         Total, '
    SET @sql = @sql +           @ColumnName + ' '
    SET @sql = @sql + '     ) '

    SET @sql = @sql + '     VALUES '
    SET @sql = @sql + '     ( '
    SET @sql = @sql +           '''' + @Description + '''' + ', '
    SET @sql = @sql +           '''' + @Code + '''' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Size) + ', '
    SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Cost) + ', '
    SET @sql = @sql +           CONVERT(varchar(20), @Cost) + ' '
    SET @sql = @sql + '     ) '
    SET @sql = @sql + ' END '


    EXEC (@sql)


SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AP_Insert_First_Product
--Purpose       :Inserts an empty Product into the Product Catalog
--Date          :2006/03/29
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Insert_First_Product
    (
        @UserID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

    INSERT AP_Products
        (
            Description,
            Product_Code,
            Default_Supplier_ID,
            [User_ID],
            AW_User_Companies_ID
        )

    VALUES
        (
            'Enter Product Description',
            'Enter Product Code',
            1,
            @UserID,
            @CompanyID
        )


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_HiQ_Price_List
--Purpose       :Replaces standard Costs/Prices with HiQ Franchise Costs/Prices
--Parameters    :
--Date          :2004/05/25
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Insert_HiQ_Price_List

AS

--SET NOCOUNT ON


----------------------------------------------------------
--> MOVE AP_Products.Price1 to AP_Products.Price2
----------------------------------------------------------
    UPDATE a
    SET a.Price2_Effective_Date = DATEADD(day, -1, a.Price1_Effective_Date),
        a.Price2_Price1 = a.Price1_Price1
    FROM AP_Products a
        INNER JOIN HIQPrices b
            ON a.Manufacturer_Code = b.Manufacturer_Code
    WHERE a.Manufacturer_Code = b.Manufacturer_Code


----------------------------------------------------------
--> MOVE HIQPrices.Price1 to AP_Products.Price1
----------------------------------------------------------
    UPDATE a
    SET a.Last_Cost = b.Last_Cost,
        a.Average_Cost = b.Average_Cost,
        a.Price1_Effective_Date = b.Price1_Effective_Date,
        a.Price1_Price1 = b.Price1_Price1
    FROM AP_Products a
        INNER JOIN HIQPrices b
            ON a.Manufacturer_Code = b.Manufacturer_Code
    WHERE a.Manufacturer_Code = b.Manufacturer_Code



--SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   : sp_AP_Insert_Markup_Groups
--Purpose       : Inserts a newly added Lup_AS_Markup_Groups record into
--              : Lup_AP_Markup_Groups
--Functionality : Tables: Lup_AP_Markup_Groups
--Parameters    : 
--Date          : 2007/07/23
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE         PROCEDURE  sp_AP_Insert_Markup_Groups
    (
        @Description varchar(50),
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    INSERT Lup_AP_Markup_Groups
        (
            [Description],
            Date_Captured,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    SELECT @Description,
           getdate(),
           @UserID,
           @CompanyID,
           1            -- Enabled

    RETURN scope_identity()

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_New_Price_Update_Product
--Purpose       :Inserts NEW AP_Products from unmatched Price Update data
--Parameters    :
--Date          :2004/04/19
--Authors       :TB
--Version       :1.0.0
--MODS          :18/06/04 - Added @LastCost input parameter
--              :05/04/05 - Added @ManufacturerID input parameter
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--V6.2 RL	2015-06-09	:Removed inserting default print description
--						 From V6.0 If Print Description is blank, normal description is used
--V6.2	RL	2015-12-02	:Insert Default Bin location for new products
--V6.2	RL	2016-06-08	:Don't create a new product if a disabled product exists
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Insert_New_Price_Update_Product]
	(
        @ProductCode varchar(20),
        @ProductDesc varchar(50),
        @Price1EffectiveDate datetime,
        @Price1 money,
        @Price2 money,
        @LastCost money,
        @ManufacturerID int,
        @UserID int
	)
AS     

SET NOCOUNT ON

	Declare @ProductID int

	IF NOT EXISTS
	(
		SELECT 1
		FROM AP_Products
		WHERE Product_Code = @ProductCode
		AND Lup_AP_Product_Manufacturers_ID = @ManufacturerID
		AND Slu_AW_Active_ID <> 1
	)
	BEGIN
		INSERT AP_Products
			(
				[Description],
				Print_Description,
				Product_Code,
				SKU_Code,
				Lup_AP_Product_Manufacturers_ID,
				Manufacturer_Code,
				Manufacturer_Description,
				Default_Supplier_ID,
				Lup_AP_Product_Types_ID,
				Lup_AP_Product_Groups_ID,
				Lup_AP_Product_Departments_ID,
				Last_Cost,
				Average_Cost,
				Price1_Effective_Date,
				Price1_Price1,
				Price1_Price2,
				[User_ID]
			)
		VALUES
			(
				LEFT(@ProductDesc, 50),
				'', --LEFT(@ProductDesc, 30), From V6.0 If Print Description is blank, normal description is used
				@ProductCode,
				@ProductCode,
				@ManufacturerID,
				@ProductCode,
				LEFT(@ProductDesc, 50),
				1,
				1,
				1,
				1,
				@LastCost,
				0,
				@Price1EffectiveDate,
				@Price1,
				@Price2,
				@UserID
			)

		SELECT @ProductID = Scope_Identity()        
		
		--V6.2 Update Bin Qty
		INSERT INTO AP_Products_Bins
		(
			AP_Products_ID, 
			Lup_AP_Product_Bins_ID, 
			On_Hand, 
			Date_Captured, 
			[User_ID], 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID
		)
		Values
		(
			@ProductID,
			1,
			0,
			GETDATE(),
			@UserID,
			1,
			1							
		)
	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :sp_AP_Insert_OR_Update_Product_Suppliers
--Purpose       :Used to link a Product to a Supplier
--Functionality :
--Parameters    :
--Date          :2002/03/22
--Authors       :TB
--Version       :1.0.0
--MODS          :06/10/02 - Added @Choice selection and new UNLINK choice
--              :04/10/03 - Added NEW Trade_Disc_Perc for Nett Billing and
--              :           NEW Inventory Manager's Discount column
--              :04/10/03 - Added NEW Trade_Disc_Date for NEW Discount above
--V6.3	RL	2017-09-07	:Update products default supplier if it currently set to ID 1 (<None>)
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_OR_Update_Product_Suppliers]
    (
    	@Choice tinyint ,
    	@Product_ID int,
    	@Supplier_ID int,
        @TradeDiscPerc decimal(5,2),
        @TradeDiscDate datetime,
    	@Lead_Time smallint ,
    	@StartDate datetime,
    	@Trade_Disc_Formula_ID smallint ,
    	@Rebate_Disc_Formula_ID smallint ,
    	@User_ID int,
        @Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @New_ID int
	SET @New_ID = 0
	
    IF @Choice = 0    --Link Supplier
        BEGIN
            IF NOT EXISTS
                (
                    SELECT AP_Products_Suppliers_ID
                    FROM AP_Products_Suppliers
                    WHERE AP_Products_ID = @Product_ID AND
                          AO_Suppliers_ID = @Supplier_ID AND
                          AW_User_Companies_ID = @Company_ID
                )
        		BEGIN 
                    INSERT INTO AP_Products_Suppliers
                        (
            				AP_Products_ID,
            				AO_Suppliers_ID,
                            Trade_Disc_Perc,
                            Trade_Disc_Date,
            				Lead_Time,
            				Start_Date,
            				AW_Trade_Discount_Formula_ID,
            				AW_Rebate_Discount_Formula_ID,
            				Date_Captured,
            				[User_ID],
            				AW_User_Companies_ID,
            				Slu_AW_Active_ID
                        )
        			VALUES
                        (
                            @Product_ID,
                            @Supplier_ID,
                            @TradeDiscPerc,
                            @TradeDiscDate,
                            @Lead_Time,
                            @StartDate,
                            @Trade_Disc_Formula_ID,
                            @Rebate_Disc_Formula_ID,
                            Getdate(),
                            @User_ID,
                            @Company_ID,
                            1
                        )
        
        			SELECT @New_ID = Scope_Identity()

					--RL V6.3 Updates Products default supplier only if it currently set to <None>. 
					--Supplier ID 1 should be <None>, if not, well ....
					
					--IF EXISTS
					--	(
					--		SELECT 1
					--		FROM AO_Suppliers nolock
					--		WHERE AO_Suppliers_ID = 1
					--		AND Supplier_Name = '<None>'
					--	)
					--BEGIN
					--	IF @Supplier_ID <> 1
					--	BEGIN
					--		IF EXISTS	(
					--						SELECT 1
					--						FROM AP_Products nolock
					--						WHERE AP_Products_ID = @Product_ID
					--						AND Default_Supplier_ID = 1
					--					)
					--		BEGIN
					--			UPDATE AP_Products
					--			SET Default_Supplier_ID = @Supplier_ID,
					--				[User_ID] = @User_ID
					--			WHERE AP_Products_ID = @Product_ID
					--		END
					--	END
					--END
        		END
            
            ELSE
        		UPDATE AP_Products_Suppliers
                SET Trade_Disc_Perc = @TradeDiscPerc,
                    Trade_Disc_Date = @TradeDiscDate,
                    Lead_Time = @Lead_Time,
                    Start_Date = @StartDate,
                    AW_Trade_Discount_Formula_ID = @Trade_Disc_Formula_ID,
                    AW_Rebate_Discount_Formula_ID = @Rebate_Disc_Formula_ID,
                    Date_Captured = Getdate(),
                    [User_ID] = @User_ID
                WHERE AP_Products_ID = @Product_ID AND
                      AO_Suppliers_ID = @Supplier_ID AND
                      AW_User_Companies_ID = @Company_ID


        END

    ELSE
    IF @Choice = 1    --Update Changes
		UPDATE AP_Products_Suppliers
        SET Trade_Disc_Perc = @TradeDiscPerc,
            Trade_Disc_Date = @TradeDiscDate,
            Lead_Time = @Lead_Time,
            Start_Date = @StartDate,
            AW_Trade_Discount_Formula_ID = @Trade_Disc_Formula_ID,
            AW_Rebate_Discount_Formula_ID = @Rebate_Disc_Formula_ID,
            Date_Captured = Getdate(),
            [User_ID] = @User_ID
        WHERE AP_Products_ID = @Product_ID AND
              AO_Suppliers_ID = @Supplier_ID AND
              AW_User_Companies_ID = @Company_ID

    ELSE
    IF @Choice = 2    --Unlink Supplier
        IF EXISTS
            (
                SELECT AP_Products_Suppliers_ID
                FROM AP_Products_Suppliers
                WHERE AP_Products_ID = @Product_ID AND
                      AO_Suppliers_ID = @Supplier_ID AND
                      AW_User_Companies_ID = @Company_ID
            )
            BEGIN
        		DELETE AP_Products_Suppliers
                WHERE AP_Products_ID = @Product_ID AND
                      AO_Suppliers_ID = @Supplier_ID AND
                      AW_User_Companies_ID = @Company_ID
            END


	RETURN @New_ID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Price_Update
--Purpose       :Updates AP_Products with Price Update data
--Parameters    :
--Date          :2003/12/31
--Authors       :TB
--Version       :1.0.0
--MODS          :18/06/04 - Added @LastCost input parameter
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_Price_Update]
	(
        @ProductID int,
        @EffectiveDate datetime,
        @Price1 money,
        @Price2 money,
        @LastCost money,
        @ChkReplaceCost int,
        @UserID		int
	)
AS     

SET NOCOUNT ON

    DECLARE @Price1EffectiveDate datetime,
            @Price1Price1 money,
            @Price1Price2 money,
            @Price2EffectiveDate datetime,
            @Price2Price1 money,
            @Price2Price2 money
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)           

    SELECT @Price1EffectiveDate = Price1_Effective_Date,
           @Price1Price1 = Price1_Price1,
           @Price1Price2 = Price1_Price2,
           @Price2EffectiveDate = Price2_Effective_Date,
           @Price2Price1 = Price2_Price1,
           @Price2Price2 = Price2_Price2,
           @Product_Code = ISNULL(Product_Code,''),
		   @Description = ISNULL([Description],'')
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID

    --> If Price1 is OLDEST price
    --IF @Price1EffectiveDate <= @Price2EffectiveDate
    --RL 2014-10-15 Added ISNULL check. Need to test
	IF @Price1EffectiveDate <= ISNULL(@Price2EffectiveDate,'1900-01-01')
        BEGIN
        	UPDATE AP_Products
            SET Price1_Effective_Date = @EffectiveDate,
                Price1_Price1 = @Price1,
                Price1_Price2 = @Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

    --> If Price2 is OLDEST price
    ELSE
    --IF @Price2EffectiveDate <= @Price1EffectiveDate
    --RL 2014-10-15 Added ISNULL check. Need to test
    IF ISNULL(@Price2EffectiveDate,'1900-01-01') <= @Price1EffectiveDate
        BEGIN
            --> Move Price1 to Price2
        	UPDATE AP_Products
            SET Price2_Effective_Date = @Price1EffectiveDate,
                Price2_Price1 = @Price1Price1,
                Price2_Price2 = @Price1Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            --> Put NEW prices into Price1
        	UPDATE AP_Products
            SET Price1_Effective_Date = @EffectiveDate,
                Price1_Price1 = @Price1,
                Price1_Price2 = @Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

    --> If Price1 = Price2 and both dates are probably NULL
    ELSE
        BEGIN
            --> Put NEW prices into Price1
        	UPDATE AP_Products
            SET Price1_Effective_Date = @EffectiveDate,
                Price1_Price1 = @Price1,
                Price1_Price2 = @Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

    --> Replace Last Cost with the Cost in list (18/06/04)
    IF @ChkReplaceCost = 1
        BEGIN
        	UPDATE AP_Products
            SET Last_Cost = @LastCost,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Product_Promotion
--Purpose       :INSERT AP_Promotion Header
--Parameters    :
--Date          :2004/02/16
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Insert_Product_Promotion
	(
        @Description varchar(50),
        @StartDate datetime,
        @EndDate datetime,
        @Active tinyint,
        @UserID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @PromotionID int

    INSERT AP_Promotions
        (
            [Description],
            Start_Date,
            End_Date,
    	    [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    VALUES
        (
            @Description,
            @StartDate,
            @EndDate,
            @UserID,
            @CompanyID,
            @Active
        )
    

	SELECT @PromotionID = Scope_Identity() 

    RETURN @PromotionID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Product_Update
--Purpose       :INSERT Product Update into target DB
--Date          :2006/06/01
--Authors       :TB
--MODS:         :
--2004.3.0      :11/07/06 - Removed RTRIM/LTRIM formatting in fetch criteria
--              :13/07/06 - Fixed assignment of @DateCaptured to Manufacturer_Code
--              :           and Manufacturer_Description in the UPDATE section
--2004.3.2      :11/09/06 - Removed update of Last_Cost and Average_Cost fields
--              :11/09/06 - Added @LocationID input parameter and update [Location] field
--              :30/09/06 - Added IF EXISTS condition to verify if this update product's
--              :           Lup_AP_Product_Manufacturers_ID = @ManufID before UPDATE
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :29/12/06 - Reworked INSERT/UPDATE section of the UPDATE PRODUCT to FIRST
--              :           fetch its Product_ID and test if it EXISTS (if value > 0)
--              :27/02/07 - Added input parameters for Lup_AP_Purchase_Categories
--2004.3.5      :26/04/07 - Modified WHERE clause in IF EXISTS @ProductID to SELECT
--              :           @ProductCode and @DateCaptured only
--              :31/05/07 - Modified WHERE clause in IF EXISTS @ProductID to STRIP
--              :           milliseconds from Date_Captured and @DateCaptured
--2004.3.8      :15/04/08 - Added Profit Protector fields [Edit Price], [Edit Disc]
--              :           [Max Disc], [Apply Max]
--              :15/04/08 - Replaced [@MaxDisc] with [@MinGP] and [@ApplyMaxID] with [@ApplyMinID]
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
--              :10/03/11 - Replaced get top 1 LookupID if Lookup does not exist
--              :           with INSERT LOOKUP if NOT EXISTS LOOKUP
--2004.5.2      :11/07/11 - Fixed @Supplier field length to new size 40 !!!!
--2004.5.3      :08/09/11 - Modified to fetch update product on code and date captured
--              :           now ONLY IF the product is ACTIVE - SHOULD PUT IN A CURSOR !!!!!!!!!
--              :20/09/11 - Modified fetch LOOKUPS to assign FIRST LOOKUP ID if @LookupDesc = BLANK
--2004.5.7 RGL	:2012-11-01 - Added Levy and Weight
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--V6.2 RL	2015-06-09	:Removed inserting default print description
--						 From V6.0 If Print Description is blank, normal description is used
--V6.2	RL	2015-12-02	:Insert Default Bin location for new products
--V6.2	RL	2016-04-08	:A new product will be created if disabled products are not checked
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_Product_Update]
	(
        @Description varchar(50), --1
        @ProductCode varchar(20), --2
        @Size decimal(9, 3), --3
        @DateCaptured datetime, --4
        @SKUCode varchar(20), --5
        @AltCode1 varchar(20), --6
        @BarCode varchar(20), --7
        @Manuf varchar(30), --8
        @ManufCode varchar(20), --9
        @ManufDesc varchar(50), --10
        @Supplier varchar(40), --11
        @Type varchar(50), --12
        @Group varchar(50), --13
        @Dept varchar(50), --14
        @Location varchar(50), --15
        @PurchaseCat varchar(50), --16
        @LastCost money, --17
        @AvgCost money, --18
        @StdCost money, --19
        @Price1Date datetime, --20
        @Price11 money, --21
        @Price12 money, --22
        @Price2Date datetime, --23
        @Price21 money, --24
        @Price22 money, --25
        @PackVolume decimal(9, 3), --26
        @PackMass decimal(9, 3), --27
        @ActiveID tinyint, --28
        @EditPriceID tinyint, --29
        @EditDiscID tinyint, --30
        @MinGP decimal(5, 2), --31
        @ApplyMinID tinyint, --32
        @chkUpdProtector tinyint, --33
                
        @Levy varchar(50), --34
        @WeightType varchar(50), --35
        @Weight decimal(9, 3), --36

        @CompanyID int, --37
        @UserID int --38
	)

AS

SET NOCOUNT ON

	DECLARE @ManufID int,
            @SupplierID int,
            @TypeID int,
            @GroupID smallint,
            @DeptID int,
            @LocationID int,
            @PurchaseCatID int,
            @RetCode int,
            @ProductID int,
            @LevyID int,
            @WeightTypeID int


    SET @RetCode = 0

	SET @Manuf = RTRIM(LTRIM(ISNULL(@Manuf,'')))
	SET @Supplier = RTRIM(LTRIM(ISNULL(@Supplier,'')))
	SET @Type = RTRIM(LTRIM(ISNULL(@Type,'')))
	SET @Group = RTRIM(LTRIM(ISNULL(@Group,'')))
	SET @Dept = RTRIM(LTRIM(ISNULL(@Dept,'')))
	SET @Location = RTRIM(LTRIM(ISNULL(@Location,'')))
	SET @PurchaseCat = RTRIM(LTRIM(ISNULL(@PurchaseCat,'')))
	SET @WeightType = RTRIM(LTRIM(ISNULL(@WeightType,'')))
	SET @Levy = RTRIM(LTRIM(ISNULL(@Levy,'')))
	Set @Description = RTRIM(LTRIM(ISNULL(@Description,'')))

	IF @Price1Date = '1900-01-01'
	BEGIN
		SET @Price1Date = NULL
	END
	
	IF @Price2Date = '1900-01-01'
	BEGIN
		SET @Price2Date = NULL
	END
	
    ---------------------------------------------------------
    --> FIND the ID of the LOOKUP if ACTIVE or INSERT NEW
    ---------------------------------------------------------
    --> Get Manufacturer ID
    SET @ManufID = NULL
    IF @Manuf = ''
        BEGIN
			SET @ManufID = 0
            SELECT TOP 1 @ManufID = Lup_AP_Product_Manufacturers_ID
            FROM Lup_AP_Product_Manufacturers
            WHERE AW_User_Companies_ID = @CompanyID AND
				LTRIM(RTRIM([Description])) = '<None>' AND
				Slu_AW_Active_ID = 1
        END
    
    IF @ManufID = 0
    BEGIN
		SET @Manuf = '<None>'
    END
    
    IF @Manuf <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Manufacturers_ID
                    FROM Lup_AP_Product_Manufacturers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Manuf AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Manufacturers (Description, AW_User_Companies_ID) VALUES (@Manuf, @CompanyID)

        			SELECT @ManufID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @ManufID = Lup_AP_Product_Manufacturers_ID
                    FROM Lup_AP_Product_Manufacturers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Manuf AND
                          Slu_AW_Active_ID = 1
                END
        END

    --> Get Supplier ID
    SET @SupplierID = NULL
    IF @Supplier = ''
        BEGIN
			SET @SupplierID = 0
            SELECT TOP 1 @SupplierID = AO_Suppliers_ID
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  LTRIM(RTRIM(Supplier_Name)) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @SupplierID = 0
    BEGIN
		SET @Supplier = '<None>'
    END
    
    IF @Supplier <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT AO_Suppliers_ID
                    FROM AO_Suppliers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          LTRIM(RTRIM(Supplier_Name)) = @Supplier AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT AO_Suppliers (Supplier_Name, AW_User_Companies_ID) VALUES (@Supplier, @CompanyID)

        			SELECT @SupplierID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @SupplierID = AO_Suppliers_ID
                    FROM AO_Suppliers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          LTRIM(RTRIM(Supplier_Name)) = @Supplier AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Product Type ID
    SET @TypeID = NULL
    IF @Type = ''
        BEGIN
			SET @TypeID = 0
            SELECT TOP 1 @TypeID = Lup_AP_Product_Types_ID
            FROM Lup_AP_Product_Types
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @TypeID = 0
    BEGIN
		SET @Type = '<None>'
    END
    
    IF @Type <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Types_ID
                    FROM Lup_AP_Product_Types
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Type AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Types (Description, AW_User_Companies_ID) VALUES (@Type, @CompanyID)

        			SELECT @TypeID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @TypeID = Lup_AP_Product_Types_ID
                    FROM Lup_AP_Product_Types
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Type AND
                          Slu_AW_Active_ID = 1
                END
        END

    --> Get Product Group ID
    SET @GroupID = NULL
    IF @Group = ''
        BEGIN
			SET @GroupID = 0
            SELECT TOP 1 @GroupID = Lup_AP_Product_Groups_ID
            FROM Lup_AP_Product_Groups
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @GroupID = 0
    BEGIN
		SET @Group = '<None>'
    END
    
    IF @Group <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Groups_ID
                    FROM Lup_AP_Product_Groups
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Group AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Groups (Description, AW_User_Companies_ID) VALUES (@Group, @CompanyID)

        			SELECT @GroupID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @GroupID = Lup_AP_Product_Groups_ID
                    FROM Lup_AP_Product_Groups
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Group AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Product Department ID
    SET @DeptID = NULL
    IF @Dept = ''
        BEGIN
			SET @DeptID = 0
            SELECT TOP 1 @DeptID = Lup_AP_Product_Departments_ID
            FROM Lup_AP_Product_Departments
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @DeptID = 0
    BEGIN
		SET @Dept = '<None>'      
    END
    
    IF @Dept <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Departments_ID
                    FROM Lup_AP_Product_Departments
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Dept AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Departments (Description, AW_User_Companies_ID) VALUES (@Dept, @CompanyID)

        			SELECT @DeptID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @DeptID = Lup_AP_Product_Departments_ID
                    FROM Lup_AP_Product_Departments
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Dept AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Product Location ID
    SET @LocationID = NULL
    IF @Location = ''
        BEGIN
			SET @LocationID = 0
            SELECT TOP 1 @LocationID = Lup_AP_Product_Locations_ID
            FROM Lup_AP_Product_Locations
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @LocationID = 0
    BEGIN
		SET @Location = '<None>'
    END
    
    IF @Location <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Locations_ID
                    FROM Lup_AP_Product_Locations
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Location AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Locations (Description, AW_User_Companies_ID) VALUES (@Location, @CompanyID)

        			SELECT @LocationID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @LocationID = Lup_AP_Product_Locations_ID
                    FROM Lup_AP_Product_Locations
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Location AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Purchase Category ID
    SET @PurchaseCatID = NULL
    IF @PurchaseCat = ''
        BEGIN
			SET @PurchaseCatID = 0
            SELECT TOP 1 @PurchaseCatID = Lup_AP_Purchase_Categories_ID
            FROM Lup_AP_Purchase_Categories
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @PurchaseCatID = 0
    BEGIN
		SET @PurchaseCat = '<None>'
    END
    
    IF @PurchaseCat <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Purchase_Categories_ID
                    FROM Lup_AP_Purchase_Categories
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @PurchaseCat AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Purchase_Categories (Description, AW_User_Companies_ID) VALUES (@PurchaseCat, @CompanyID)

        			SELECT @PurchaseCatID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @PurchaseCatID = Lup_AP_Purchase_Categories_ID
                    FROM Lup_AP_Purchase_Categories
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @PurchaseCat AND
                          Slu_AW_Active_ID = 1
                END
        END

    --> Get Levy ID
    SET @LevyID = 0
    IF @Levy <> ''
        BEGIN
            SELECT TOP 1 @LevyID = AP_Products_ID
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @CompanyID AND
    			  Slu_AW_YesNo_Levy_Item = 1 AND
    			  [Description] = @Levy
        END
    
    --> Get Weight ID
    SET @WeightTypeID = NULL
    IF @WeightType = ''
        BEGIN
			SET @WeightTypeID = 0
            SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
            FROM Lup_AP_AW_Weight
            WHERE AW_User_Companies_ID = @CompanyID AND
				  LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
        
    IF @WeightTypeID = 0
    BEGIN
		SET @WeightType = '<None>'
    END
    
    IF @WeightType <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_AW_Weight_ID
                    FROM Lup_AP_AW_Weight
                    WHERE AW_User_Companies_ID = @CompanyID AND
						  LTRIM(RTRIM([Description])) = @WeightType AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_AW_Weight (Description, AW_User_Companies_ID) VALUES (@WeightType, @CompanyID)

        			SELECT @WeightTypeID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
                    FROM Lup_AP_AW_Weight
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @WeightType AND
                          Slu_AW_Active_ID = 1
                END
        END

	--V6.3
	--Best of both worlds implemented. 
	--First check is on Product Code and Manufacturer,
	--Second. If it did not find a product useing the first check it will use the 
	--second checked based on Product Code and Date Captured. This was TB's method.
	--NB NB. Date Captured can not be used as a modified date. Second check would fail then!!!!!!!!

    ---------------------------------------------------------
    --> FIND the ID of the PRODUCT if ACTIVE or INSERT NEW
    ---------------------------------------------------------
    SET @ProductID = 0

    SELECT @ProductID = AP_Products_ID
    FROM AP_Products p
    INNER JOIN Lup_AP_Product_Manufacturers m
    On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
    WHERE Product_Code = @ProductCode
      --AND CONVERT(CHAR(19), Date_Captured) = CONVERT(CHAR(19), @DateCaptured)
      --AND m.Description = @Manuf V6.2 Product should be unique depending on Product Code and Manufacturer
      AND m.Description = @Manuf --This was commented out in V6.2 WTF!!!!
      --V6.2 RL 2016-04-08 A new product will be created if disabled products are not checked
      --AND p.Slu_AW_Active_ID = 1

    ---------------------------------------------------------

	--V6.3 RL 2017-05-16 Added this back for Mertin at tyres 2000
	IF ISNULL(@ProductID,0) = 0
	BEGIN
		SELECT @ProductID = AP_Products_ID
		FROM AP_Products
		WHERE Product_Code = @ProductCode
			AND CONVERT(CHAR(19), Date_Captured) = CONVERT(CHAR(19), @DateCaptured)
			--AND Slu_AW_Active_ID = 1
	END

    IF @ProductID IS NULL
    BEGIN
		SET @ProductID = 0
	END

    IF @chkUpdProtector = 1
        BEGIN
            IF @ProductID > 0
                BEGIN
                    UPDATE AP_Products
                    SET Description = @Description,
                        --Date_Captured = @DateCaptured, --RL V6.0
						Date_Captured = @DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
                        SKU_Code = @SKUCode,
                        Alternate_Code1 = @AltCode1,
                        Alternate_Code2 = @BarCode,
                        Lup_AP_Product_Manufacturers_ID = @ManufID,
                        Manufacturer_Code = @ManufCode,
                        Manufacturer_Description = @ManufDesc,
                        Default_Supplier_ID = @SupplierID,
                        Lup_AP_Product_Types_ID = @TypeID,
                        Lup_AP_Product_Groups_ID = @GroupID,
                        Lup_AP_Product_Departments_ID = @DeptID,
                        Lup_AP_Product_Locations_ID = @LocationID,
                        Lup_AP_Purchase_Categories_ID = @PurchaseCatID,
                        Standard_Cost = Cast(@StdCost As Money),
                        Price1_Effective_Date = @Price1Date,
                        Price1_Price1 = Cast(@Price11 As Money),
                        Price1_Price2 = Cast(@Price12 As Money),
                        Price2_Effective_Date = @Price2Date,
                        Price2_Price1 = Cast(@Price21 As Money),
                        Price2_Price2 = Cast(@Price22 As Money),
                        Pack_Volume = @PackVolume,
                        Pack_Mass = @PackMass,
                        Slu_AW_Active_ID = @ActiveID,
                        Slu_AW_YesNo_Edit_Price = @EditPriceID,
                        Slu_AW_YesNo_Edit_Discount = @EditDiscID,
                        Max_Discount_Perc = @MinGP,
                        Slu_AW_YesNo_Max_Discount_Perc = @ApplyMinID,
                        
                        Levy_AP_Product_ID = @LevyID,
                        Lup_AP_AW_Weight_ID = @WeightTypeID,
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                        
                    WHERE AP_Products_ID = @ProductID
        
                    SET @RetCode = 1
                END
            ELSE
                BEGIN
					IF ISNULL(@ProductCode,'') <> ''
					BEGIN
						INSERT AP_Products
							(
								[Description],
								Print_Description,
								Product_Code,
								Pack_Size,
								Date_Captured,
								SKU_Code,
								Alternate_Code1,
								Alternate_Code2,
								Lup_AP_Product_Manufacturers_ID,
								Manufacturer_Code,
								Manufacturer_Description,
								Default_Supplier_ID,
								Lup_AP_Product_Types_ID,
								Lup_AP_Product_Groups_ID,
								Lup_AP_Product_Departments_ID,
								Lup_AP_Product_Locations_ID,
								Lup_AP_Purchase_Categories_ID,
								Standard_Cost,
								Price1_Effective_Date,
								Price1_Price1,
								Price1_Price2,
								Price2_Effective_Date,
								Price2_Price1,
								Price2_Price2,
								Pack_Volume,
								Pack_Mass,
								Slu_AW_Active_ID,
								Slu_AW_YesNo_Edit_Price,
								Slu_AW_YesNo_Edit_Discount,
								Max_Discount_Perc,
								Slu_AW_YesNo_Max_Discount_Perc,                            
								AW_User_Companies_ID,
	                            
								Levy_AP_Product_ID,
								Lup_AP_AW_Weight_ID,
								Product_Weight,
								[User_ID]  
							)
						VALUES
							(
								@Description,
								'',--Left(@Description,30), From V6.0 If Print Description is blank, normal description is used
								@ProductCode,
								@Size,
								@DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
								--GETDATE(), --RL V6.0
								@SKUCode,
								@AltCode1,
								@BarCode,
								@ManufID,
								@ManufCode,
								@ManufDesc,
								@SupplierID,
								@TypeID,
								@GroupID,
								@DeptID,
								@LocationID,
								@PurchaseCatID,
								Cast(@StdCost As Money),
								@Price1Date,
								Cast(@Price11 As Money),
								Cast(@Price12 As Money),
								@Price2Date,
								Cast(@Price21 As Money),
								Cast(@Price22 As Money),
								@PackVolume,
								@PackMass,
								@ActiveID,
								@EditPriceID,
								@EditDiscID,
								@MinGP,
								@ApplyMinID,
								@CompanyID,
	                            
								@LevyID,
								@WeightTypeID,
								@Weight,
								@UserID                                                    
							)
	        
						SELECT @ProductID = Scope_Identity()        
						SET @RetCode = 2
						
						--V6.2 Update Bin Qty
						--Done via trigger
						--INSERT INTO AP_Products_Bins
						--(
						--	AP_Products_ID, 
						--	Lup_AP_Product_Bins_ID, 
						--	On_Hand, 
						--	Date_Captured, 
						--	[User_ID], 
						--	AW_User_Companies_ID, 
						--	Slu_AW_Active_ID
						--)
						--Values
						--(
						--	@ProductID,
						--	1,
						--	0,
						--	GETDATE(),
						--	@UserID,
						--	@CompanyID,
						--	1							
						--)
					END
                END
        END
    ELSE
        BEGIN
            IF @ProductID > 0
                BEGIN
                    UPDATE AP_Products
                    SET Description = @Description,
                        --Date_Captured = @DateCaptured, --RL V6.0
						Date_Captured = @DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
                        SKU_Code = @SKUCode,
                        Alternate_Code1 = @AltCode1,
                        Alternate_Code2 = @BarCode,
                        Lup_AP_Product_Manufacturers_ID = @ManufID,
                        Manufacturer_Code = @ManufCode,
                        Manufacturer_Description = @ManufDesc,
                        Default_Supplier_ID = @SupplierID,
                        Lup_AP_Product_Types_ID = @TypeID,
                        Lup_AP_Product_Groups_ID = @GroupID,
                        Lup_AP_Product_Departments_ID = @DeptID,
                        Lup_AP_Product_Locations_ID = @LocationID,
                        Lup_AP_Purchase_Categories_ID = @PurchaseCatID,
                        Standard_Cost = Cast(@StdCost As Money),
                        Price1_Effective_Date = @Price1Date,
                        Price1_Price1 = Cast(@Price11 As Money),
                        Price1_Price2 = Cast(@Price12 As Money),
                        Price2_Effective_Date = @Price2Date,
                        Price2_Price1 = Cast(@Price21 As Money),
                        Price2_Price2 = Cast(@Price22 As Money),
                        Pack_Volume = @PackVolume,
                        Pack_Mass = @PackMass,
                        Slu_AW_Active_ID = @ActiveID,

                        Levy_AP_Product_ID = @LevyID,
                        Lup_AP_AW_Weight_ID = @WeightTypeID,
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                                                
                    WHERE AP_Products_ID = @ProductID
        
                    SET @RetCode = 1
                END
            ELSE
                BEGIN
   					IF ISNULL(@ProductCode,'') <> ''
					BEGIN

						INSERT AP_Products
							(
								[Description],
								Print_Description,
								Product_Code,
								Pack_Size,
								Date_Captured,
								SKU_Code,
								Alternate_Code1,
								Alternate_Code2,
								Lup_AP_Product_Manufacturers_ID,
								Manufacturer_Code,
								Manufacturer_Description,
								Default_Supplier_ID,
								Lup_AP_Product_Types_ID,
								Lup_AP_Product_Groups_ID,
								Lup_AP_Product_Departments_ID,
								Lup_AP_Product_Locations_ID,
								Lup_AP_Purchase_Categories_ID,
								Standard_Cost,
								Price1_Effective_Date,
								Price1_Price1,
								Price1_Price2,
								Price2_Effective_Date,
								Price2_Price1,
								Price2_Price2,
								Pack_Volume,
								Pack_Mass,
								Slu_AW_Active_ID,
								AW_User_Companies_ID,
	                            
								Levy_AP_Product_ID,
								Lup_AP_AW_Weight_ID,
								Product_Weight,
								[User_ID]                     
							)
						VALUES
							(
								@Description,
								'',--Left(@Description,30), From V6.0 If Print Description is blank, normal description is used
								@ProductCode,
								@Size,
								@DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
								--GETDATE(), --RL V6.0
								@SKUCode,
								@AltCode1,
								@BarCode,
								@ManufID,
								@ManufCode,
								@ManufDesc,
								@SupplierID,
								@TypeID,
								@GroupID,
								@DeptID,
								@LocationID,
								@PurchaseCatID,
								Cast(@StdCost As Money),
								@Price1Date,
								Cast(@Price11 As Money),
								Cast(@Price12 As Money),
								@Price2Date,
								Cast(@Price21 As Money),
								Cast(@Price22 As Money),
								@PackVolume,
								@PackMass,
								@ActiveID,
								@CompanyID,

								@LevyID,
								@WeightTypeID,
								@Weight,
								@UserID
							)
	                        
						SELECT @ProductID = Scope_Identity()
						SET @RetCode = 2
						
						--V6.2 Update Bin Qty
						--Done via trigger
						--INSERT INTO AP_Products_Bins
						--(
						--	AP_Products_ID, 
						--	Lup_AP_Product_Bins_ID, 
						--	On_Hand, 
						--	Date_Captured, 
						--	[User_ID], 
						--	AW_User_Companies_ID, 
						--	Slu_AW_Active_ID
						--)
						--Values
						--(
						--	@ProductID,
						--	1,
						--	0,
						--	GETDATE(),
						--	@UserID,
						--	@CompanyID,
						--	1							
						--)
						
					END
                END
        END
	
	IF (@ProductID <> 0 AND @SupplierID <> 0)
	BEGIN
		IF NOT EXISTS
		(
			SELECT 1
			FROM AP_Products_Suppliers
			WHERE AP_Products_ID = @ProductID
			AND AO_Suppliers_ID = @SupplierID
		)
		BEGIN
			INSERT INTO AP_Products_Suppliers(AP_Products_ID, AO_Suppliers_ID, Start_Date, User_ID)
			VALUES(@ProductID, @SupplierID, GETDATE(), @UserID)
		END	
	END


RETURN @RetCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Promotion_Products
--Purpose       :INSERT AP_Promotion Products
--Parameters    :
--Date          :2004/02/16
--Authors       :TB
--Version       :1.0.0
--MODS          :01/03/04 - Removed Max_Per_Customer
--              :11/03/04 - Added Product Description and Code
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Insert_Promotion_Products
	(
        @PromotionID int,
        @ProductID int,
        @Product varchar(50),
        @ProductCode varchar(20),
        @StartDate datetime,
        @EndDate datetime,
        @TermsID tinyint,
        @Selling money,
        @ProjectedQty decimal(9,3),
        @CutoffQty decimal(9,3),
        @SoldQty decimal(9,3),
        @Active tinyint,
        @UserID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @PromoProductID int

    INSERT AP_Promotion_Products
        (
            AP_Promotions_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Start_Date,
            End_Date,
            Slu_AW_Credit_Terms_ID,
            Selling_Price,
            Qty_Projected_Sales,
            Qty_Cutoff,
            Qty_Sold,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    VALUES
        (
            @PromotionID,
            @ProductID,
            @Product,
            @ProductCode,
            @StartDate,
            @EndDate,
            @TermsID,
            @Selling,
            @ProjectedQty,
            @CutoffQty,
            @SoldQty,
            @UserID,
            @CompanyID,
            @Active
        )


	SELECT @PromoProductID = Scope_Identity() 

    RETURN @PromoProductID



SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Stock_Exchange
--Purpose       :INSERT AP_Stock_Exchange with Stock Exchange data
--Parameters    :
--Date          :2004/01/13
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Insert_Stock_Exchange
	(
        @RemoteID int,
        @NodeName varchar(30),
        @ProductID int,
        @ProductDescription varchar(50),
        @ProductCode varchar(20),
        @OnHand decimal(9, 3),
        @OnOrder decimal(9, 3),
        @LastCost money,
        @AverageCost money,
        @CountDate datetime,
        @UserID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    INSERT AP_Stock_Exchange
        (
            AW_Remote_Access_ID,
            NodeName,
            AP_Products_ID,
            Product_Description,
            Product_Code,
            On_Hand,
            On_Order,
            Last_Cost,
            Average_Cost,
            Count_Date,
    	    [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @RemoteID,
            @NodeName,
            @ProductID,
            @ProductDescription,
            @ProductCode,
            @OnHand,
            @OnOrder,
            @LastCost,
            @AverageCost,
            @CountDate,
            @UserID,
            @CompanyID
        )



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Stock_Transfer_Details
--Purpose       :
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2	2016-10-03	RL	:Added Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Insert_Stock_Transfer_Details]
    (
        @CustomerID int,
        @ProductID int,
        @Description varchar(50),
        @ProductCode varchar(20),
        @Quantity decimal(9, 3),
        @BackOrder decimal(9, 3),
        @OriginalPrice money,
        @UnitPrice money,
        @DiscountAmount money,
        @Amount money,
--        @Shipping money,
        @Tax_Rate decimal(9, 3),
        @TaxAmount money,
        @ExtendedAmount money,
        @UnitCost money,
--        @PromoProductID int,
--        @PromoPrice money,
		@Bin_ID Int,
        @DateCaptured datetime,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewOrderID int


    INSERT AP_Stock_Transfer_Details
        (
            AC_Customers_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Quantity,
            Back_Order,
            Original_Price,
            Unit_Price,
            Discount_Amount,
            Amount,
--            Shipping_Cost,
            Tax_Rate,
            Tax_Amount,
            Extended_Amount,
            Unit_Cost,
--            AP_Promotion_Products_ID,
--            Promo_Price,
			Lup_AP_Product_Bins_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
        )
    VALUES
        (
            @CustomerID,
            @ProductID,
            @Description,
            @ProductCode,
            @Quantity,
            @BackOrder,
            @OriginalPrice,
            @UnitPrice,
            @DiscountAmount,
            @Amount,
--            @Shipping,
            @Tax_Rate,
            @TaxAmount,
            @ExtendedAmount,
            @UnitCost,
--            @PromoProductID,
--            @PromoPrice,
			@Bin_ID,
            @DateCaptured,
            @UserID,
            @CompanyID
        )


SELECT @NewOrderID = Scope_Identity()


RETURN @NewOrderID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Last_12_Month_Sales_Qty
--Purpose       :Product Sales Qty for last 12 months from @EndDate
--Used by    `  :Order Analysis Report,
--Date          :2003/04/11
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------
--NB always use float for date conversions

CREATE           PROCEDURE sp_AP_Last_12_Month_Sales_Qty
   (
    	@ProductID int,
    	@EndDate datetime
   )

AS

SET NOCOUNT ON
    
    DECLARE @StartDate datetime,
            @StartMonthNo int,
            @EndMonthNo int

    SET @StartDate = DATEADD(yy, -1, @EndDate)

    SET @StartMonthNo = dbo.fn_AS_Get_Month_Number(@StartDate)
    SET @EndMonthNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
    SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as [DateString],
           MAX( p.AP_Products_ID ) AS [ID],
           MAX( p.[Description] ) AS [Description],
           MAX( p.Product_Code ) AS [Code],
           MAX( p.Last_Cost ) AS [LastCost],
           MAX( p.On_Hand ) AS [OnHand],
           MAX( p.Min_Stock_Level ) AS [MSL],
           MAX( p.Min_Order_Qty ) AS [MinOQ],
           MAX( p.Max_Order_Qty ) AS [MaxOQ],
--            SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
--            SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
--            SUM(d.Discount_Amount) as Discount,
--            SUM(d.Quantity * d.Unit_Cost) as Cost,
--            SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
           SUM(d.Quantity) as [Qty]
    FROM AS_Transaction_Details d
        INNER JOIN AS_Transactions h
            ON h.AS_Transactions_ID = d.AS_Transactions_ID
        INNER JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AP_Products_ID = @ProductID AND
         (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartMonthNo AND    --must be >
          dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndMonthNo) AND
         (h.Sys_AW_Transaction_Types_ID = 3 OR
          h.Sys_AW_Transaction_Types_ID = 4)
    GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
    ORDER BY DateString DESC


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



-----------------------------------------------------------------------------
--Description   :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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE Procedure sp_AP_Link_Delete_Link
   @LinkID int
AS
   DELETE FROM AP_Products_Switch3 WHERE AP_Products_Switch3_ID = @LinkID


 









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








CREATE   Procedure sp_AP_Link_Insert_Link
   @ProductID int, 
   @Switch3ID int,
   @UserID int,
   @CompanyID int

AS

DECLARE @RETURN int

   INSERT AP_Products_Switch3
        (
            AP_Products_ID,
            AP_Switch3_ID,
            User_ID,
            AW_User_Companies_ID
        )
   VALUES
        (
            @ProductID,
            @Switch3ID,
            @UserID,
            @CompanyID
        )

SELECT @Return = Scope_Identity()

RETURN @Return







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







CREATE    PROCEDURE sp_AP_Link_Products_Per_Switch_Resync
	(@ProductsSwitchID int)
AS
	SELECT  
		ps3.AP_Products_Switch3_ID as ID, 
		ps3.AP_Products_ID as ProductID,
		ps3.AP_Switch3_ID as FKID ,
		--p.AP_Products_ID as ProductsProductID,
		p.Description, 
		p.Product_Code as [Code]
	FROM AP_Products_Switch3 ps3  
		INNER JOIN AP_Products p ON ps3.AP_Products_ID = p.AP_Products_ID
	WHERE ps3.AP_Products_Switch3_ID = @ProductsSwitchID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







CREATE    PROCEDURE sp_AP_Link_Products_Per_Switch_Select
	(@Switch3ID int)
AS
	SELECT  
		ps3.AP_Products_Switch3_ID as ID, 
		ps3.AP_Products_ID as ProductID,
		ps3.AP_Switch3_ID as FKID ,
		--p.AP_Products_ID as ProductsProductID,
		p.Description, 
		p.Product_Code as [Code] 
	FROM AP_Products_Switch3  ps3 
		INNER JOIN AP_Products p ON ps3.AP_Products_ID = p.AP_Products_ID
	WHERE ps3.AP_Switch3_ID = @Switch3ID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE   PROCEDURE sp_AP_Link_Products_Unlinked_SELECT
	(
		@LookupType smallint,
		@LookupValue int,
		@F1 varchar(50) = '',
		@F2 varchar(50) = '',
		@F3 varchar(50) = ''
	)

AS
	IF @LookupType = 0    --All
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Description like '%' + @F1 + '%' OR
                      Product_Code like '%' + @F1 + '%'
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE ((Description like '%' + @F1 + '%' AND
                        Description like '%' + @F2 + '%') OR
                       (Product_Code like '%' + @F1 + '%' AND
                        Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE ((Description like '%' + @F1 + '%' AND
                        Description like '%' + @F2 + '%' AND
                        Description like '%' + @F3 + '%') OR
                       (Product_Code like '%' + @F1 + '%' AND
                        Product_Code like '%' + @F2 + '%' AND
                        Product_Code like '%' + @F3 + '%' ))
		END		
	ELSE
	IF @lookupType = 1  --Supplier
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        p.AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products p
                    JOIN AP_Products_Suppliers ps
                        ON p.AP_Products_ID = ps.AP_Products_ID
                WHERE ps.AO_Suppliers_ID = @LookupValue
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        p.AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products p
                    JOIN AP_Products_Suppliers ps
                        ON p.AP_Products_ID = ps.AP_Products_ID 
				WHERE ps.AO_Suppliers_ID = @LookupValue	AND
                     (p.Description like '%' + @F1 + '%' OR
                      p.Product_Code like '%' + @F1 + '%')
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000 p.AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products p
                    JOIN AP_Products_Suppliers ps
                        ON p.AP_Products_ID = ps.AP_Products_ID 
				WHERE ps.AO_Suppliers_ID = @LookupValue AND
                    ((p.Description like '%' + @F1 + '%' AND
                      p.Description like '%' + @F2 + '%') OR
                     (p.Product_Code like '%' + @F1 + '%' AND
                      p.Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        p.AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products p
                    JOIN AP_Products_Suppliers ps
                        ON p.AP_Products_ID = ps.AP_Products_ID 
				WHERE ps.AO_Suppliers_ID = @LookupValue AND
                    ((p.Description like '%' + @F1 + '%' AND
                      p.Description like '%' + @F2 + '%' AND
                      p.Description like '%' + @F3 + '%') OR
                      (p.Product_Code like '%' + @F1 + '%' AND
                       p.Product_Code like '%' + @F2 + '%' AND
                       p.Product_Code like '%' + @F3 + '%' ))
		END		
	ELSE
	IF @LookupType = 2  --Manufacturer
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
                WHERE Lup_AP_Product_Manufacturers_ID = @LookupValue
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Manufacturers_ID = @LookupValue AND
                     (Description like '%' + @F1 + '%' OR
                      Product_Code like '%' + @F1 + '%')
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Manufacturers_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%') OR
                     (Product_Code like '%' + @F1 + '%' AND
                      Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Manufacturers_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%' AND
                      Description like '%' + @F3 + '%') OR
                     (Product_Code like '%' + @F1 + '%' AND
                      Product_Code like '%' + @F2 + '%' AND
                      Product_Code like '%' + @F3 + '%' ))
		END		
	ELSE
	IF @LookupType = 3  --Type
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
                WHERE Lup_AP_Product_Types_ID = @LookupValue
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
				WHERE Lup_AP_Product_Types_ID  = @LookupValue AND
                    (Description like '%' + @F1 + '%' OR
                    Product_Code like '%' + @F1 + '%')
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
				WHERE Lup_AP_Product_Types_ID  = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%') OR
                     (Product_Code like '%' + @F1 + '%' AND
                      Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                 FROM AP_Products
				 WHERE Lup_AP_Product_Types_ID  = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%' AND
                      Description like '%' + @F3 + '%') OR
                      (Product_Code like '%' + @F1 + '%' AND
                       Product_Code like '%' + @F2 + '%' AND
                       Product_Code like '%' + @F3 + '%' ))
		END		
	ELSE
	IF @LookupType = 4  --Group
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
                WHERE Lup_AP_Product_Groups_ID = @LookupValue
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Groups_ID = @LookupValue AND
                    (Description like '%' + @F1 + '%' OR
                     Product_Code like '%' + @F1 + '%')
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Groups_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%') OR
                     (Product_Code like '%' + @F1 + '%' AND
                      Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Groups_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%' AND
                      Description like '%' + @F3 + '%') OR
                      (Product_Code like '%' + @F1 + '%' AND
                       Product_Code like '%' + @F2 + '%' AND
                       Product_Code like '%' + @F3 + '%' ))
		END		
	ELSE
	IF @LookupType = 5  --Department
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
                WHERE Lup_AP_Product_Departments_ID = @LookupValue
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Departments_ID = @LookupValue AND
                    (Description like '%' + @F1 + '%' OR
                     Product_Code like '%' + @F1 + '%')
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE  Lup_AP_Product_Departments_ID  = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%') OR
                      (Product_Code like '%' + @F1 + '%' AND
                       Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE  Lup_AP_Product_Departments_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%' AND
                      Description like '%' + @F3 + '%') OR
                      (Product_Code like '%' + @F1 + '%' AND
                       Product_Code like '%' + @F2 + '%' AND
                       Product_Code like '%' + @F3 + '%' ))
		END		
	ELSE
	IF @LookupType = 6 --Location
		BEGIN
			IF @F1 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products
                WHERE  Lup_AP_Product_Locations_ID = @LookupValue
			ELSE
			IF @F1 <> '' and @F2 ='' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Locations_ID = @LookupValue AND
                    (Description like '%' + @F1 + '%' OR
                     Product_Code like '%' + @F1 + '%')
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 = ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Locations_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%') OR
                     (Product_Code like '%' + @F1 + '%' AND
                      Product_Code like '%' + @F2 + '%' ))
			ELSE
			IF @F1 <> '' and @F2 <>'' and @F3 <> ''
				SELECT Top 1000
                        AP_Products_ID as ID,
                        Description,
                        Product_Code as [Code]
                FROM AP_Products 
				WHERE Lup_AP_Product_Locations_ID = @LookupValue AND
                    ((Description like '%' + @F1 + '%' AND
                      Description like '%' + @F2 + '%' AND
                      Description like '%' + @F3 + '%') OR
                      (Product_Code like '%' + @F1 + '%' AND
                       Product_Code like '%' + @F2 + '%' AND
                       Product_Code like '%' + @F3 + '%' ))
		END		
	







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE  Procedure sp_AP_Link_Select_Lookups
       @DataMember varchar(20) ,
       @CompanyID int ,
       @Filter int = 0
  
AS
SET NOCOUNT ON

    IF @DataMember = 'Switch1'
        SELECT AP_Switch1_ID as ID, Description
        FROM AP_Switch1
        WHERE AW_User_Companies_ID = @CompanyID
    ELSE
    IF @DataMember = 'Filter_Switch2'
        SELECT AP_Switch2_ID as ID, Description, AP_Switch1_ID as FKID
        FROM  AP_Switch2 
    ELSE
    IF @DataMember = 'Filter_Switch3'
        SELECT AP_Switch3_ID as ID, Description, AP_Switch2_ID as FKID
        FROM AP_Switch3

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Link_Select_Product_Search_Lups
--Purpose       :Returns a rs for the specified LUP 
--Functionality :
--Parameters    :	
--Date          :2002/02/14
--Authors       :TB
--Version       :1.0.0
--MODS:         :14/04/04 - Added ORDER BY in Option 1 and 2
--2004.3.2      :30/09/06 - Added GL Accounts in Option 9 for Product Updates
--2004.4.1      :29/09/08 - Added Purchase Category
--V6.2	RL	2015-11-16	:Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Link_Select_Product_Search_Lups]
    (
    	@Option int
    )

AS

SET NOCOUNT ON

    --> Supplier
    	IF @Option = 1
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name as [Description]
    		FROM AO_Suppliers
            ORDER BY Supplier_Name
    
    --> Manufacturer
    	ELSE 
    	IF @Option = 2
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Manufacturers
            ORDER BY [Description]
    
    --> Type
    	ELSE 
    	IF @Option = 3
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Types
    
    --> Group
    	ELSE 
    	IF @Option = 4
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Groups	
    
    --> Department
    	ELSE 
    	IF @Option = 5
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Product_Departments
    
    --> Location
    	ELSE 
    	IF @Option = 6
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Locations

    --> Active
    	ELSE 
    	IF @Option = 7
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_Active

    --> Model Types
    	ELSE 
    	IF @Option = 8
    		SELECT Lup_AP_Switch2_Types_ID AS [ID],
    		   [Description] 
    		FROM Lup_AP_Switch2_Types

    --> GL Accounts
        ELSE 
    	IF @Option = 9
        	SELECT AB_Accounts_ID AS [ID], 
               [Description]
        	FROM AB_Accounts 
        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Purchase Categories
    	ELSE 
    	IF @Option = 10
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Purchase_Categories
            ORDER BY [Description]

    --> From Bins
    	ELSE 
    	IF @Option = 11
    		SELECT Lup_AP_Product_Bins_ID AS [ID], 
    			[Description] AS [From Bin]
    		FROM Lup_AP_Product_Bins
            ORDER BY [Description]
    --> To Bins
    	ELSE 
    	IF @Option = 12
    		SELECT Lup_AP_Product_Bins_ID AS [ID], 
    			[Description] AS [To Bin] 
    		FROM Lup_AP_Product_Bins
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 13
    		SELECT Lup_AP_Product_Bins_ID AS [ID], 
    			[Description] AS [Description] 
    		FROM Lup_AP_Product_Bins
            ORDER BY [Description]            

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE   PROCEDURE sp_AP_Link_Select_Switches
    @Choice tinyint

AS

    IF @Choice = 1
       SELECT 
          AP_Switch1_ID as ID, 
          Description,
          [User_ID] as UserID, 
          AW_User_Companies_ID as CompanyID, 
          Slu_AW_Active_ID as Active 
       FROM AP_Switch1

    IF @Choice = 2
       SELECT 
          AP_Switch2_ID as ID, 
          Description, 
          AP_Switch1_ID as Make, 
          Lup_AP_Switch2_Types_ID as Type, 
          Rim_Front as [Front Rim], 
          Rim_Rear as [Rear Rim], 
          Tyre_Front as [Front Tyre], 
          Tyre_Rear as [Rear Tyre], 
          Front_Susp1 as [Front Susp1], 
          Front_Susp2 as [Front Susp2], 
          Rear_Susp1 as [Rear Susp1], 
          Rear_Susp2 as [Rear Sup2], 
          [User_ID] as UserID,  
          AW_User_Companies_ID as CompanyID, 
          Slu_AW_Active_ID as Active 
       FROM AP_Switch2

    IF @Choice = 3
       SELECT 
          AP_Switch3_ID as ID, 
          Description, 
          From_Year as [From], 
          To_Year as [To], 
          AP_Switch2_ID as Model, 
          [User_ID] as UserID, 
          AW_User_Companies_ID as CompanyID, 
          Slu_AW_Active_ID as Active
       FROM AP_Switch3









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


--------------------------------------------------------------------------------
--Description   :sp_AP_Post_Stock_Take_Adjustments
--Purpose       :Inserts Stock Adjustments from Stock Take Procedure
--              :    1. Normal Inventory/Cost-of-Sales Control or
--              :    2. Split Inventory/Adjustment Control by PRODUCT TYPE
--              :
--Functionality :Uses CURSOR. Only Qty Stock Adjustments (Type 1)
--              :Can be used to ZERO all stock if Total Count = 0
--              :Uses TRANSACTION ISOLATION LEVEL SERIALIZABLE
--Date          :2009/02/22
--Authors       :TB
--Mods          :
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Post_Stock_Take_Adjustments]
    (
    	@StockTakeProcedureID int,
        @SplitGRVGL tinyint,
        @SplitADJGL tinyint,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @StockTakeID int,
            @ProductID int,
            @UnitCost money,
            @OnHand decimal(9,3),
            @Variance decimal(9,3),
            @ProductCode varchar(20),
    		@UserFirstName varchar(40),
            @AdjustmentTypeID tinyint,
            @AdjustValue money,
            @AdjustTotal money,
            @Narration varchar(50),
            @NextGLTranID int,
            @JNLHeaderID int,
            @InsertGLTran bit,
            @AdjustDate datetime,
            @GLInventoryControlID int,
            @GLCOSControlID int,
    	    @Note varchar(70),
            @Prev_On_Hand decimal(9,3),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
            @New_On_Hand decimal(9,3),
            @New_Last_Cost money,
            @New_Average_Cost money,
            @ProcedureDate varchar(30),

            @TypeDescription varchar(50),
            @TypeTotal money,
            @SplitGRVparameter varchar(10),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ReturnValue int,
            @ProductBinID	int


    --> Get the User Name
	SELECT @UserFirstName = LEFT(ISNULL(FirstName, ''), 20)
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --> Get the Stock Take Procedure details
	SELECT @ProcedureDate = CONVERT(varchar(30), Procedure_Date, 120)
	FROM AP_Stock_Take_Procedures
	WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID


    SET @ProcedureDate = LEFT(@ProcedureDate, 20)


    --> Get INVENTORY CONTROL
    SELECT @GLInventoryControlID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 601    --Inventory Control


    --> Get INVENTORY ADJUSTMENTS CONTROL
	SELECT @GLCOSControlID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 107    --Inventory Adjustments Control


    --> Initialize vars
    SET @ReturnValue = 0
    SET @AdjustmentTypeID = 1            --Intialize as 'Qty Adjustment' type
    SET @Narration = LEFT(('Stock Take ' + @ProcedureDate + ' Adjust by ' + @UserFirstName), 50) 
	SET @Note = LEFT(('Stock Take ' + @ProcedureDate + ' Adjust by ' + @UserFirstName), 70) 
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = DO NOT insert a GL Transaction in JNL Details
    SET @AdjustTotal = 0
    SET @AdjustDate = getdate()


    BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
        BEGIN TRANSACTION

        ------------------------------------------------------------
        --> INSERT Stock Adjustment in AP_Inventory_Adjustments
        ------------------------------------------------------------
    	DECLARE Adjustment_Cursor CURSOR FOR
            (
                SELECT AP_Products_Stock_Takes_ID,
                       AP_Products_ID,
                       ISNULL(Unit_Cost, 0),
                       ISNULL(On_Hand, 0),
                       ISNULL(Variance, 0),
                       ROUND(ISNULL(Unit_Cost, 0) * ISNULL(Variance, 0), 2),
                       ISNULL(Lup_AP_Product_Bins_ID,1)
                FROM AP_Products_Stock_Takes
                WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
                      ISNULL(Variance, 0) <> 0
            )

    	OPEN Adjustment_Cursor

        	FETCH NEXT FROM Adjustment_Cursor 
        	INTO
                @StockTakeID,
                @ProductID,
                @UnitCost,
                @OnHand,
                @Variance,
                @AdjustValue,
                @ProductBinID

        	WHILE @@FETCH_STATUS = 0
        	BEGIN

                --> @AdjustValue = NEGATIVE if @Variance NEGATIVE (Stock Loss)
                SET @AdjustTotal = @AdjustTotal + @AdjustValue

                --> Get PREV (In case it changed since Stock Take Procedure)
            	SELECT @Prev_On_Hand = ISNULL(On_Hand, 0),
                       @Prev_Last_Cost = ISNULL(Last_Cost, 0),
                       @Prev_Average_Cost = ISNULL(Average_Cost, 0),
                       @ProductCode = ISNULL(Product_Code, '')
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID

                --> Set NEW
                SET @New_On_Hand = @Prev_On_Hand + @Variance
                SET @New_Last_Cost = @Prev_Last_Cost
                SET @New_Average_Cost = @Prev_Average_Cost

                --> Adjust CURRENT On_Hand with COUNT VARIANCE AND COST
                --  because THAT WAS THE ACTUAL COST when the Stock Take WAS MADE !!
            	UPDATE AP_Products
                SET On_Hand = @New_On_Hand,
                [User_ID] = @UserID
            	WHERE AP_Products_ID = @ProductID

				--Update Bin Qty
				IF @Variance <> 0
				BEGIN
					EXEC sp_AP_Products_Bins_Update_Insert 
						@ProductID,		--@ProductID int,
						@ProductBinID,	--@ProductBinID int,
    					@Variance,		--@Qty decimal(9,3)
    					'STOCK TAKE',	--@Source varchar(10),
    					0,				--@Batch_No
    					@UserID,		--@UserID int,
    					@CompanyID		--@CompanyID int
				END	

                ------------------------------------------------------------
                --> INSERT Stock Adjustment table
                ------------------------------------------------------------
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID,
            			Lup_AP_Product_Bins_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentTypeID,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    0,
            			0,
            		    0,
            			@New_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			0 ,
            			0,
            			0,
            			@Note,
            			@AdjustDate,
            			@UserID,
            			@CompanyID,
            			@ProductBinID
                    )
                ------------------------------------------------------------

            	FETCH NEXT FROM Adjustment_Cursor 
            	INTO
                    @StockTakeID,
                    @ProductID,
                    @UnitCost,
                    @OnHand,
                    @Variance,
                    @AdjustValue,
                    @ProductBinID

        	END

    	CLOSE Adjustment_Cursor

    	DEALLOCATE Adjustment_Cursor


------------------------------------------------------------
--> INSERT Split GL per PRODUCT TYPE Journal here
------------------------------------------------------------


        IF @SplitGRVGL = 1 OR @SplitADJGL = 1
            BEGIN
                ------------------------------------------------------------
                --> INSERT Stock Adjustment in AP_Inventory_Adjustments
                ------------------------------------------------------------
            	DECLARE Type_Cursor CURSOR FOR
                    (
                        SELECT ISNULL(t.Description, ''),
                               SUM(ROUND(ISNULL(st.Unit_Cost, 0) * ISNULL(st.Variance, 0), 2))
                        FROM AP_Products_Stock_Takes st
                            INNER JOIN AP_Products p
                                ON st.AP_Products_ID = p.AP_Products_ID
                            INNER JOIN Lup_AP_Product_Types t
                                ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID
                        WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
                              ISNULL(Variance, 0) <> 0
                        GROUP BY t.Description
                    )

            	OPEN Type_Cursor

                	FETCH NEXT FROM Type_Cursor 
                	INTO
                        @TypeDescription,
                        @TypeTotal


                	WHILE @@FETCH_STATUS = 0
                	BEGIN

                        IF LTRIM(RTRIM(@TypeDescription)) = ''
                            BEGIN
                                SET @TypeDescription = '<None>'
                            END

                        SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
                        SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)


                        ------------------------------------------------------------------------------
                        --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
                        ------------------------------------------------------------------------------
                        IF @TypeTotal <> 0
                            BEGIN
                                IF @SplitADJGL = 1
                                    BEGIN
                                        ---------------------------------------------------------------------
                                        --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                                        ---------------------------------------------------------------------
                                        SET @GLAdjustID = 0

                                        SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                                        FROM AB_Accounts
                                        WHERE AW_User_Companies_ID = @CompanyID AND
                                             [Description] = @AdjustGLDescription AND
                                              Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                                              Slu_AW_Active_ID = 1


--                                        IF @GLAdjustID IS NULL OR @GLAdjustID = 0
                                        IF @GLAdjustID = 0
                                            BEGIN
                                 				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                                        @AdjustGLDescription,
                                                                        14,
                                                                        @UserID,
                                                                        @CompanyID
                                            END
                                    END

                                ---------------------------------------------------------------------
                                --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                                ---------------------------------------------------------------------
                                IF @SplitGRVGL = 1
                                    BEGIN
                                        ---------------------------------------------------------------------
                                        --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                                        ---------------------------------------------------------------------
                                        SET @GLInventoryID = 0

                                        SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                                        FROM AB_Accounts
                                        WHERE AW_User_Companies_ID = @CompanyID AND
                                             [Description] = @InventoryGLDescription AND
                                              Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                              Slu_AW_Active_ID = 1


--                                        IF @GLInventoryID IS NULL OR @GLInventoryID  = 0
                                        IF @GLInventoryID  = 0
                                            BEGIN
                                 				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                                        @InventoryGLDescription,
                                                                        7,
                                                                        @UserID,
                                                                        @CompanyID
                                            END
                                        ---------------------------------------------------------------------
                                    END
                                ---------------------------------------------------------------------

                                ---------------------------------------------------------------------
                                --> Create JOURNAL HEADER for ADJUSTMENT Product Type
                                ---------------------------------------------------------------------
                                IF @NextGLTranID = 0
                                    BEGIN
                         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                                15,
                                                @CompanyID
            
                        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                                @AdjustDate,
                                                @NextGLTranID,
                                                @Narration,
                                                @Month,
                                                @Year,
                                                @UserID,
                                                @CompanyID
                                    END
                                ---------------------------------------------------------------------

                                IF @SplitGRVGL = 1
                                    BEGIN
                                        --> Create JOURNAL DETAIL for Inventory Control
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLInventoryID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran


                                        --> Create GL TRANSACTION for SPLIT GL Inventory Account
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLInventoryID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END
                                ELSE
                                    BEGIN
                                        --> Create JOURNAL DETAIL for Inventory Control 601
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLInventoryControlID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran

                                        --> Create GL TRANSACTION for Inventory Control 601
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLInventoryControlID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END


                                --> Reverse signs to balance double entry
                                SET @TypeTotal = @TypeTotal * -1


                                IF @SplitADJGL = 1
                                    BEGIN
                                        --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLAdjustID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran

                                        --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLAdjustID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END
                                ELSE
                                    BEGIN
                                        --> Create JOURNAL DETAIL for Cost-of-Sales 106
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLCOSControlID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran

                                        --> Create GL TRANSACTION for Cost-of-Sales 106
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLCOSControlID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END

                            END    --IF @TypeTotal <> 0
                        ------------------------------------------------------------

                    	FETCH NEXT FROM Type_Cursor 
                    	INTO
                            @TypeDescription,
                            @TypeTotal

                	END

            	CLOSE Type_Cursor

            	DEALLOCATE Type_Cursor

            END    --IF @SplitGRVGL = 1 OR @SplitADJGL = 1


------------------------------------------------------------
--> INSERT Non-Split GL Single Journal here
------------------------------------------------------------

            ELSE
                BEGIN
                    ------------------------------------------------------------
                    --> INSERT GL - Create NORMAL JOURNAL header for Cost Of Sales
                    ------------------------------------------------------------
                    IF @NextGLTranID = 0
                        BEGIN
                            EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

                			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    --> Create JOURNAL DETAIL for Inventory Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLInventoryControlID,
                            @AdjustTotal,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Inventory Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLInventoryControlID,
                            @AdjustDate,
                            @ProcedureDate,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @AdjustTotal,
                            @UserID,
                            @CompanyID


                    --> Reverse signs to balance double entry to COST OF SALES
                    SET @AdjustTotal = @AdjustTotal * -1


                    --> Create JOURNAL DETAIL for Cost Of Sales Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLCOSControlID,
                            @AdjustTotal,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Cost Of Sales Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLCOSControlID,
                            @AdjustDate,
                            @ProcedureDate,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @AdjustTotal,
                            @UserID,
                            @CompanyID

                END
    
------------------------------------------------------------
--> UPDATE Stock Take Procedure
------------------------------------------------------------
    	UPDATE AP_Stock_Take_Procedures
        SET Slu_AW_Months_ID = @Month,
            Slu_AW_Years_ID = @Year,
            AB_Journals_ID = @JNLHeaderID,
            Stock_Adjustment_Total = @AdjustTotal
    	WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID
------------------------------------------------------------

	    COMMIT TRANSACTION

        SET @ReturnValue = 1

    END



RETURN @ReturnValue


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


--------------------------------------------------------------------------------
--Description   :sp_AP_Post_Stock_Take_Adjustments_CHK
--Purpose       :Checks if stock take will push stock on hand into a negative
--				:if consignment stock exists against that product
--Date          :2016/05/10
--Authors       :RL
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Post_Stock_Take_Adjustments_CHK]
    (    
    	@StockTakeProcedureID	int,
    	@Message				Varchar(5000) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @StockTakeICHK Table

    (
		ProductID	int,
		OnHand		decimal(9,3),
		Variance	decimal(9,3),
		Consignment decimal(9,3)
     )
     
     DECLARE @Temp			Varchar(100),
			 @TotalVariance	decimal(9,3)

	SET @Message = ''

	INSERT INTO @StockTakeICHK(ProductID)
	SELECT DISTINCT AP_Products_ID
	FROM AP_Products_Stock_Takes
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
    ISNULL(Variance, 0) <> 0 
    
--Select * From @StockTakeICHK

	UPDATE @StockTakeICHK
	SET OnHand = p.On_Hand
	FROM @StockTakeICHK t
		INNER JOIN AP_Products p
			ON t.ProductID = p.AP_Products_ID
			
--Select * From @StockTakeICHK	

	UPDATE @StockTakeICHK
	SET Consignment = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(ProductID),0)	
	
--Select * From @StockTakeICHK

	--SELECT ProductID, SUM(ISNULL(Variance, 0)) AS [TotalVariance]
	--FROM @StockTakeICHK
	--GROUP BY ProductID

	UPDATE @StockTakeICHK
	SET Variance = t.TotalVariance
	FROM @StockTakeICHK s
		INNER JOIN (SELECT AP_Products_ID, SUM(ISNULL(Variance, 0)) AS [TotalVariance]
					FROM AP_Products_Stock_Takes
					WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID
					AND ISNULL(Variance, 0) <> 0 
					GROUP BY AP_Products_ID) t
			ON s.ProductID = t.AP_Products_ID
			
--Select * From @StockTakeICHK

	--UPDATE @StockTakeICHK
	--SET Variance = SELECT SUM(ISNULL(p.Variance, 0)) FROM 
	--FROM @StockTakeICHK t
	--	INNER JOIN AP_Products_Stock_Takes p
	--		ON t.ProductID = p.AP_Products_ID

	IF EXISTS
	(
		SELECT 1
		FROM @StockTakeICHK
		WHERE Consignment > 0
		AND (OnHand + Variance) < Consignment
	)
	BEGIN
		
		DECLARE GetData CURSOR
		FOR
		SELECT ISNULL(p.Product_Code,'') + ' - ' + ISNULL(Description,'')
		FROM AP_Products p
			INNER JOIN @StockTakeICHK t
				ON p.AP_Products_ID = t.ProductID
		WHERE t.Consignment > 0
		AND (t.OnHand + t.Variance) < t.Consignment
		
		OPEN GetData
		
		FETCH NEXT FROM GetData INTO @Temp
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @Message = ''
				SET @Message = @Temp
			Else
				SET @Message = @Message + '
' + @Temp
		
			FETCH NEXT FROM GetData INTO @Temp
		END	
		CLOSE GetData
		DEALLOCATE GetData
	END

	SELECT @Message AS [Message]


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Product_Bin_Select
--Purpose       :Returns details for a specific product and bin
--Functionality :
--Parameters    :	
--Date          :2016/04/28
--Authors       :RL
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Product_Bin_Select]
    (
    	@AP_Products_ID int,
    	@BinID			int,
    	@CompanyID		int
    )

AS

SET NOCOUNT ON
		SELECT  l.Lup_AP_Product_Bins_ID,
				l.[Description],
				ISNULL(l.Email,'') As [Email],
				b.On_Hand
		FROM Lup_AP_Product_Bins l
			Inner Join AP_Products_Bins b
				On l.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		WHERE b.AP_Products_ID = @AP_Products_ID
		AND	b.Lup_AP_Product_Bins_ID = @BinID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :144 sp_AP_Product_Bins_Multi_CHK
--Purpose       :Checks if products exist in other bins
--Date          :2016-05-09
--Authors       :RL
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Product_Bins_Multi_CHK]
    (
    	@ProductID				int,
        @ProductBinID			int,
    	@CompanyID				int,
    	@OtherBinQty			decimal(9,3) OUTPUT,
    	@ConsignmentStockQty	decimal(9,3) OUTPUT
    )

AS

SET NOCOUNT ON

	SELECT @ConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
	
	SELECT @OtherBinQty = ISNULL(SUM(On_Hand),0)
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND AW_User_Companies_ID = @CompanyID
	AND Lup_AP_Product_Bins_ID <> @ProductBinID
    
    SELECT @OtherBinQty, @ConsignmentStockQty
    
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Bins_Switch
--Purpose       :Switch Product Bins on or off.
--				 If Products Bins are switched off, then move all products to the default Bins
--Date          :2016-05-02
--Version		:V6.2
--Authors       :RL
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AP_Product_Bins_Switch]
    (
    	@Switch					int,	--0	OFF, 1 ON
    	@UserID					int,
		@CompanyID				int
    )

AS

SET NOCOUNT ON

    DECLARE @From_Qty						decimal(9,3),
			@From_AP_Products_Bins_ID		int,
			@From_Lup_AP_Product_Bins_ID	int,
			
			@To_Lup_AP_Product_Bins_ID		int,			
			@To_Bin_Previous_On_Hand		decimal(9,3),
			@To_AP_Products_Bins_ID			int,
			
			@Previous_Bin_Switch			int,
			@AP_Products_ID					int
			
			
	SET @Previous_Bin_Switch = 1
		
	SELECT @Previous_Bin_Switch = Control_Value
	FROM Sys_AW_Options
	Where Control_Name = 'chkEnableProductBins'
	AND Control_Index = 0

	IF ( (@Previous_Bin_Switch = 1) AND (@Switch = 0) )
	BEGIN
		
		DECLARE GetData CURSOR
		FOR
		SELECT  AP_Products_Bins_ID,
				AP_Products_ID,
				Lup_AP_Product_Bins_ID,
				On_Hand
		FROM AP_Products_Bins
		WHERE Lup_AP_Product_Bins_ID <> 1
		AND On_Hand <> 0
		
		OPEN GetData
		FETCH NEXT FROM GetData INTO @From_AP_Products_Bins_ID, @AP_Products_ID, @From_Lup_AP_Product_Bins_ID, @From_Qty
		WHILE @@FETCH_STATUS = 0
		BEGIN

			SET @To_Bin_Previous_On_Hand = 0
			SET @To_AP_Products_Bins_ID = 0
			SET @To_Lup_AP_Product_Bins_ID = 1

			IF EXISTS
			(
				SELECT 1
				FROM AP_Products_Bins
				WHERE AP_Products_ID = @AP_Products_ID
    			AND Lup_AP_Product_Bins_ID = 1	
			)
			BEGIN
				SELECT	@To_Bin_Previous_On_Hand = On_Hand,
						@To_AP_Products_Bins_ID = AP_Products_Bins_ID
				FROM AP_Products_Bins
				WHERE AP_Products_ID = @AP_Products_ID
    			AND Lup_AP_Product_Bins_ID = 1	
			
				--From Bin
				UPDATE AP_Products_Bins
				SET On_Hand = 0
				WHERE AP_Products_Bins_ID = @From_AP_Products_Bins_ID
				
				--To Bin
				UPDATE AP_Products_Bins
				SET On_Hand = On_Hand + @From_Qty
				WHERE AP_Products_Bins_ID = @To_AP_Products_Bins_ID			
			END
			ELSE
			BEGIN
				INSERT INTO AP_Products_Bins
				(
					AP_Products_ID, 
					Lup_AP_Product_Bins_ID, 
					On_Hand, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID
				)
				VALUES
				(
					@AP_Products_ID,
					1,
					@From_Qty,
					GETDATE(),
					@UserID,
					@CompanyID,
					1
				)	
				
				--From Bin
				UPDATE AP_Products_Bins
				SET On_Hand = 0
				WHERE AP_Products_Bins_ID = @From_AP_Products_Bins_ID
				
				--To Bin
				SET @To_Bin_Previous_On_Hand = 0
			END				
			
			INSERT INTO AP_Products_Bins_History
			(
				Batch_No, 
				AP_Products_ID, 
				From_Lup_AP_Product_Bins_ID, 
				From_Bin_Previous_On_Hand, 
				From_Bin_New_On_Hand, 
				To_Lup_AP_Product_Bins_ID, 
				To_Bin_Previous_On_Hand, 
				To_Bin_New_On_Hand, 
				Movement_Source, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID		
			)
			VALUES
			(
				'0',									--Batch_No, 
				@AP_Products_ID, 
				@From_Lup_AP_Product_Bins_ID, 
				@From_Qty,								--From_Bin_Previous_On_Hand
				0,										--From_Bin_New_On_Hand
				
				1,										--To_Lup_AP_Product_Bins_ID
				@To_Bin_Previous_On_Hand,				--To_Bin_Previous_On_Hand
				@To_Bin_Previous_On_Hand + @From_Qty,	--To_Bin_New_On_Hand
				
				'SYS Option',							--Movement_Source
				GETDATE(), 
				@UserID, 
				@CompanyID, 
				1
			)			
			
			FETCH NEXT FROM GetData INTO @From_AP_Products_Bins_ID, @AP_Products_ID, @From_Lup_AP_Product_Bins_ID, @From_Qty	
		END
		CLOSE GetData
		DEALLOCATE GetData
	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




---------------------------------------------------------------------------------
--Description   :sp_AP_Product_Filter_Lups
--Purpose       :Returns LUPS for Product Filters
--Functionality :
--Date          :2005/04/27
--Authors       :TB
--MODS          :21/10/05 - Added Options 8 = Location, 9 = Added Barcode Types
--2004.3.4      :27/03/07 - Added Added Options 10 = Purchase
--2004.5.7 RGL  :2012-10-20 - Added Product Levy 11
--2004.5.8 RGL  :2013-02-20 - Added <None> as Levy LU
---------------------------------------------------------------------------------
CREATE Procedure [dbo].[sp_AP_Product_Filter_Lups]
    (
    	@Option int,
    	@Company_ID int
    )
AS

SET NOCOUNT ON

        IF @Option = 1    --> Type
        	SELECT Lup_AP_Product_Types_ID AS [ID],
        		  [Description] AS [Type] 
        	FROM Lup_AP_Product_Types
        	WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC
        
        ELSE
        IF @Option = 2    --> Group
        	SELECT Lup_AP_Product_Groups_ID AS [ID],
        		  [Description] AS [Group] 
        	FROM Lup_AP_Product_Groups	
        	WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC
        
        ELSE
        IF @Option = 3    --> Department
        	SELECT Lup_AP_Product_Departments_ID AS [ID], 
        		  [Description] AS [Department] 
        	FROM Lup_AP_Product_Departments
        	WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC
        
        ELSE
        IF @Option = 4    --> Suppliers
        	SELECT AO_Suppliers_ID AS [ID],
        		   Supplier_Name AS [Supplier] 
        	FROM AO_Suppliers
        	WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY Supplier_Name ASC
        
        ELSE
        IF @Option = 5    --> Manufacturer
        	SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
        		  [Description] AS [Manufacturer] 
        	FROM Lup_AP_Product_Manufacturers
        	WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC
        
        ELSE
        IF @Option = 6    --> Active
        	SELECT Slu_AW_Active_ID AS [ID],
        		[Description] AS [Active]
        	FROM Slu_AW_Active
        
        ELSE
        IF @Option = 7    --> Yes No
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description] AS [YesNo]
            FROM Slu_AW_YesNo

    	ELSE 
    	IF @Option = 8    --> Location
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			[Description] AS [Location]
    		FROM Lup_AP_Product_Locations
            WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC

    	ELSE 
    	IF @Option = 9    --> Barcode Types
    		SELECT Sys_AW_Barcode_Types_ID AS [ID],
    		   [Type] AS [Barcode],
               [Value_ID],
               [Mnemonic],
               [Description]
    		FROM Sys_AW_Barcode_Types

    	ELSE 
    	IF @Option = 10    --> Purchase Category
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID],
    			[Description] AS [Purchase]
    		FROM Lup_AP_Purchase_Categories
            WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC
        ELSE    
    	IF @Option = 11    --> Levy   
    	    SELECT 0 AS [ID],
    		      '<None>' As [Levy]
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @Company_ID AND
    		   Slu_AW_YesNo_Levy_Item = 1            
            UNION        
            SELECT AP_Products_ID AS [ID],
    		      [Description] As [Levy]
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @Company_ID AND
    		   Slu_AW_YesNo_Levy_Item = 1
            ORDER BY 2 ASC

SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AP_Product_Inventory_Details
--Purpose       :Returns selected fields from Products for Stock Adjestments 
--Functionality :
--Parameters    :	
--Date          :2002/04/09
--Authors       :TB
--Version       :1.0.0
--MODS          :31/05/03 - Added NEW Average_Cost field
--V6.0	RL		:2014-10-28 - Reworked Job, Quote And Sales Order Reserved
--V6.2 RL	2015-11-29	:Added Product Bins
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Product_Inventory_Details]
    (
    	@ProductID int,
    	@ProductBinID int
    )
AS

SET NOCOUNT ON

    SELECT
        p.AP_Products_ID AS [ID],
        p.[Description] AS [Description],
        p.Last_Cost AS [Last Cost],
        p.Average_Cost AS [Ave Cost],
        p.On_Hand AS [Total On Hand],
        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Consignment Stock],
        b.On_Hand AS [On Hand],
        b.Lup_AP_Product_Bins_ID AS [BinID],
        pb.[Description] AS [Bin],
        --Job_Reserved AS [Job Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Reserved], 
        --Sales_Order_Reserved AS [S/O Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Reserved], 
        --Quote_Reserved AS [Quote Reserved]
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Reserved]
    FROM AP_Products p
		LEFT OUTER JOIN AP_Products_Bins b
			ON p.AP_Products_ID = b.AP_Products_ID
		Left Outer Join Lup_AP_Product_Bins pb
			ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID	
    WHERE p.AP_Products_ID = @ProductID
    AND b.Lup_AP_Product_Bins_ID = @ProductBinID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AP_Product_Promotion_Lups
--Purpose       :Returns LUPS for Product Promotions
--Functionality :
--Date          :2004/02/16
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE            Procedure sp_AP_Product_Promotion_Lups
    (
    	@Option int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON


    	IF @Option = 1    --> Active
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] AS [Active]
    		FROM Slu_AW_Active

        ELSE
        IF @Option = 2    --> Yes No
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description] AS [YesNo]
            FROM Slu_AW_YesNo

        ELSE
        IF @Option = 3    --> Credit Terms
          	SELECT Slu_AW_Credit_Terms_ID AS [ID],
                [Description] AS [Terms]
            FROM Slu_AW_Credit_Terms
            WHERE Slu_AW_Credit_Terms_ID > 1    --To ALWAYS incude <None>

        ELSE
    	IF @Option = 4    --> Supplier
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name ASC
    	ELSE 
    	IF @Option = 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]
    	ELSE 
    	IF @Option = 6    --> Type
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			  [Description] AS [Type] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 7    --> Group
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			  [Description] AS [Group] 
    		FROM Lup_AP_Product_Groups	
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 8    --> Department
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			  [Description] AS [Department] 
    		FROM Lup_AP_Product_Departments
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 9    --> Location
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			  [Description] AS [Location] 
    		FROM Lup_AP_Product_Locations
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 10    --> Users
          	SELECT AW_Users_ID as [ID],
                   ISNULL(FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
            FROM AW_Users 
            ORDER BY [User]
        ELSE
    	IF @Option = 11    --> ALL Suppliers
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY Supplier_Name ASC

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Product_Tax_Rate
--Purpose       :Gets Product Tax Rate
--Date          :2018-03-28
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AP_Product_Tax_Rate]
    (    	    	
    	@Products_ID	int,
    	@Tax_Rate		Decimal(5,2) Output
    )
AS 

	SELECT @Tax_Rate = tc.Tax_Rate
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
			ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
	WHERE AP_Products_ID = @Products_ID
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Audit_Select
--Purpose       :Return Audit Data on AP_Products
--Date          :2013/10/30
--Authors       :RL
-------------------------------------------------------------------------------
--16923
--986
-- Exec sp_AP_Products_Audit_Select '2013-10-14', '2013-10-29', 0
-- Exec sp_AP_Products_Audit_Select NULL, NULL, NULL
-- AA3_Silverlakes
CREATE PROCEDURE [dbo].[sp_AP_Products_Audit_Select]
	(
        @FromDate	DATETIME,
        @ToDate		DATETIME,
        @Days		INT
	)
AS

SET NOCOUNT ON

--SET @FromDate = '2013-10-01'
--SET @ToDate = '2013-11-03'

	IF @ToDate IS NULL
		SET @ToDate = GetDate()
				
	IF @FromDate IS  NULL
		SET @FromDate = GetDate()

	IF (@FromDate IS NOT NULL AND 
		@ToDate IS NOT NULL)
	BEGIN
		SELECT @FromDate = CAST(Convert(Varchar(10),@FromDate,120) AS DATETIME)
		SELECT @ToDate = CAST(Convert(Varchar(10),DateAdd(dd,1,@ToDate),120) AS DATETIME)		
	END

	IF @Days <> 0
	BEGIN
		SET @FromDate = GetDate()
		SET @ToDate = DateAdd(dd,(@Days*-1),@FromDate)
		
		SELECT @FromDate = CAST(Convert(Varchar(10),@FromDate,120) AS DATETIME)
		SELECT @ToDate = CAST(Convert(Varchar(10),DateAdd(dd,1,@ToDate),120) AS DATETIME)			
	END

SELECT	'1' + '|' + 
		left('Action_Date' + REPLICATE(' ',19), 19) + '|' +
		left('ID' + REPLICATE(' ',7), 7) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +
		left('Product_Description' + REPLICATE(' ',50), 50) + '|' +
		left('Action' + REPLICATE(' ',6), 6) + '|' +
		left('Field' + REPLICATE(' ',20), 20) + '|' +		
		left('Prev_Value'+ REPLICATE(' ',50), 50) + '|' +
		left('New_Value'+ REPLICATE(' ',50), 50)	
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +		
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		left(ynp.[Description] + REPLICATE(' ',50), 50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Field = 'Slu_AW_Active_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Description'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Print_Description'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Product_Code' AND 
	  ap.Record_Action = 'Update'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  	  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Departments_ID
WHERE ap.Field = 'Lup_AP_Product_Departments_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Groups_ID
WHERE ap.Field = 'Lup_AP_Product_Groups_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Locations_ID
WHERE ap.Field = 'Lup_AP_Product_Locations_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID
WHERE ap.Field = 'Lup_AP_Product_Manufacturers_ID' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Types_ID
WHERE ap.Field = 'Lup_AP_Product_Types_ID' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Lup_AP_Purchase_Categories_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate   
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +  --Product Code Stored Here
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	--Product Description Stored Here
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Delete' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price1'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price2'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate   
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price1,0) As Varchar(50)) + REPLICATE(' ',50), 50)				
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price2,0) As Varchar(50)) + REPLICATE(' ',50), 50)					
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(p.Lup_AP_Purchase_Categories_ID,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID		
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(p.Lup_AP_Product_Types_ID,0) AS INT) = ln.Lup_AP_Product_Types_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(p.Lup_AP_Product_Manufacturers_ID,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(p.Lup_AP_Product_Locations_ID,0) AS INT) = ln.Lup_AP_Product_Locations_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(p.Lup_AP_Product_Groups_ID,0) AS INT) = ln.Lup_AP_Product_Groups_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(p.Lup_AP_Product_Departments_ID,0) AS INT) = ln.Lup_AP_Product_Departments_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(p.Print_Description,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(p.Slu_AW_Active_ID AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
ORDER BY 1

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Audit_Select2
--Purpose       :Return Audit Data on AP_Products
--Date          :2014/04/11
--Authors       :RL
--Version		:6.0
-------------------------------------------------------------------------------
--16923
--986
-- Exec sp_AP_Products_Audit_Select2 25890, '2013-10-14', '2015-10-29', 0, 0, 0, 0
-- Exec sp_AP_Products_Audit_Select NULL, NULL, NULL
-- AA3_Silverlakes
CREATE PROCEDURE [dbo].[sp_AP_Products_Audit_Select2]
	(
        @AP_Products_ID		INT,
        @FromDate			DATETIME,
        @ToDate				DATETIME,
        @ShowQuantity		BIT,
        @ShowLastSale		BIT,
        @ShowAverageCost	BIT,
        @ShowLastCost		BIT
	)
AS

SET NOCOUNT ON

SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',
	ap.Prev_Value As 'Previous Value',
	ap.New_Value AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Description'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Print Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Print_Description'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'    
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Search Keyword' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Keywords'
	AND	ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Type' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Types_ID' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Group' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Groups_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Department' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID			
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Departments_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Location' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Locations_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Purchase Category' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID				
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Purchase_Categories_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Serial Number' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Serial_Number'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Manufacturer' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Manufacturers_ID' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Manufacturer Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Manufacturer_Code'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Manufacturer Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Manufacturer_Description'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Default Supplier' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.Supplier_Name As 'Previous Value',
	ynn.Supplier_Name AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AO_Suppliers ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AO_Suppliers_ID
	INNER JOIN AO_Suppliers ynn
		ON CAST(ap.New_Value AS INT) = ynn.AO_Suppliers_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Default_Supplier_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Self Managed' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Self_Managed'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Active' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_Active_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Product_Code' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'SKU Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'SKU_Code' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Supercession Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Supercession' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Alternate Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Alternate_Code1' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Bar Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Alternate_Code2' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Pack Size' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Pack_Size' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Measure' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AP_Units_Of_Measure ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AP_Units_Of_Measure ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AP_Units_Of_Measure_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Packaging' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Strength' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Mass_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Mass_Codes_ID
	INNER JOIN Lup_AP_Mass_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Mass_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Mass_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Pack Volume' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Pack_Volume' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Pack Mass' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Pack_Mass' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_AW_Weight ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_AW_Weight_ID
	INNER JOIN Lup_AP_AW_Weight ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_AW_Weight_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_AW_Weight_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Weight' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Product_Weight' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Qty On Hand' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'On_Hand' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
	AND @ShowQuantity = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Last Cost' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Last_Cost' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
	And @ShowLastCost = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Average Cost' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Average_Cost' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND	ap.Record_Action = 'Update'  
	AND @ShowAverageCost = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Standard Cost' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Standard_Cost' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Average Markup' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Average_Markup' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Last Sale Date' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Last_Sale_Date' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
	AND @ShowLastSale = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Service Level' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Service_Level' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Max Order Qty' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Max_Order_Qty' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Min Order Qty' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Min_Order_Qty' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Min Stock Level' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Min_Stock_Level'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price1 Effective Date' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price1_Effective_Date'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 1_1' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price1_Price1'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 1_2' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price1_Price2'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price2 Effective Date' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price2_Effective_Date'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 2_1' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price2_Price1'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 2_2' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price2_Price2'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Rounding Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Rounding_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Rounding_Codes_ID
	INNER JOIN Lup_AP_Rounding_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Rounding_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Rounding_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Tax Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Sys_AW_Tax_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Sys_AW_Tax_Codes_ID
	INNER JOIN Sys_AW_Tax_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Sys_AW_Tax_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Sys_AW_Tax_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Sell By Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Sell_By_Codes_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Sell_By_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Sell_By_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION

--Levy
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Levy Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	CASE 
	When ISNULL(ynp.[Description],'') = '' Then '<None>'
	ELSE ynp.[Description]		
	END As 'Previous Value',
	CASE 
	When ISNULL(ynn.[Description],'') = '' Then '<None>'
	ELSE ynn.[Description]		
	END As 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AP_Products ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AP_Products_ID
	INNER JOIN AP_Products ynn
		ON CAST(ap.New_Value AS INT) = ynn.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Levy_AP_Product_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Sell By Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Sell_By_Codes_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Sell_By_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Sell_By_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Non-Stock Item' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Non_Stock_Item'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Levy Item' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Levy_Item'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Levy Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_AW_Weight ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_AW_Weight_ID
	INNER JOIN Lup_AP_AW_Weight ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_AW_Weight_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Levy_Weight_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Sales Discount Group' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Discount_Groups ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Discount_Groups_ID
	INNER JOIN Lup_AP_Discount_Groups ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Discount_Groups_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Discount_Groups_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Cost Plus' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Cost_Plus_Item'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Cost Plus Group' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Markup_Groups ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Markup_Groups_ID
	INNER JOIN Lup_AP_Markup_Groups ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Markup_Groups_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Markup_Groups_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Edit Price' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Edit_Price'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Edit Discount' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Edit_Discount'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Min GP' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Max_Discount_Perc'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Enforce Min GP' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Max_Discount_Perc'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'GL Purchase Account' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AB_Accounts ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AB_Accounts_ID
	INNER JOIN AB_Accounts ynn
		ON CAST(ap.New_Value AS INT) = ynn.AB_Accounts_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'GL_Purchases_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'GL Sales Account' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AB_Accounts ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AB_Accounts_ID
	INNER JOIN AB_Accounts ynn
		ON CAST(ap.New_Value AS INT) = ynn.AB_Accounts_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'GL_Sales_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'GL COS Account' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AB_Accounts ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AB_Accounts_ID
	INNER JOIN AB_Accounts ynn
		ON CAST(ap.New_Value AS INT) = ynn.AB_Accounts_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'GL_COS_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION

--Insert
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.Prev_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Insert' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Insert' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
UNION
--Delete
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.Prev_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Delete' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Delete' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
ORDER BY 1, 2

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Audit_Temp_Select
--Purpose       :Return Audit Data on AP_Products - Runs via Task Scheduler
--Date          :2013/10/30
--NOTES			:ALL CHANGES DONE IN THIS PROC SHOULD BE DONE IN 
--				:sp_AP_Products_Audit_Temp_Select as well
--Authors       :RL
-------------------------------------------------------------------------------
--16923
--986
-- Exec sp_AP_Products_Audit_Temp_Select
-- Exec sp_AP_Products_Audit_Temp_Select
-- AA3_Silverlakes
CREATE PROCEDURE [dbo].[sp_AP_Products_Audit_Temp_Select]
AS

SET NOCOUNT ON

--Update AP_Products_Audit
--Set Changes_Sent = 0

--TRUNCATE TABLE AP_Products_Audit_Temp

--INSERT INTO AP_Products_Audit_Temp
--SELECT *
--FROM AP_Products_Audit
--WHERE ISNULL(Changes_Sent,0) = 0

--UPDATE AP_Products_Audit
--SET Changes_Sent = 1
--WHERE ISNULL(Changes_Sent,0) = 0

SELECT	'1' + '|' + 
		left('Action_Date' + REPLICATE(' ',19), 19) + '|' +
		left('ID' + REPLICATE(' ',7), 7) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +
		left('Product_Description' + REPLICATE(' ',50), 50) + '|' +
		left('Action' + REPLICATE(' ',6), 6) + '|' +
		left('Field' + REPLICATE(' ',20), 20) + '|' +		
		left('Prev_Value'+ REPLICATE(' ',50), 50) + '|' +
		left('New_Value'+ REPLICATE(' ',50), 50)	
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +		
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		left(ynp.[Description] + REPLICATE(' ',50), 50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Field = 'Slu_AW_Active_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Description'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Print_Description'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Product_Code' AND 
	  ap.Record_Action = 'Update'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Departments_ID
WHERE ap.Field = 'Lup_AP_Product_Departments_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Groups_ID
WHERE ap.Field = 'Lup_AP_Product_Groups_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Locations_ID
WHERE ap.Field = 'Lup_AP_Product_Locations_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID
WHERE ap.Field = 'Lup_AP_Product_Manufacturers_ID' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Types_ID
WHERE ap.Field = 'Lup_AP_Product_Types_ID' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Lup_AP_Purchase_Categories_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +  --Product Code Stored Here
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	--Product Description Stored Here
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Delete' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price1'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price2'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price1,0) As Varchar(50)) + REPLICATE(' ',50), 50)						
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price2,0) As Varchar(50)) + REPLICATE(' ',50), 50)						
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(p.Lup_AP_Purchase_Categories_ID,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID		
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(p.Lup_AP_Product_Types_ID,0) AS INT) = ln.Lup_AP_Product_Types_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(p.Lup_AP_Product_Manufacturers_ID,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(p.Lup_AP_Product_Locations_ID,0) AS INT) = ln.Lup_AP_Product_Locations_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(p.Lup_AP_Product_Groups_ID,0) AS INT) = ln.Lup_AP_Product_Groups_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(p.Lup_AP_Product_Departments_ID,0) AS INT) = ln.Lup_AP_Product_Departments_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(p.Print_Description,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(p.Slu_AW_Active_ID AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Record_Action = 'Insert' 
ORDER BY 1

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Products_Bins_Hist_Insert
--Purpose       :maintain Product Bins
--Date          :2015-02-02
--Authors       :RL
--Mods          :
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Products_Bins_Hist_Insert]
    (
    	@ProductID					int,
        @From_Bin_ID				int,
        @From_Bin_Previous_On_Hand	decimal(9,3),
        @To_Bin_ID					int,
        @To_Bin_Previous_On_Hand	decimal(9,3),
    	@Qty						decimal(9,3), --From V6.2 This is the bin on hand qty
    	@Source						varchar(10),
    	@Batch_No					int,
    	@UserID						int,
    	@CompanyID					int
    )
AS

SET NOCOUNT ON

	Declare @Bin_Prev_On_Hand decimal(9,3),
            @On_Hand_Diff decimal(9,3),
            @New_On_Hand decimal(9,3),
            @AP_Products_Bins_History_ID int

    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @Bin_Prev_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    --SET @Batch_No = 0

 	--> Calculate Product on hand diff
	--SELECT @Bin_Prev_On_Hand = On_Hand
	--FROM AP_Products_Bins
	--WHERE AP_Products_ID = @ProductID
	--AND Lup_AP_Product_Bins_ID = @ProductBinID
	
	SELECT @New_On_Hand = @Bin_Prev_On_Hand + @Qty
	
	IF @Qty <> 0
	BEGIN --@Qty <> 0
		--From Bin
		IF EXISTS
		(
			SELECT 1
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @ProductID
    		AND Lup_AP_Product_Bins_ID = @From_Bin_ID	
		)
		BEGIN
			UPDATE AP_Products_Bins
			SET On_Hand = On_Hand - @Qty
			WHERE AP_Products_ID = @ProductID
			AND Lup_AP_Product_Bins_ID = @From_Bin_ID
		END
		ELSE
		BEGIN
			INSERT INTO AP_Products_Bins
			(
				AP_Products_ID, 
				Lup_AP_Product_Bins_ID, 
				On_Hand, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			VALUES
			(
				@ProductID,
				@From_Bin_ID,
				@Qty,
				GETDATE(),
				@UserID,
				@CompanyID,
				1
			)		
		END	

		--To Bin
		IF EXISTS
		(
			SELECT 1
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @ProductID
    		AND Lup_AP_Product_Bins_ID = @To_Bin_ID	
		)
		BEGIN
			UPDATE AP_Products_Bins
			SET On_Hand = On_Hand + @Qty
			WHERE AP_Products_ID = @ProductID
			AND Lup_AP_Product_Bins_ID = @To_Bin_ID
		END
		ELSE
		BEGIN
			INSERT INTO AP_Products_Bins
			(
				AP_Products_ID, 
				Lup_AP_Product_Bins_ID, 
				On_Hand, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			VALUES
			(
				@ProductID,
				@To_Bin_ID,
				@Qty,
				GETDATE(),
				@UserID,
				@CompanyID,
				1
			)		
		END	

		IF @Source <> ''
		BEGIN		
			--SELECT @AP_Products_Bins_History_ID = MAX(AP_Products_Bins_History_ID)
			--FROM AP_Products_Bins_History
			--WHERE AP_Products_ID = @ProductID
			
			--SELECT @Batch_No = MAX(Batch_No)
			--FROM AP_Products_Bins_History
			
			--IF @Batch_No IS NULL
			--	SET @Batch_No = 0
				
			--SET @Batch_No = @Batch_No + 1
			
			--IF @AP_Products_Bins_History_ID = 0
			--BEGIN
				INSERT INTO AP_Products_Bins_History
				(
					Batch_No, 
					AP_Products_ID, 
					From_Lup_AP_Product_Bins_ID, 
					From_Bin_Previous_On_Hand, 
					From_Bin_New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_Previous_On_Hand, 
					To_Bin_New_On_Hand, 
					Movement_Source, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID		
				)
				VALUES
				(
					@Batch_No, 
					@ProductID, 
					@From_Bin_ID, 
					@From_Bin_Previous_On_Hand, 
					@From_Bin_Previous_On_Hand - @Qty, 
					@To_Bin_ID, --To_Lup_AP_Product_Bins_ID
					@To_Bin_Previous_On_Hand, --To_Bin_Previous_On_Hand
					@To_Bin_Previous_On_Hand + @Qty, --To_Bin_New_On_Hand
					@Source, 
					GETDATE(), 
					@UserID, 
					@CompanyID, 
					1 --Slu_AW_Active_ID
				)			
			--END
			--ELSE
			--BEGIN			
			--	INSERT INTO AP_Products_Bins_History
			--	(
			--		Batch_No, 
			--		AP_Products_ID, 
			--		From_Lup_AP_Product_Bins_ID, 
			--		From_Bin_Previous_On_Hand, 
			--		From_Bin_New_On_Hand, 
			--		To_Lup_AP_Product_Bins_ID, 
			--		To_Bin_Previous_On_Hand, 
			--		To_Bin_New_On_Hand, 
			--		Movement_Source, 
			--		Date_Captured, 
			--		[User_ID], 
			--		AW_User_Companies_ID, 
			--		Slu_AW_Active_ID		
			--	)
			--	SELECT
			--		@Batch_No, 
			--		@ProductID, 
			--		@ProductBinID, 
			--		@Bin_Prev_On_Hand, 
			--		@New_On_Hand, 
			--		To_Lup_AP_Product_Bins_ID, 
			--		To_Bin_New_On_Hand, 
			--		To_Bin_New_On_Hand, 
			--		@Source, 
			--		GETDATE(), 
			--		@UserID, 
			--		@CompanyID, 
			--		1
			--	FROM AP_Products_Bins_History
			--	WHERE AP_Products_Bins_History_ID = @AP_Products_Bins_History_ID		
			--END
		END
	END --@Qty <> 0
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Products_Bins_Update_Insert
--Purpose       :maintain Product Bins
--Date          :2015-02-02
--Authors       :RL
--Mods          :
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Products_Bins_Update_Insert]
    (
    	@ProductID		int,
        @ProductBinID	int,
    	@Qty			decimal(9,3), --From V6.2 This is the bin on hand qty
    	@Source			varchar(10),
    	@Batch_No		int,
    	@UserID			int,
    	@CompanyID		int
    )
AS

SET NOCOUNT ON

	Declare @Bin_Prev_On_Hand decimal(9,3),
            @On_Hand_Diff decimal(9,3),
            @New_On_Hand decimal(9,3),
            @AP_Products_Bins_History_ID int

    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @Bin_Prev_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    --SET @Batch_No = 0

 	--> Calculate Product on hand diff
	SELECT @Bin_Prev_On_Hand = On_Hand
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND Lup_AP_Product_Bins_ID = @ProductBinID
	
	SELECT @New_On_Hand = @Bin_Prev_On_Hand + @Qty
	
	IF @Qty <> 0
	BEGIN
		IF EXISTS
		(
			SELECT 1
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @ProductID
    		AND Lup_AP_Product_Bins_ID = @ProductBinID	
		)
		BEGIN
			UPDATE AP_Products_Bins
			SET On_Hand = @New_On_Hand
			WHERE AP_Products_ID = @ProductID
			AND Lup_AP_Product_Bins_ID = @ProductBinID
		END
		ELSE
		BEGIN
			INSERT INTO AP_Products_Bins
			(
				AP_Products_ID, 
				Lup_AP_Product_Bins_ID, 
				On_Hand, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			VALUES
			(
				@ProductID,
				@ProductBinID,
				@New_On_Hand,
				GETDATE(),
				@UserID,
				@CompanyID,
				1
			)		
		END	

		IF @Source <> ''
		BEGIN		
			--SELECT @AP_Products_Bins_History_ID = MAX(AP_Products_Bins_History_ID)
			--FROM AP_Products_Bins_History
			--WHERE AP_Products_ID = @ProductID
			
			--SELECT @Batch_No = MAX(Batch_No)
			--FROM AP_Products_Bins_History
			
			--IF @Batch_No IS NULL
			--	SET @Batch_No = 0
				
			--SET @Batch_No = @Batch_No + 1
			
			IF @AP_Products_Bins_History_ID = 0
			BEGIN
				INSERT INTO AP_Products_Bins_History
				(
					Batch_No, 
					AP_Products_ID, 
					From_Lup_AP_Product_Bins_ID, 
					From_Bin_Previous_On_Hand, 
					From_Bin_New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_Previous_On_Hand, 
					To_Bin_New_On_Hand, 
					Movement_Source, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID		
				)
				VALUES
				(
					@Batch_No, 
					@ProductID, 
					@ProductBinID, 
					@Bin_Prev_On_Hand, 
					@New_On_Hand, 
					1, --To_Lup_AP_Product_Bins_ID
					0, --To_Bin_Previous_On_Hand
					0, --To_Bin_New_On_Hand
					@Source, 
					GETDATE(), 
					@UserID, 
					@CompanyID, 
					1 --Slu_AW_Active_ID
				)			
			END
			ELSE
			BEGIN			
				INSERT INTO AP_Products_Bins_History
				(
					Batch_No, 
					AP_Products_ID, 
					From_Lup_AP_Product_Bins_ID, 
					From_Bin_Previous_On_Hand, 
					From_Bin_New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_Previous_On_Hand, 
					To_Bin_New_On_Hand, 
					Movement_Source, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID		
				)
				SELECT
					@Batch_No, 
					@ProductID, 
					@ProductBinID, 
					@Bin_Prev_On_Hand, 
					@New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_New_On_Hand, 
					To_Bin_New_On_Hand, 
					@Source, 
					GETDATE(), 
					@UserID, 
					@CompanyID, 
					1
				FROM AP_Products_Bins_History
				WHERE AP_Products_Bins_History_ID = @AP_Products_Bins_History_ID		
			END
		END
	END
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















---------------------------------------------------------------------------
--Description	:sp_AP_Products_History_Insert
--Purpose	    :Saves a Stock Valuation as at NOW
--Functionality	: 
--Parameters	: 
--Date		    :21/01/2002
--Authors	    :TB
--Version	    :1.0.0
--MODS          :31/05/03 - Added Average_Cost insert from AP_Products
--              :10/08/03 - Added Current Accounting Period (MonthID/YearID)
--              :           PLUS Stock Valuation TOTAL for each Stock Valuation
--              :15/08/03 - Base Stock_Valuation calc on Valuation Method PARAMETER
--2004.3.0      :13/06/06 - Added filter for @CompanyID and WHERE On_Hand <> 0
--              :           to prevent superflous data storage
--2004.3.1      :22/08/06 - Added INSERT Standard_Cost field to AP_Products_History
--2004.3.2      :18/09/06 - Added RETURN @MonthEndID for Enterprise Stock Valuation
--              :19/09/06 - Added @Date input parameter for Enterprise Stock Valuation
--              :19/09/06 - Added ONLY INSERT Stock Valuation if Stock Value <> 0
--2004.4.2      :26/10/08 - Added new Standard Cost Inventory Valuation method
---------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AP_Products_History_Insert
	(
    	@ApplicationTypeID int,
    	@Description varchar(100),
    	@UserID int,
    	@CompanyID int,
        @Date datetime
	)

AS

SET NOCOUNT ON

	DECLARE @MonthEndID int,
            @StockValuation money,
            @MonthID tinyint,
            @YearID smallint,
--            @ValuationMethod varchar(10)
            @ValuationMethod smallint


    IF @Date IS NULL
        BEGIN
            SET @Date = getdate()
        END


    SET @MonthEndID = 0
    SET @StockValuation = 0


    SELECT @MonthID = Slu_AW_Months_ID,
           @YearID = Slu_AW_Years_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    --> Stock Valuation (theoretical now)
    --------------------------------------------------------
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


    IF @ValuationMethod = 0
        BEGIN
        	SELECT @StockValuation = SUM(ISNULL(Average_Cost, 0) * ISNULL(On_Hand, 0))
        	FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  On_Hand <> 0
        END
    ELSE
    IF @ValuationMethod = 1
        BEGIN
        	SELECT @StockValuation = SUM(ISNULL(Last_Cost, 0) * ISNULL(On_Hand, 0))
        	FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  On_Hand <> 0
        END
    ELSE
    IF @ValuationMethod = 2
        BEGIN
        	SELECT @StockValuation = SUM(ISNULL(Standard_Cost, 0) * ISNULL(On_Hand, 0))
        	FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  On_Hand <> 0
        END
    --------------------------------------------------------


    IF @StockValuation <> 0
        BEGIN
        	INSERT AW_Period_Procedures
        		(
            		Sys_AW_Period_Procedure_Types_ID,
            		[Description],
                    [Month],
                    [Year],
            		Month_End_Date,
                    Stock_Valuation,
            		AW_User_Companies_ID,
            		[User_ID]
        		) 
        	VALUES
        		(
            		@ApplicationTypeID,
            		@Description,
                    @MonthID,
                    @YearID,
            		@Date,
                    @StockValuation,
            		@CompanyID,
            		@UserID
        		)
        
        	SELECT @MonthEndID = Scope_Identity()
        
        	INSERT AP_Products_History
        		(
            		AP_Products_ID,
            		AW_Period_Procedures_ID,
            		Cost,
                    Average_Cost,
                    Standard_Cost,
            		Qty,
            		AW_User_Companies_ID,
            		[User_ID]
        		)
        	SELECT     
                    AP_Products_ID,
                    @MonthEndID,
                    Last_Cost, 
                    Average_Cost,
                    Standard_Cost,
                    On_Hand,
                    @CompanyID,
                    @UserID
        	FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID AND
                  On_Hand <> 0
        END



RETURN @MonthEndID


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--TRUNCATE TABLE AP_Products_History

---------------------------------------------------------------------------
--Description	:sp_AP_Products_History_Select
--Purpose	    :Selects Picklist for Stock Valuations
--Functionality	: 
--Parameters	: 
--Date		    :21/01/2002
--Authors	    :TB
--Version	    :1.0.0
---------------------------------------------------------------------------

CREATE  PROCEDURE sp_AP_Products_History_Select
    (
    	@Choice int,
    	@PeriodTypeID int = 0,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	IF @Choice = 1  --List
		SELECT AW_Period_Procedures_ID as [ID],
              [Description],
               Date_Captured as [Date] 
		FROM AW_Period_Procedures 
		WHERE Sys_AW_Period_Procedure_Types_ID = @PeriodTypeID AND
              AW_User_Companies_ID = @CompanyID
		 ORDER BY Date_Captured DESC
	        
	ELSE 
	IF @Choice = 2
		SELECT 1


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Stock_Take_Insert
--Purpose       :Inserts Ad Hoc Stock Take into
--Tables        :    AP_Stock_Take_Procedures AND AP_Products_Stock_Takes
--Date          :2002/02/14
--Authors       :TB
--MODS          :21/04/02 - Insert 0 into Count1 not 'On_Hand, '
--              :24/04/02 - Removed Discount & Commission parameters
--              :15/08/03 - Switched to NEW AP_Stock_Take_Procedures from
--              :           AW_Period_Procedures because of table cluttering
--2004.4.3      :15/02/09 - Updated with the latest Stock Valuation costing methods
--              :15/02/09 - Reworked with new table definitions
--2004.4.4      :02/05/09 - Added ISNULL validation of Costs and On Hand before insert - TCWIT
--V6.2	RL	2015-12-01	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Products_Stock_Take_Insert]
	(
    	@UserID int,
    	@CompanyID int,
    	@Description varchar(500),
    	@ManufacturerID int = -1,
    	@DepartmentID int = -1,
    	@LocationID int = -1,
    	@TypeID int = -1,
    	@ProductGroupID int = -1,
    	@SupplierID int = -1,
    	@BinID int = -1
	)

AS

SET NOCOUNT ON

	DECLARE @ProcedureID int,
            @Filter varchar(6000),
            @SQL varchar(6000),
            @StockValuation money,
            @ValuationMethod smallint


	SET @Filter = ''

    --> Company
	IF @CompanyID > 0 
		BEGIN
            SET @Filter = ' WHERE p.AW_User_Companies_ID = ' + 
                            CONVERT(varchar(20), @CompanyID)
        END

    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Manufacturers_ID = ' +
                                CONVERT(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                CONVERT(varchar(20), @ManufacturerID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Departments_ID = ' +
                                CONVERT(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                CONVERT(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Locations_ID = ' +
                                CONVERT(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                CONVERT(varchar(20), @LocationID)
    	END
    --> Type
	IF @TypeID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Types_ID = ' +
                                CONVERT(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                CONVERT(varchar(20), @TypeID)
		END
    --> Product Group
	IF @ProductGroupID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Groups_ID = ' +
                                CONVERT(varchar(20), @ProductGroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                CONVERT(varchar(20), @ProductGroupID)
		END
    --> Default Supplier
	IF @SupplierID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Default_Supplier_ID = ' +
                                CONVERT(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                CONVERT(varchar(20), @SupplierID)
		END
    --> Product Bin
	IF @BinID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END


	INSERT AP_Stock_Take_Procedures
        (
            [Description],
            [Procedure_Date],
            [Stock_Valuation],
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @Description,
            getdate(),
            0,
            @UserID,
            @CompanyID
        )

	SELECT @ProcedureID = Scope_Identity()


    --------------------------------------------------------
    --> Get Primary Costing Method
    --------------------------------------------------------
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID
    --------------------------------------------------------


	SET @SQL = 'INSERT AP_Products_Stock_Takes ('
    SET @SQL = @SQL + 'AP_Products_ID, '
    SET @SQL = @SQL + 'Lup_AP_Product_Bins_ID, '
    SET @SQL = @SQL + 'AP_Stock_Take_Procedures_ID, '
    SET @SQL = @SQL + 'Count1, '
    SET @SQL = @SQL + 'Count2, '
    SET @SQL = @SQL + 'Count3, '
    SET @SQL = @SQL + 'Total_Count, '
    SET @SQL = @SQL + 'Unit_Cost, '
    SET @SQL = @SQL + 'On_Hand, '
    SET @SQL = @SQL + 'Variance, '
    SET @SQL = @SQL + 'Total_On_Hand, '
    SET @SQL = @SQL + 'Consignment_Qty, ' 
    SET @SQL = @SQL + 'On_Hand_Calc, '     
    

       
    SET @SQL = @SQL + 'AW_User_Companies_ID, '
    SET @SQL = @SQL + 'User_ID'
    SET @SQL = @SQL + ') '

    SET @SQL = @SQL + 'SELECT p.AP_Products_ID, '
    SET @SQL = @SQL + 'b.Lup_AP_Product_Bins_ID, '
    SET @SQL = @SQL + CONVERT(varchar(10), @ProcedureID) + ', ' 
    SET @SQL = @SQL + '0, '
    SET @SQL = @SQL + '0, '
    SET @SQL = @SQL + '0, '
    SET @SQL = @SQL + '0, '

--     IF @ValuationMethod = 0
--         BEGIN
--             SET @SQL = @SQL + 'Average_Cost, '
--         END
--     ELSE
--     IF @ValuationMethod = 1
--         BEGIN
--             SET @SQL = @SQL + 'Last_Cost, '
--         END
--     ELSE
--     IF @ValuationMethod = 2
--         BEGIN
--             SET @SQL = @SQL + 'Standard_Cost, '
--         END
-- 
--     SET @SQL = @SQL + 'On_Hand, '
--     SET @SQL = @SQL + '(On_Hand * -1), '

    --2004.4.4 - Added ISNULL validation of Costs and On Hand - TCWIT
    IF @ValuationMethod = 0
        BEGIN
            SET @SQL = @SQL + 'ISNULL(p.Average_Cost, 0), '
        END
    ELSE
    IF @ValuationMethod = 1
        BEGIN
            SET @SQL = @SQL + 'ISNULL(p.Last_Cost, 0), '
        END
    ELSE
    IF @ValuationMethod = 2
        BEGIN
            SET @SQL = @SQL + 'ISNULL(p.Standard_Cost, 0), '
        END

    SET @SQL = @SQL + 'ISNULL(b.On_Hand, 0), '				--V6.2 Bin On Hand Used
    SET @SQL = @SQL + '(ISNULL(b.On_Hand, 0) * -1), '		--V6.2 Bin On Hand Used
    SET @SQL = @SQL + 'ISNULL(p.On_Hand, 0), '				
	SET @SQL = @SQL + 'ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0), '				    

	SET @SQL = @SQL + '		CASE '
	SET @SQL = @SQL + '			WHEN ( ISNULL(p.On_Hand, 0) - ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0) ) < ISNULL(p.On_Hand, 0) Then 0 '
	SET @SQL = @SQL + '			ELSE ( ISNULL(p.On_Hand, 0) - ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0) )'
	SET @SQL = @SQL + '		END, '


    SET @SQL = @SQL + CONVERT(varchar(10),@CompanyID) + ', '
    SET @SQL = @SQL + CONVERT(varchar(10),@UserID) + ' '
    SET @SQL = @SQL + 'FROM AP_Products p'
    SET @SQL = @SQL + '		LEFT OUTER JOIN AP_Products_Bins b '
    SET @SQL = @SQL + '			ON p.AP_Products_ID = b.AP_Products_ID'   
    SET @SQL = @SQL + @Filter


	EXEC (@SQL)
	--Select @SQL

	UPDATE AP_Products_Stock_Takes
	SET Variance_Calc = Variance + Consignment_Qty
	WHERE AP_Stock_Take_Procedures_ID = @ProcedureID

    IF @ValuationMethod = 0
        BEGIN
        	--SELECT @StockValuation = SUM( ISNULL(p.Average_Cost, 0) * ISNULL(pst.On_Hand, 0) )	--V6.2 Bin On Hand Used
        	SELECT @StockValuation = SUM( ISNULL(p.Average_Cost, 0) * ISNULL(pst.On_Hand_Calc, 0) )	--V6.2 Bin On Hand Used
        	FROM AP_Products p
                INNER JOIN AP_Products_Stock_Takes pst
                    ON pst.AP_Products_ID = p.AP_Products_ID
            WHERE pst.AP_Stock_Take_Procedures_ID = @ProcedureID
        END
    ELSE
    IF @ValuationMethod = 1
        BEGIN
        	--SELECT @StockValuation = SUM( ISNULL(p.Last_Cost, 0) * ISNULL(pst.On_Hand, 0) )		--V6.2 Bin On Hand Used
        	SELECT @StockValuation = SUM( ISNULL(p.Last_Cost, 0) * ISNULL(pst.On_Hand_Calc, 0) )		--V6.2 Bin On Hand Used
        	FROM AP_Products p
                INNER JOIN AP_Products_Stock_Takes pst
                    ON pst.AP_Products_ID = p.AP_Products_ID
            WHERE pst.AP_Stock_Take_Procedures_ID = @ProcedureID
        END
    ELSE
    IF @ValuationMethod = 2
        BEGIN
        	--SELECT @StockValuation = SUM( ISNULL(p.Standard_Cost, 0) * ISNULL(pst.On_Hand, 0) )	--V6.2 Bin On Hand Used
        	SELECT @StockValuation = SUM( ISNULL(p.Standard_Cost, 0) * ISNULL(pst.On_Hand_Calc, 0) )	--V6.2 Bin On Hand Used
        	FROM AP_Products p
                INNER JOIN AP_Products_Stock_Takes pst
                    ON pst.AP_Products_ID = p.AP_Products_ID
            WHERE pst.AP_Stock_Take_Procedures_ID = @ProcedureID
        END
    --------------------------------------------------------

    --> Update table with Stock Valuation (theoretical now)
    UPDATE AP_Stock_Take_Procedures
    SET Stock_Valuation = @StockValuation
    WHERE AP_Stock_Take_Procedures_ID = @ProcedureID



RETURN @ProcedureID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Stock_Take_Select
--Purpose       :Check if Products EXIST for selected Filters before Create Stock Take
--Date          :2009/02/20
--Authors       :TB
--MODS          :
--V6.2	RL	2015-12-01	:Added Product Bins
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Products_Stock_Take_Select]
	(
    	@CompanyID int,
    	@ManufacturerID int = -1,
    	@DepartmentID int = -1,
    	@LocationID int = -1,
    	@TypeID int = -1,
    	@ProductGroupID int = -1,
    	@SupplierID int = -1,
    	@BinID int = -1
	)
AS

SET NOCOUNT ON

    DECLARE @Filter varchar(6000),
            @SQL varchar(6000)


	SET @Filter = ''


    --> Company
	IF @CompanyID > 0 
		BEGIN
            SET @Filter = ' WHERE p.AW_User_Companies_ID = ' + 
                            convert(varchar(20), @CompanyID)
        END

    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
    	END
    --> Type
	IF @TypeID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Product Group
	IF @ProductGroupID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @ProductGroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @ProductGroupID)
		END
    --> Default Supplier
	IF @SupplierID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Product Bin
	IF @BinID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END


    SET @SQL = 'SELECT count(*) AS [CNT] '
    SET @SQL = @SQL + 'FROM AP_Products p'
    SET @SQL = @SQL + '		LEFT OUTER JOIN AP_Products_Bins b '
    SET @SQL = @SQL + '			ON p.AP_Products_ID = b.AP_Products_ID'
    SET @SQL = @SQL + @Filter

	EXEC (@SQL)
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE     PROCEDURE sp_AP_Products_Utility
(
    @Choice tinyint,
    @Criteria varchar(4000)
)

AS
    SET NOCOUNT ON
    IF @Choice = 0 --Unique Identifiers
        BEGIN
            SET @Criteria = '%' + @Criteria + '%'
            SELECT * FROM vw_AP_Products_Subset_Identifiers
            WHERE     Description like @Criteria  OR 
                  [Packs Bar Code] like @Criteria  OR
                  [Units Bar Code] like @Criteria
        END
    ELSE
    IF @Choice = 1 --Relations for current Product
        BEGIN
            SELECT 
                Switch1_Description as Make,
                Switch2_Description as Model,
                Switch3_Description as [Model Year],
                Switch4_Description as [Type]
            FROM vw_AP_Switches
            WHERE  AP_Products_ID = @Criteria
        END
    ELSE
    IF @Choice = 2  --Contract Prices
        SELECT  AO_Supplier_Contracts_ID as ID,
                AO_Suppliers_ID as [Suppliers ID],
                AP_Products_ID as [Product ID],
                Start_Date as [Start Date], 
                End_Date as [End Date],
                Packs_Contract_Qty as [Contract Packs Qty],
                Packs_Purchased as [Packs Purchased]
        FROM AO_Supplier_Contracts
        WHERE AO_Suppliers_ID = @Criteria


    ELSE
    IF @Choice = 3  --Orders
        SELECT  oi.AO_Order_Items_ID AS ID, 
                oi.AP_Products_ID AS [Product ID], 
                oi.Lead_Time AS [Lead Time], 
                oi.Packs_Order_Qty AS [Packs Order Qty], 
                oi.Packs_Free AS [Packs Free], 
                oi.Unit_Cost AS [Unit Cost], 
                oi.Average_Discount AS [Average Discount], 
                o.Order_Number AS [Order No], 
                o.Order_Date AS [Order Date], 
                o.Supplier_Rep AS [Supplier Rep], 
                o.Our_Ref AS [Our Ref], 
                o.Supplier_Reference AS [Supplier Ref], 
                o.Order_Total AS [Order Total]
        FROM    AO_Orders o INNER JOIN AO_Order_Items oi 
                    ON o.AO_Orders_ID = oi.AO_Orders_ID
        WHERE o.AO_Suppliers_ID = @Criteria            
    ELSE   
    IF @Choice = 4 --Supplier Identifiers
        BEGIN
            SET @Criteria = '%' + @Criteria + '%'
            SELECT * FROM vw_AO_Suppliers_Subset_Identifiers
            WHERE Description like @Criteria  
        END






 








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




















---------------------------------------------------------------------------------
--Description   :sp_AP_Profit_Protector_Lups
--Purpose       :Returns LUPS for Profit Protector
--Functionality :
--Parameters    :	
--Date          :2004/02/14
--Authors       :TB
--MODS          :14/04/04 - Added ORDER BY in Option 1 and 2
--              :05/08/04 - Added ORDER BY in Option 3, 4, and 5
--2004.3.8      :09/05/08 - Replaced [ApplyMaxDisc] field functionality with
--              :           [ApplyMinGP] functionality in Option 9
--2004.4.1      :29/09/08 - Added Purchase Category
---------------------------------------------------------------------------------

CREATE                  Procedure sp_AP_Profit_Protector_Lups
    (
    	@Option int
    )

AS

SET NOCOUNT ON


    --> Supplier
    	IF @Option = 1
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name as [Description]
    		FROM AO_Suppliers
            ORDER BY Supplier_Name
    
    --> Manufacturer
    	ELSE 
    	IF @Option = 2
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Manufacturers
            ORDER BY [Description]
    
    --> Type
    	ELSE 
    	IF @Option = 3
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Types
            ORDER BY [Description]
    
    --> Group
    	ELSE 
    	IF @Option = 4
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Groups
            ORDER BY [Description]
    
    --> Department
    	ELSE 
    	IF @Option = 5
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Product_Departments
            ORDER BY [Description]

    --> Active
    	ELSE 
    	IF @Option = 6
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_Active

    --> Yes/No Edit Price
    	ELSE 
    	IF @Option = 7
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] AS [Edit Price]
    		FROM Slu_AW_YesNo

    --> Yes/No Edit Disc
    	ELSE 
    	IF @Option = 8
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] AS [Edit Disc]
    		FROM Slu_AW_YesNo

    --> Yes/No Enforce Min GP%
    	ELSE 
    	IF @Option = 9
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] AS [Apply Min%]
    		FROM Slu_AW_YesNo

    --> Purchase Categories
    	ELSE 
    	IF @Option = 10
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Purchase_Categories
            ORDER BY [Description]

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_RPT_Stock_Transfer_Print
--Purpose       :POS Sales Order printing
--Parameters    :
--Date          :21 AUG 2009
--Authors       :TB
--MODS:         :
--V6.2 RL	2015-11-29	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_RPT_Stock_Transfer_Print]
    (
    	@TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @TextMessage varchar(100),
            @TextMessagePrint varchar(100),
            @Message varchar(100),
            @WhichAddress tinyint,
            @WhichName tinyint,
            @PaymentMethod varchar(20),
            @AddressOption0 varchar(20),
            @AddressOption1 varchar(20)


    SET @WhichAddress = 0
    SET @Message = ''


    SELECT TOP 1 @TextMessage = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'



    SELECT TOP 1 @AddressOption0 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 0

    SELECT TOP 1 @AddressOption1 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 1

    IF @AddressOption0 = 'True'
        BEGIN
            SET @WhichAddress = 0        --Print POSTAL Address
        END
    ELSE
    IF @AddressOption1 = 'True'
        BEGIN
            SET @WhichAddress = 1        --Print STREET Addres
        END


    SELECT TOP 1 @TextMessagePrint = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    IF @TextMessagePrint = '1'
        BEGIN
            SET @Message = @TextMessage
        END


    SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSPrintTradeName'


    SELECT TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''), 20)
	FROM AS_Transactions_Transactions att
        LEFT JOIN AS_Transaction_Payments tp
            ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID
        LEFT JOIN Sys_AW_Payment_Methods pm
            ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID
	WHERE att.Source_AS_Transactions_ID = @TransactionID
    ORDER BY att.Source_AS_Transactions_ID


	SELECT 
		RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') AS [CustomerName],
        ISNULL(c.Firstnames, '') AS [TradeName],
        ISNULL(c.Contact_Name, '') AS [Contact],

    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
		ISNULL(c.Post_Box, '') AS [PostBox],
		ISNULL(c.Post_Office, '') AS [PostOffice],
		ISNULL(c.City, '') AS [PostCity],
		ISNULL(c.Post_Code, '') AS [PostCode],

		ISNULL(c.Street_Address, '') AS [StreetAddress],
		ISNULL(c.Suburb, '') AS [StreetSuburb],
		ISNULL(c.City, '') AS [StreetCity],
		ISNULL(c.Street_Post_Code, '') AS [StreetPostCode],

		ISNULL(c.Delivery_Address, '') AS [DeliverAddress],
		ISNULL(c.Delivery_Suburb, '') AS [DeliverSuburb],
		ISNULL(c.Delivery_City, '') AS [DeliverCity],
		ISNULL(c.Delivery_Post_Code, '') AS [DeliverPostCode],

		ISNULL(c.Customer_Number, '') + '(' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + ')' AS [CustomerNo],

        CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> ''
             THEN 'Merchant No: ' + RTRIM(LTRIM(c.Old_Customer_Number))
             ELSE ''
             END AS [MerchantNo],

        t.Sys_AW_Transaction_Types_ID AS [TranTypeID],
		tt.[Description] AS [TransactionType],
		comp.Tax_Number AS [CompanyTaxNumber],
		comp.Company_Name AS [CompanyName],
		comp.Company_Trading_Name AS [TradingName],
		comp.Company_Addr1 AS [CompanyAddress1],
		comp.Company_Addr2 AS [CompanyAddress2],
		comp.Company_City AS [CompanyCity],
		comp.Company_Post_Code AS [CompanyPostCode],
        comp.Company_Registration_Number AS [CompanyRegNo],
        comp.Tel_No AS [CompanyTelNo],
        comp.Fax_No AS [CompanyFaxNo],
		rep.[Description] AS [RepName],
		t.AS_Transactions_ID AS [TransactionID],
		t.Transaction_Number AS [TransactionNo],
		CONVERT(varchar(12), t.Transaction_Date, 103) AS [TransactionDate],
		t.Customer_Reference AS [TransactionCustomerRef],
        t.Amount AS [TransactionAmount],
		t.Total_Amount AS [TransactionTotalAmount],
		t.Total_Discount_Amount AS [TransactionTotalDiscount],
		t.Total_Tax_Amount AS [TransactionTotalTax],
		com.Comment AS [TransactionComment],
-------------------------------------------------------------------------------
		p.Product_Code AS [ProductCode],
		p.Description AS [ProductDescription],
		td.Quantity AS [DetailQty],
		td.Unit_Price AS [DetailUnitPrice],

        CASE WHEN (td.Unit_Price * td.Quantity) <> 0
             THEN CONVERT(money,ABS(ROUND((((td.Discount_Amount) / (td.Unit_Price * td.Quantity)) * 100), 2)))
             ELSE 0.00
             END AS [DetailDiscPerc],

		td.Discount_Amount AS [DetailDiscount],
       (td.Unit_Price * td.Quantity) + td.Discount_Amount AS [DetailAmount],
		td.Tax_Amount AS [DetailTaxAmount],
		td.Extended_Amount AS [DetailExtendedAmount],
        CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime],
        u.UserName AS [UserCode],
        t.Comment AS [Comment],

        ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Cell_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Home_Tel_No)), '') AS [TelNos],
        ISNULL('Fax No ' + RTRIM(LTRIM(c.Fax_No)), '') AS [FaxNo],

        ISNULL(RTRIM(LTRIM(c.Tax_Number)), '') AS [VATNo],

        CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> ''
             THEN 'Jobcard No: ' + RTRIM(LTRIM(ts.Transaction_Numbers))
             ELSE ''
             END AS [JobSource],

        t.AW_User_Companies_ID AS [CompanyID],
        ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass],
        ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Volume, 0), 2) AS [PackVolume],
        @PaymentMethod AS [PayMethod],

        CASE WHEN td.AS_Job_References_ID = 0 
             THEN NULL
             ELSE td.AS_Job_References_ID
             END AS [JobRefNo],

        @Message AS [TextMessage],
        @WhichAddress AS [AddressType],
        td.Serial_No AS [SerialNo],
        td.Make AS [Make],
        td.Customer AS [Customer],
        @WhichName AS [NameType],
        b.description As [Bin]

	FROM AS_Transactions t 
        LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AW_User_Companies comp
            ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID
        LEFT JOIN Lup_AS_Reps rep
            ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID
        LEFT JOIN AS_Transaction_Details td
            ON t.AS_Transactions_ID = td.AS_Transactions_ID
        LEFT JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN AS_Transaction_Sources ts
            ON t.AS_Transactions_ID = ts.AS_Transactions_ID
        LEFT JOIN AW_Comments com
            ON t.AW_Comments_ID = com.AW_Comments_ID
        LEFT JOIN Lup_AP_Product_Bins b
			On b.Lup_AP_Product_Bins_ID = td.Lup_AP_Product_Bins_ID
	WHERE t.AS_Transactions_ID = @TransactionID
    ORDER BY AS_Transaction_Details_ID



SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description	:sp_AP_SUM_Product_Job_Reserved
--Purpose       :Gets JOB CARD and SALES ORDER RESERVED for one Product
--Date			:2006/12/31
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_SUM_Product_Job_Reserved
	(
		@ProductID int,
        @ReservedQTY decimal(9, 3) OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @ReservedQTY = dbo.fn_AP_SUM_Product_Job_Reserved(@ProductID)



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO













-----------------------------------------------------------------------------
--Description   :sp_AP_Sales_Promotion_Top_20_Perc
--Purpose       :Select Top 20% Best Sellers for Sales Promotions
--Functionality :uses FUNCTION dbo.fn_AP_Sales_Promotion_Top_20_Perc
--Parameters    :
--Date          :2004/02/19
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Sales_Promotion_Top_20_Perc
    (
		@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Today datetime

    SET @Today = getdate()

    SELECT  [ID],
            [SupplierID],
            [Product],
            [Code],
            [Last Sale],
            [Sold],
            [On Hand],
            [Ords],
            [Pend],
            [Selling 1],
            [Selling 2],
            [Last Cost],
            [Avg Cost],
            [GP %],
            [MSL],
            [MIN],
            [MAX],
            [SL],
            [Pack]
    FROM dbo.fn_AP_Sales_Promotion_Top_20_Perc(@CompanyID, @Today)


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Billing_Non_Stock_Products
--Purpose       :Fetch all Non-Stock Products for Periodic Billing
--Functionality :
--Date          :2010/11/15
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Select_Billing_Non_Stock_Products
    (
         @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        p.AP_Products_ID AS [ProductID],
		p.Description + ' (' + ISNULL(p.Product_Code, '') + ')' AS [Description], 
		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) AS [Unit Price],
        ISNULL(tc.Tax_Rate, 0) as [ProdTaxRate]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
    WHERE p.AW_User_Companies_ID = @CompanyID AND
          p.Slu_AW_YesNo_Non_Stock_Item = 1 AND
          p.Slu_AW_Active_ID = 1
    ORDER BY [Description]



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Bond_Stock_Data
--Functionality :Select Bonded Stock Interface file data
--Parameters    :
--Date          :2010/09/08
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Select_Bond_Stock_Data
    (
        @CompanyID int,
        @CustCode varchar(50),
        @WarehouseNo varchar(50),
        @FilePrefix varchar(50),
        @FileDate varchar(20),
        @FileTime varchar(20),
        @ChkDates tinyint,
        @StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @MyDate varchar(20),
            @MyTime varchar(20),
            @TempDate varchar(20),
            @TempTime varchar(20),
            @RowCNT varchar(20)


    SET @MyDate = ''
    SET @MyTime = ''
    SET @TempDate = ''
    SET @TempTime = ''
    SET @RowCNT = 0


    ----------------------------------------------------------------
    --> Set File DATE
    ----------------------------------------------------------------
    IF ISNUMERIC(@FileDate) > 0 AND LEN(@FileDate) = 8
        BEGIN
            SET @MyDate = LEFT(@FileDate, 4) + '-' + SUBSTRING(@FileDate, 5,2) + '-' + RIGHT(@FileDate, 2)
        END
    ELSE
        BEGIN
            SELECT @TempDate = CONVERT(CHAR(10), getdate(), 121)

            SET @MyDate = @TempDate
        END

    ----------------------------------------------------------------
    --> Set File TIME
    ----------------------------------------------------------------
    IF ISNUMERIC(@FileTime) > 0 AND LEN(@FileTime) = 8
        BEGIN
            SET @FileTime = LEFT(@FileTime, 4) + '-' + SUBSTRING(@FileTime, 5,2) + '-' + RIGHT(@FileTime, 2)
        END
    ELSE
        BEGIN
            SELECT @TempTime = CONVERT(CHAR(10), getdate(), 108)

            SET @MyTime = @TempTime
        END


    ----------------------------------------------------------------
    --> Fetch the DATA
    ----------------------------------------------------------------
    SET @sql = ' SELECT '

    ----------------------------------------------------------------
    --> Goods Received into Bond - GRV and GRN
    ----------------------------------------------------------------
    IF @FilePrefix = 'RGB'
        BEGIN
            SELECT @RowCNT = CONVERT(varchar(20), COUNT(*))
            FROM AO_GRV gh
                INNER JOIN AO_GRV_Details gd
                    ON gh.AO_GRV_ID = gd.AO_GRV_ID
                INNER JOIN AP_Products p
                    ON gd.AP_Products_ID = p.AP_Products_ID
            WHERE gh.AW_User_Companies_ID = @CompanyID
              AND gh.Sys_AW_Transaction_Types_ID = 19
              AND gh.Date_Captured >= @StartDate
              AND gh.Date_Captured <= @EndDate

            SET @sql = @sql + '''' + @CustCode + '''' + ' AS [Customer], '
            SET @sql = @sql + ' ISNULL(gh.Supplier_Reference, '''') AS [Ref No], '
            SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), gh.Date_Captured, 121)) AS [Date], '
            SET @sql = @sql + '''' + @WarehouseNo + '''' + ' AS [Warehouse No], '
            SET @sql = @sql + '''' + @RowCNT + '''' + ' AS [Rows], '
            ---------------
            SET @sql = @sql + ' p.Product_Code AS [Product Code], '
            SET @sql = @sql + ' gd.Qty AS [Qty] '

            SET @sql = @sql + ' FROM AO_GRV gh '
            SET @sql = @sql + '     INNER JOIN AO_GRV_Details gd '
            SET @sql = @sql + '         ON gh.AO_GRV_ID = gd.AO_GRV_ID '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON gd.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + ' WHERE gh.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)
            SET @sql = @sql + '   AND (gh.Sys_AW_Transaction_Types_ID = 19 ' + ' '
            SET @sql = @sql + '    OR  gh.Sys_AW_Transaction_Types_ID = 20) ' + ' '
            SET @sql = @sql + '   AND gh.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '   AND gh.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '

            SET @sql = @sql + ' ORDER BY [Product Code] ASC '
        END

    ----------------------------------------------------------------
    --> Export Notification - Invoice and Refund
    ----------------------------------------------------------------
    ELSE
    IF @FilePrefix = 'EXP'
        BEGIN
            SELECT @RowCNT = CONVERT(varchar(20), COUNT(*))
            FROM AS_Transaction_Details d
            WHERE d.AS_Transactions_ID = @CompanyID


            SET @sql = @sql + '''' + @CustCode + '''' + ' AS [Customer], '
            SET @sql = @sql + '''' + @WarehouseNo + '''' + ' AS [Warehouse No], '
        	SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') + ''('' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + '')'' AS [CustomerNo], '
        	SET @sql = @sql + ' RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') AS [CustomerName], '
            SET @sql = @sql + ' ISNULL(c.Street_Address, '''') + '
            SET @sql = @sql + ' ISNULL(''  '' + c.Suburb, '''') + '
            SET @sql = @sql + ' ISNULL(''  '' + c.City, '''') AS [Address], '
            SET @sql = @sql + ' ISNULL(cn.Country_Code3, '''') + '
            SET @sql = @sql + ' ISNULL(''  '' + cn.Description, '''') AS [Country], '
            SET @sql = @sql + '''' + @FileDate + '''' + ' AS [ExportDate], '
            SET @sql = @sql + ' ''ROAD'' AS [TransportMethod], '
            SET @sql = @sql + ' '' '' AS [ForwarderName], '
            SET @sql = @sql + ' '' '' AS [ForwarderTel], '
        	SET @sql = @sql + ' ISNULL(h.Transaction_Number, '''') AS [Order No], '
            SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [OrderXref], '
            SET @sql = @sql + ' '' '' AS [UCRNo], '
            SET @sql = @sql + '''' + @RowCNT + '''' + ' AS [Rows], '
            ---------------
            SET @sql = @sql + ' p.Product_Code AS [Product Code], '
            SET @sql = @sql + ' d.Quantity AS [Qty] '

            SET @sql = @sql + ' FROM AS_Transactions h '
            SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
            SET @sql = @sql + '         ON h.AS_Transactions_ID = d.AS_Transactions_ID '
            SET @sql = @sql + '     INNER JOIN AC_Customers c '
            SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
            SET @sql = @sql + '     INNER JOIN Slu_AW_Countries cn '
            SET @sql = @sql + '         ON c.Slu_AW_Countries_ID = cn.Slu_AW_Countries_ID '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + ' WHERE h.AS_Transactions_ID = ' + CONVERT(varchar(10), @CompanyID)
        END

    ----------------------------------------------------------------
    --> XIB Issues - Invoice and Refund and Stock Transfers
    ----------------------------------------------------------------
    ELSE
    IF @FilePrefix = 'XIB'
        BEGIN
            SELECT @RowCNT = CONVERT(varchar(20), COUNT(*))
            FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c
                    ON h.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
            WHERE h.AW_User_Companies_ID = @CompanyID
              AND (h.Sys_AW_Transaction_Types_ID = 3
               OR  h.Sys_AW_Transaction_Types_ID = 23)
              AND c.Sys_AC_Account_Types_ID = 3
              AND LEN(ISNULL(c.Old_Customer_Number, '')) > 0
              AND h.Date_Captured >= @StartDate
              AND h.Date_Captured <= @EndDate

            SET @sql = @sql + '''' + @CustCode + '''' + ' AS [Customer], '
            SET @sql = @sql + '''' + @WarehouseNo + '''' + ' AS [Warehouse No], '
            ---------------
            SET @sql = @sql + '''' + @RowCNT + '''' + ' AS [Rows], '
            SET @sql = @sql + ' c.Old_Customer_Number AS [Warehouse No To], '
        	SET @sql = @sql + ' ISNULL(h.Transaction_Number, '''') AS [Order No], '
            SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), h.Date_Captured, 121)) AS [Date], '
            SET @sql = @sql + ' p.Product_Code AS [Product Code], '
            SET @sql = @sql + ' d.Quantity AS [Qty] '

            SET @sql = @sql + ' FROM AS_Transactions h '
            SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
            SET @sql = @sql + '         ON h.AS_Transactions_ID = d.AS_Transactions_ID '
            SET @sql = @sql + '     INNER JOIN AC_Customers c '
            SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)
            SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 ' + ' '
            SET @sql = @sql + '    OR  h.Sys_AW_Transaction_Types_ID = 4 ' + ' '
            SET @sql = @sql + '    OR  h.Sys_AW_Transaction_Types_ID = 23) ' + ' '
            SET @sql = @sql + '   AND c.Sys_AC_Account_Types_ID = 3 ' + ' '
            SET @sql = @sql + '   AND LEN(ISNULL(c.Old_Customer_Number, '''')) > 0 ' + ' '
            SET @sql = @sql + '   AND h.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '   AND h.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '

            SET @sql = @sql + ' ORDER BY [Product Code] ASC '
        END

    ----------------------------------------------------------------
    --> Bonded Stock Issues - Invoice and Refund and Stock Transfers
    ----------------------------------------------------------------
    ELSE
    IF @FilePrefix = 'ISS'
        BEGIN
            SELECT @RowCNT = CONVERT(varchar(20), COUNT(*))
            FROM AS_Transactions h
                INNER JOIN AS_Transaction_Details d
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
            WHERE h.AW_User_Companies_ID = @CompanyID
              AND (h.Sys_AW_Transaction_Types_ID = 3
               OR  h.Sys_AW_Transaction_Types_ID = 23)
              AND h.Date_Captured >= @StartDate
              AND h.Date_Captured <= @EndDate

            SET @sql = @sql + '''' + @CustCode + '''' + ' AS [Customer], '
            SET @sql = @sql + '''' + @WarehouseNo + '''' + ' AS [Warehouse No], '
            SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), h.Date_Captured, 121)) AS [Date], '
        	SET @sql = @sql + ' ISNULL(h.Transaction_Number, '''') AS [Order No], '
            SET @sql = @sql + '''' + @RowCNT + '''' + ' AS [Rows], '
            ---------------
            SET @sql = @sql + ' p.Product_Code AS [Product Code], '
            SET @sql = @sql + ' d.Quantity AS [Qty] '

            SET @sql = @sql + ' FROM AS_Transactions h '
            SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
            SET @sql = @sql + '         ON h.AS_Transactions_ID = d.AS_Transactions_ID '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)
            SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 ' + ' '
            SET @sql = @sql + '    OR  h.Sys_AW_Transaction_Types_ID = 4 ' + ' '
            SET @sql = @sql + '    OR  h.Sys_AW_Transaction_Types_ID = 23) ' + ' '
            SET @sql = @sql + '   AND h.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '   AND h.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '

            SET @sql = @sql + ' ORDER BY [Product Code] ASC '
        END

    ----------------------------------------------------------------
    --> Bonded Stock Adjustments - Adjustment and Stock Take-On
    ----------------------------------------------------------------
    ELSE
    IF @FilePrefix = 'BSA'
        BEGIN
            SELECT @RowCNT = CONVERT(varchar(20), COUNT(*))
            FROM AP_Inventory_Adjustments
            WHERE AW_User_Companies_ID = @CompanyID
              AND (Sys_AP_Adjustment_Types_ID = 1
               OR  Sys_AP_Adjustment_Types_ID = 6)
              AND New_On_Hand <> Previous_On_Hand
              AND Date_Captured >= @StartDate
              AND Date_Captured <= @EndDate

            SET @sql = @sql + '''' + @CustCode + '''' + ' AS [Customer], '
            SET @sql = @sql + '''' + @WarehouseNo + '''' + ' AS [Warehouse No], '
            SET @sql = @sql + ' CONVERT(varchar(30), a.AP_Inventory_Adjustments_ID) AS [No], '
            SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
            SET @sql = @sql + '''' + @RowCNT + '''' + ' AS [Rows], '
            ---------------
            SET @sql = @sql + ' p.Product_Code AS [Product Code], '
            SET @sql = @sql + ' ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) AS [Qty] '

            SET @sql = @sql + ' FROM AP_Inventory_Adjustments a '
            SET @sql = @sql + '     INNER JOIN AP_Products p '
            SET @sql = @sql + '         ON a.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)
            SET @sql = @sql + '   AND (a.Sys_AP_Adjustment_Types_ID = 1 ' + ' '
            SET @sql = @sql + '    OR  a.Sys_AP_Adjustment_Types_ID = 6) ' + ' '
            SET @sql = @sql + '   AND a.New_On_Hand <> a.Previous_On_Hand ' + ' '
            SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '   AND a.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '

            SET @sql = @sql + ' ORDER BY [Product Code] ASC '
        END

--     ELSE
--     IF @FilePrefix = 'TRO'        -- Bonded Stock Transfers Out
--         BEGIN
-- 
--         END

--     ELSE
--     IF @FilePrefix = 'TRI'        -- Bonded Stock Transfers In
--         BEGIN
-- 
--         END

    ----------------------------------------------------------------
    --> Stock on Hand - As at NOW
    ----------------------------------------------------------------
    ELSE
    IF @FilePrefix = 'SOH'
        BEGIN
            SELECT @RowCNT = CONVERT(varchar(20), COUNT(*))
            FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID
              AND On_Hand <> 0

            SET @sql = @sql + '''' + @CustCode + '''' + ' AS [Customer], '
            SET @sql = @sql + '''' + @WarehouseNo + '''' + ' AS [Warehouse No], '
            SET @sql = @sql + '''' + @MyDate + '''' + ' AS [Date], '
            SET @sql = @sql + '''' + @RowCNT + '''' + ' AS [Rows], '
            ---------------
            SET @sql = @sql + ' Product_Code AS [Product Code], '
            SET @sql = @sql + ' On_Hand AS [On Hand] '

            SET @sql = @sql + ' FROM AP_Products '
            SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)
            SET @sql = @sql + '   AND On_Hand <> 0 '
            SET @sql = @sql + ' ORDER BY [Product Code] ASC '
        END


    EXEC (@sql)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Bond_Stock_Log
--Purpose       :Fetch Bond Stock Log
--Date          :2010/09/09
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                        PROCEDURE sp_AP_Select_Bond_Stock_Log
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint = 0
	)

AS

SET NOCOUNT ON


        IF @SortOrder = 0        -- Sort Order by Date Transmitted
            BEGIN
                SELECT
                    l.File_Type AS [File Type],
                    l.Status AS [Status],
                    l.File_Location AS [File Location],
                    l.Computer AS [Computer],
                    l.Date_Captured AS [Transmit Date],
                    l.File_Date AS [File Date],
                    l.File_Time AS [File Time],
                    l.Row_CNT AS [Rows],
                    l.FTP_Login_URL AS [FTP URL],
                    l.FTP_User_Name AS [User Name],
                    l.FTP_Password AS [Password],
                    l.FTP_Folder AS [Folder],
                    u.UserName AS [User]
                FROM AP_Bond_Stock_Log l
                    LEFT JOIN AW_Users u
                        ON l.User_ID = u.AW_Users_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Date_Captured, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Date_Captured, @EndDate) >= 0)
                ORDER BY [Transmit Date]
            END
        ELSE
        IF @SortOrder = 1        -- Sort Order by Interface Type
            BEGIN
                SELECT
                    l.File_Type AS [File Type],
                    l.Status AS [Status],
                    l.File_Location AS [File Location],
                    l.Computer AS [Computer],
                    l.Date_Captured AS [Transmit Date],
                    l.File_Date AS [File Date],
                    l.File_Time AS [File Time],
                    l.Row_CNT AS [Rows],
                    l.FTP_Login_URL AS [FTP URL],
                    l.FTP_User_Name AS [User Name],
                    l.FTP_Password AS [Password],
                    l.FTP_Folder AS [Folder],
                    u.UserName AS [User]
                FROM AP_Bond_Stock_Log l
                    LEFT JOIN AW_Users u
                        ON l.User_ID = u.AW_Users_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Date_Captured, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Date_Captured, @EndDate) >= 0)
                ORDER BY [File Type], [Transmit Date]
            END
        ELSE
        IF @SortOrder = 2        -- Sort Order by File Date
            BEGIN
                SELECT
                    l.File_Type AS [File Type],
                    l.Status AS [Status],
                    l.File_Location AS [File Location],
                    l.Computer AS [Computer],
                    l.Date_Captured AS [Transmit Date],
                    l.File_Date AS [File Date],
                    l.File_Time AS [File Time],
                    l.Row_CNT AS [Rows],
                    l.FTP_Login_URL AS [FTP URL],
                    l.FTP_User_Name AS [User Name],
                    l.FTP_Password AS [Password],
                    l.FTP_Folder AS [Folder],
                    u.UserName AS [User]
                FROM AP_Bond_Stock_Log l
                    LEFT JOIN AW_Users u
                        ON l.User_ID = u.AW_Users_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Date_Captured, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Date_Captured, @EndDate) >= 0)
                ORDER BY [File Date]
            END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








--Description   :sp_AP_Select_Commission_Categories_As_PickList
--Purpose       :
--Functionality :Tables: Lup_AS_Commission_Categories
--Parameters    :
--Date          :2002/02/07
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE   PROCEDURE sp_AP_Select_Commission_Categories_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AS_Commission_Categories_ID AS [ID],
          [Description] as [Commission Category] 
	FROM Lup_AS_Commission_Categories
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   : sp_AP_Select_Commission_Groups_As_PickList
--Purpose       : 
--Functionality : Tables: Lup_AP_Commission_Groups
--Parameters    : 
--Date          : 2002/02/07
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE    PROCEDURE sp_AP_Select_Commission_Groups_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AP_Commission_Groups_ID AS [ID],
		   [Description] as [Commission Group] 
	FROM Lup_AP_Commission_Groups
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Customer_Contract_Prices
--Purpose       :Select Customer Contract Price data
--Functionality :
--Date          :2004/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :12/03/04 - Added Product Description and Product Code to table and
--              :           Removed JOIN with AP_Products for rs updateability
--RL	V6.0	:MinSaleQty - Contract price if minimum quantity sold 
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AP_Select_Customer_Contract_Prices]
    (
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)
   
	SET @sql = ' SELECT '
    SET @sql = @sql + ' cp.AC_Contract_Prices_ID AS [ContractID], '
    SET @sql = @sql + ' cp.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' cp.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' cp.[Description] AS [Product], '
    SET @sql = @sql + ' cp.Product_Code AS [Code], '
    SET @sql = @sql + ' cp.Start_Date AS [Starts], '
    SET @sql = @sql + ' cp.End_Date AS [Ends], '
    SET @sql = @sql + ' cp.Pack_Size AS [Unit], '
    SET @sql = @sql + ' cp.Unit_Price AS [Unit Price], '
    SET @sql = @sql + ' cp.Discount_Perc AS [Discount %], '
    SET @sql = @sql + ' cp.Discount_Amount AS [Discount], '
    SET @sql = @sql + ' cp.MinSaleQty AS [Min Sale Qty], '    
    SET @sql = @sql + ' cp.Slu_AW_Active_ID AS [Status] '

    SET @sql = @sql + ' FROM AC_Contract_Prices cp '
    SET @sql = @sql + ' WHERE cp.AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + '   AND cp.AC_Customers_ID = ' + CONVERT(varchar(20), @CustomerID) + ' '
    SET @sql = @sql + ' ORDER BY cp.[Description] '

SET NOCOUNT OFF

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Customer_Stock_Transfer_Details
--Purpose       :
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2	2016-10-03	RL	:Added Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Customer_Stock_Transfer_Details]
    (
        @CustomerID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

   SELECT 
        d.AP_Stock_Transfer_Details_ID AS [ID],
        d.AC_Customers_ID AS [CustomerID],
        d.AP_Products_ID AS [ProductID],
        d.Description AS [Product],
        d.Product_Code AS [Code],
        d.Unit_Price AS [Unit Price],
        d.Quantity AS [Qty],
        d.Back_Order AS [B/O],
        d.Discount_Amount AS [Discount],
        d.Amount AS [Amount],
--        Shipping_Cost AS [Shipping],
        d.Tax_Amount AS [Tax],
        d.Extended_Amount AS [Total],
        d.Tax_Rate AS [Tax Rate],
        d.Original_Price AS [Orig Price],
        d.Unit_Cost AS [UnitCost],
--        AP_Promotion_Products_ID AS [PromoProdID],
--        Promo_Price AS [Promo Price],
		d.Lup_AP_Product_Bins_ID As [BinID],
		b.Description As [Bin],
        d.Date_Captured AS [Captured],
        d.User_ID AS [UserID],
        d.AW_User_Companies_ID AS [CompanyID]
	FROM AP_Stock_Transfer_Details d
	LEFT OUTer JOIN Lup_AP_Product_Bins b
		ON d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
	WHERE d.AW_User_Companies_ID = @CompanyID AND
          d.AC_Customers_ID = @CustomerID
    ORDER BY d.Date_Captured DESC 


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Disabled_Products
--Purpose       :SELECT DISABLED Product IDs with ZERO STOCK in target DB
--Date          :2008/08/01
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Select_Disabled_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
              a.Slu_AW_Active_ID <> 1 AND
              b.AP_Products_ID IS NULL AND
              c.AP_Products_ID IS NULL AND
              d.AP_Products_ID IS NULL AND
              a.On_Hand = 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Discount_Categories_As_PickList
--Purpose       :
--Functionality :Tables: Lup_AC_Discount_Categories
--Parameters    :
--Date          :2002/02/07
--Authors       :TB
--MODS          :
--2004.4.0      :28/07/07 - Added ORDER BY [Description]
-------------------------------------------------------------------------------
CREATE      PROCEDURE sp_AP_Select_Discount_Categories_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AC_Discount_Categories_ID AS [ID],
          [Description] as [Discount Category] 
	FROM Lup_AC_Discount_Categories
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   : sp_AP_Select_Discount_Groups_As_PickList
--Purpose       : 
--Functionality : Tables: Lup_AP_Discount_Groups
--Parameters    : 
--Date          : 2002/02/09
--Authors       : TB
--MODS          :
--2004.4.0      :28/07/07 - Added ORDER BY [Description]
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AP_Select_Discount_Groups_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AP_Discount_Groups_ID AS [ID],
		   [Description] as [Discount Groups] 
	FROM Lup_AP_Discount_Groups
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Duplicate_Product_Codes
--Purpose       :SELECT DUPLICATE Product Codes with ZERO STOCK in target DB
--Date          :2007/05/03
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Select_Duplicate_Product_Codes
	(
        @CompanyID int
	)

AS

SET NOCOUNT ON

    
        SELECT Product_Code AS [Code],
               count(*) AS [CNT]
        FROM AP_Products
        WHERE AW_User_Companies_ID = @CompanyID AND
              On_Hand = 0
        GROUP BY Product_Code
        HAVING count(*) > 1











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Enterprise_Stock
--Purpose       :SELECT Enterprise Slow Moving Stock
--Date          :2006/10/05
--Authors       :TB
--MODS:         :
--2004.4.7      :19/09/09 - Added ISNULL(LastSaleDate) validation to also include
--              :           products NEVER SOLD and removed ACTIVE validation
--              :           to synchronize with sp_RPT_AP_Slow_Moving_Inventory
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Select_Enterprise_Slow_Moving_Stock
	(
        @CompanyID int,
        @StartDate as datetime,
        @Filter varchar(100),
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand]'

    SET @sql = @sql + ' FROM AP_Products p '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
--    SET @sql = @sql + '   AND p.Last_Sale_Date <= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (p.Last_Sale_Date IS NULL OR CONVERT(varchar(30), CONVERT(float, p.Last_Sale_Date)) < ' +
                       '''' + CONVERT(varchar(30), CONVERT(float, @StartDate)) + '''' + ') '
--    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.On_Hand > 0 '
        END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Enterprise_Stock
--Purpose       :SELECT Enterprise Stock
--Date          :2006/05/23
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Select_Enterprise_Stock
	(
        @CompanyID int,
        @Filter varchar(100),
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand]'

    SET @sql = @sql + ' FROM AP_Products p '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
        END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Enterprise_Stock_MSL
--Purpose       :SELECT Enterprise Stock Min Stock Level
--Date          :2008/12/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Select_Enterprise_Stock_MSL
	(
        @CompanyID int,
        @Filter varchar(100),
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL]'

    SET @sql = @sql + ' FROM AP_Products p '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
        END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Enterprise_Stock_Replenish
--Purpose       :SELECT Enterprise Stock Replenishment
--Date          :2008/12/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Select_Enterprise_Stock_Replenish
	(
        @CompanyID int,
        @Filter varchar(100),
        @Sort int,
        @NonStock int,
        @Reserved int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.[Description] AS [Filter], '


--> QTY to ORDER
    IF @Reserved = 1
        BEGIN
            SET @sql = @sql + ' CASE WHEN  '
            SET @sql = @sql + ' (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0))) > 0 '
            SET @sql = @sql + ' THEN  '
            SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0) ) '
            SET @sql = @sql + ' ELSE NULL '
            SET @sql = @sql + ' END '
            SET @sql = @sql + ' AS [ToOrder] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' CASE WHEN  '
            SET @sql = @sql + ' (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (ISNULL(p.On_Hand, 0) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0))) > 0 '
            SET @sql = @sql + ' THEN  '
            SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (ISNULL(p.On_Hand, 0) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0) ) '
            SET @sql = @sql + ' ELSE NULL '
            SET @sql = @sql + ' END '
            SET @sql = @sql + ' AS [ToOrder] '
        END


    SET @sql = @sql + ' FROM AP_Products p '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


--------------------------------------------------------
--> (MSL - (On-Hand + On-Order)) > 0 (Qty to Order)
--------------------------------------------------------
    IF @Reserved = 1
        BEGIN
            SET @sql = @sql + '   AND (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '        (CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) + '
            SET @sql = @sql + '         ISNULL(( '
            SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '             FROM AO_Order_Details od '
            SET @sql = @sql + '                 INNER JOIN AO_Orders o '
            SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '             WHERE o.Date_Ordered IS NOT NULL AND '
            SET @sql = @sql + '                   o.Complete <> 1 AND '
            SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '         ), 0))) > 0 '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '   AND (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '        (ISNULL(p.On_Hand, 0) + '
            SET @sql = @sql + '         ISNULL(( '
            SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '             FROM AO_Order_Details od '
            SET @sql = @sql + '                 INNER JOIN AO_Orders o '
            SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '             WHERE o.Date_Ordered IS NOT NULL AND '
            SET @sql = @sql + '                   o.Complete <> 1 AND '
            SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '         ), 0))) > 0 '
        END
-----------------------------------------------------


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Enterprise_Stock_Replenish_Max
--Purpose       :SELECT Enterprise Stock Replenish Max Order Qty
--Date          :2009/07/23
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Select_Enterprise_Stock_Replenish_Max
	(
        @CompanyID int,
        @Filter varchar(100),
        @Sort int,
        @NonStock int,
        @Overstocked int,
        @Reserved int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.[Description] AS [Filter], '

--> QTY to ORDER
    IF @Reserved = 1
        BEGIN
            SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) - ((ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) AS [MaxOQTY] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) - ISNULL(p.On_Hand, 0) AS [MaxOQTY] '
        END

    SET @sql = @sql + ' FROM AP_Products p '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '
    SET @sql = @sql + '   AND ISNULL(p.Max_Order_Qty, 0) <> 0 '


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Overstocked = 1
        BEGIN
            IF @Reserved = 1
                BEGIN
                    SET @sql = @sql + ' AND ISNULL(p.Max_Order_Qty, 0) - ((ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) > 0 '
                END
            ELSE
                BEGIN
                    SET @sql = @sql + ' AND ISNULL(p.Max_Order_Qty, 0) - ISNULL(p.On_Hand, 0) > 0 '
                END
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Export_Contract_Products
--Purpose       :Select Customer Contract Products to export
--Date          :2004/04/08
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	:MinSaleQty - Contract price if minimum quantity sold 
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Export_Contract_Products]
    (
        @CustomerID int,
       	@CompanyID int
    )
AS

SET NOCOUNT ON

    SELECT
        AP_Products_ID AS [ProductID],
        ISNULL([Description], '') AS [Product],
        ISNULL(Product_Code, '') AS [Code],
        ISNULL(CONVERT(CHAR(10), Start_Date, 121), '') AS [Starts],
        ISNULL(CONVERT(CHAR(10), End_Date, 121), '') AS [Ends],
        ISNULL(Pack_Size, 1) AS [Unit],
        ISNULL(Unit_Price, 0) AS [Unit Price],
        ISNULL(Discount_Perc, 0) AS [Discount %],
        ISNULL(Discount_Amount, 0) AS [Discount],
        ISNULL(MinSaleQty, 0) AS [MinSaleQty]        
--        ISNULL(Slu_AW_Active_ID, 1) AS [Status]
    FROM AC_Contract_Prices
    WHERE AW_User_Companies_ID = @CompanyID AND
          AC_Customers_ID = @CustomerID
    ORDER BY ISNULL([Description], '')

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description   :sp_AP_Select_Filtered_Contract_Products
--Functionality :Returns products matching search criteria in Contract Pricing
--Date          :2004/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :05/09/04 - Added select ACTIVE products only
--2004.3.8      :07/05/08 - Added Standard Cost field to enable replacement
--              :           of Last or Average Cost when Export/Import data
----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Select_Filtered_Contract_Products
    (
       @CompanyID int = -1,
       @FilterType int = -1,
       @FilterValue int = -1,
       @Criteria1 varchar(100) = '',
       @Criteria2 varchar(100) = '',
       @Criteria3 varchar(100) = ''
    )

AS

SET NOCOUNT ON

   DECLARE
        @Criteria varchar(2000), 
        @SQL varchar(6000),
        @FilterString varchar(2000),
        @OrderBy varchar(100)

   SET @Criteria = ''
	
   IF @CompanyID > -1   
--       BEGIN
--          IF @Criteria = '' 
--             SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
--          ELSE
--             SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
--       END

      BEGIN
         IF @Criteria = '' 
            BEGIN
                SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + ' '
                SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '
            END
         ELSE
            BEGIN
                SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + ' '
                SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '
            END
      END

   IF @Criteria3 <> '' and @criteria2 <> '' and @criteria1 <> ''
      BEGIN
        IF @Criteria = '' 
           SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                   (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
        ELSE
            SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                              (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria2 <> '' and @criteria1 <> '' 
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
										(p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                                   (p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria1 <> ''   
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    SET @SQL = ' SELECT '
    SET @SQL = @SQL + '    p.AP_Products_ID as [ProductID], '
    SET @SQL = @SQL + '    p.Default_Supplier_ID AS [SupplierID], '
    SET @SQL = @SQL + '    p.Description as [Product], ' 
    SET @SQL = @SQL + '    p.Product_Code as [Code], '  
    SET @SQL = @SQL + '    p.On_Hand as [On Hand], '
    SET @SQL = @SQL + '    dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1,getdate()) as [Selling 1], '
    SET @SQL = @SQL + '    dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2, Price2_Effective_Date, Price2_Price2,getdate()) as [Selling 2], '
    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 + '    dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost) as [GP %], '
    SET @SQL = @SQL + '    p.Min_Stock_Level AS [MSL],  '
    SET @SQL = @SQL + '    p.Min_Order_Qty AS [MIN],  '
    SET @SQL = @SQL + '    p.Max_Order_Qty AS [MAX],  '
    SET @SQL = @SQL + '    p.Service_Level AS [SL], '
    SET @SQL = @SQL + '    p.Pack_Size AS [Pack], '
    SET @SQL = @SQL + '    p.Job_Reserved AS [Job Res], '
    SET @SQL = @SQL + '    p.Sales_Order_Reserved AS [S/O Res], '
    SET @SQL = @SQL + '    p.Quote_Reserved AS [Quot Res], '
    SET @SQL = @SQL + '    uof.Description AS [Unit],  '
    SET @SQL = @SQL + '    p.Measure AS [Measure],  '
    SET @SQL = @SQL + '    p.Manufacturer_Code AS [Manuf Code],  '
    SET @SQL = @SQL + '    p.Manufacturer_Description AS [Manuf Description],  '
    SET @SQL = @SQL + '    pt.Description AS [Type],  '
    SET @SQL = @SQL + '    pg.Description AS [Group],  '
    SET @SQL = @SQL + '    pd.Description AS [Department],  '
    SET @SQL = @SQL + '    pl.Description AS [Location],  '
    SET @SQL = @SQL + '    p.Alternate_Code1 AS [Alt Code1],  '
    SET @SQL = @SQL + '    p.Alternate_Code2 AS [Alt Code2],  '
    SET @SQL = @SQL + '    p.Supercession AS [SuperCede],  '
    SET @SQL = @SQL + '    p.Pack_Volume AS [Volume],  '
    SET @SQL = @SQL + '    mc.Description AS [Mass Code],  '
    SET @SQL = @SQL + '    p.Pack_Mass AS [Pack Mass],  '
    SET @SQL = @SQL + '    p.Strength AS [Strength],  '
    SET @SQL = @SQL + '    p.Last_Sale_Date AS [Last Sale],  '
    SET @SQL = @SQL + '    p.Serial_Number AS [Serial No],  '
    SET @SQL = @SQL + '    p.Date_Captured AS [Date],  '
    SET @SQL = @SQL + '    p.User_ID AS [UserID],  '
    SET @SQL = @SQL + '    p.AW_User_Companies_ID AS [CompanyID] '
    SET @SQL = @SQL + ' FROM AP_Products p   '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Mass_Codes mc '
    SET @SQL = @SQL + '     ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Locations pl '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Departments pd '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Types pt '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Groups pg '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Slu_AP_Units_Of_Measure uof '
    SET @SQL = @SQL + '     ON p.Slu_AP_Units_Of_Measure_ID = uof.Slu_AP_Units_Of_Measure_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Manufacturers pm '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @SQL = @SQL + @Criteria + ' '

    BEGIN	
    	IF @FilterType = 0 --> All
    		SET @FilterString = ''
    
     	IF @FilterType = 1 --> Suppliers
    		SET @FilterString = 'AND p.AP_Products_ID in (SELECT AP_Products_ID
    				FROM AP_Products_Suppliers
    				WHERE AO_Suppliers_ID = ' + Convert(Varchar(10),@FilterValue) + ')'
    	ELSE 
    	IF @FilterType = 2 --> Manufacturer
    		SET @FilterString = 'AND p.Lup_AP_Product_Manufacturers_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 3 --> Type
    		SET @FilterString = 'AND p.Lup_AP_Product_Types_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 4 --> Group
    		SET @FilterString = 'AND p.Lup_AP_Product_Groups_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 5 --> Department
    		SET @FilterString = 'AND p.Lup_AP_Product_Departments_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 6 --> Location
    		SET @FilterString = 'AND p.Lup_AP_Product_Locations_ID = ' + Convert(Varchar(10),@FilterValue) 
    	
    	ELSE
    	IF @FilterType = 7 --> With Stock On Hand
    		SET @FilterString = 'AND p.On_Hand > 0 '
    
    END 

    SET @OrderBy = ' ORDER BY p.Description '

    BEGIN
    	IF @FilterString <> '' 
            EXEC (@SQL + @FilterString + @OrderBy)
    	IF @FilterString = '' 
            EXEC (@SQL + @OrderBy)
    END 



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AP_Select_Filtered_Products
--Functionality :Fetches products matching search criteria in Stock Adjustments
--Functionality :NB: Used by both Purchase Orders and Stock Adjustments
--Date          :2002/04/09
--Authors       :TB
--MODS          :10/11/03 - Fixed @Criteria fieldnames in the 3 WHERE strings
--              :           fixed Bitwise Operators in @Criteria WHERE clauses
--              :10/11/03 - Rebuild @SQL string and removed redundant fields
--              :05/09/04 - Added select ACTIVE products only
--              :05/09/04 - Added JOIN to Default Supplier
--2004.3.7      :22/11/07 - Added [Std. Cost], [Std. Disc1], [Std. Disc2] using
--              :           Standard Cost as default purchase price
--2004.4.8      :28/03/10 - Added WILDCARD Pattern Matching using _ (underscore) character
--              :           in Normal Search (@SearchType = 0) for the 3 @Filter(n)
--        ****  :02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section and reworked script
--        ****  :02/09/10 - REMOVED WILDCARD search
--V6.0	RL		:2014-10-28 - Reworked Job, Quote And Sales Order Reserved
--V6.2	RL		:2015-11-29 - Added Product Bins
----------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Filtered_Products]
    (
       @CompanyID		int = -1,
       @FilterType		int = -1,
       @FilterValue		int = -1,
       @Criteria1		varchar(100) = '',
       @Criteria2		varchar(100) = '',
       @Criteria3		varchar(100) = '',
       @chkQtyOnHand	tinyint = 0
    )

AS

SET NOCOUNT ON

   DECLARE
        @Criteria varchar(4000), 
        @SQL varchar(8000),
        @Wildcard varchar(50),
        @wc1 varchar(50),
        @wc2 varchar(50)


    SET @Criteria = ''
    SET @Wildcard = ''
    SET @wc1 = ''
    SET @wc2 = ''


--     --> WILDCARD Pattern Matching using _ (underscore) character
--     IF LTRIM(RTRIM(@Criteria1)) <> '' AND ISNUMERIC(@Criteria1) > 0
--         BEGIN
--             SET @wc1 = REPLACE(LTRIM(RTRIM(@Criteria1)), '/', '')
--             SET @wc2 = REPLACE(@wc1, '-', '')
--             IF LEN(@wc2) >= 5 AND ISNUMERIC(LEFT(@wc2, 3)) > 0
--                 BEGIN
--                     SET @Wildcard = 
--                         CASE LEN(@wc2)
--                              WHEN 5 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2)
--                              WHEN 6 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 1)
--                              WHEN 7 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '_' + RIGHT(@wc2, 2)
--                              WHEN 8 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '__' + RIGHT(@wc2, 2)
--                         END    
--                     SET @Wildcard = '''%' + @Wildcard + '%'''
--                 END
--         END


    SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + 
                    ' AND p.Slu_AW_Active_ID = 1 '                     --> INCLUDE only ACTIVE products (06/03/05)


    IF @Criteria3 <> ''
        BEGIN
            SET @Criteria3 = '''%' +  @Criteria3 + '%'''
        END

    IF @Criteria2 <> ''
        BEGIN
            SET @Criteria2 = '''%' +  @Criteria2 + '%'''
        END

    IF @Criteria1 <> ''
        BEGIN
            SET @Criteria1 = '''%' +  @Criteria1 + '%'''
        END


    IF @Criteria3 <> ''
        BEGIN
            SET @Criteria = @Criteria +
                            ' AND (p.Description Like ' + @Criteria3 + ' and p.Description Like ' + @Criteria2 + ' and p.Description Like ' + @Criteria1 + ') OR
                                  (p.Product_Code Like ' + @Criteria3 + ' and p.Product_Code Like ' + @Criteria2 + ' and p.Product_Code Like ' + @Criteria1 + ' )'
        END
    ELSE
    IF @Criteria2 <> ''
        BEGIN
            SET @Criteria = @Criteria +
                            ' AND (p.Description Like ' + @Criteria2 + ' and p.Description Like ' + @Criteria1 + ') OR
                                  (p.Product_Code Like ' + @Criteria2 + ' and p.Product_Code Like ' + @Criteria1 + ' )'
        END
    ELSE
    IF @Criteria1 <> ''        --02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section
        BEGIN
--             IF @Wildcard <> ''
--                 BEGIN
--                     SET @Criteria = @Criteria + ' AND (p.Description Like ' + @Criteria1 + ' OR p.Product_Code Like ' + @Criteria1 + ' OR p.Description Like ' + @Wildcard + ' OR p.Product_Code Like ' + @Wildcard + ' )'
--                 END
--             ELSE
--                 BEGIN
                    SET @Criteria = @Criteria + ' AND (p.Description Like ' + @Criteria1 + ' OR p.Product_Code Like ' + @Criteria1 + ' )'
--                 END
        END


    SET @SQL = ' SELECT '
    SET @SQL = @SQL + ' p.AP_Products_ID as [ID], '
    SET @SQL = @SQL + ' p.Default_Supplier_ID AS [Supplier ID], '
    SET @SQL = @SQL + ' p.Description, ' 
    SET @SQL = @SQL + ' p.Product_Code as [Code], '
    SET @SQL = @SQL + ' s.Supplier_Name as [Default Supplier], ' 
    --Product Bins
    SET @SQL = @SQL + ' p.On_Hand as [Total On Hand], '
    SET @SQL = @SQL + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Consignment Stock], '
    SET @SQL = @SQL + ' pb.Lup_AP_Product_Bins_ID as [BinID], '
    SET @SQL = @SQL + ' pb.Description as [Bin], '
    SET @SQL = @SQL + ' b.On_Hand as [On Hand], '
    SET @SQL = @SQL + ' p.Last_Cost AS [Last Cost], '
    SET @SQL = @SQL + ' p.Average_Cost AS [Avg Cost],  '

    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1,getdate()) as [Selling 1], '
    SET @SQL = @SQL + ' p.Standard_Cost AS [Std. Cost], '
    SET @SQL = @SQL + ' p.Standard_Disc1 AS [Std. Disc1],  '
    SET @SQL = @SQL + ' p.Standard_Disc2 AS [Std. Disc2], '

    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2, Price2_Effective_Date, Price2_Price2,getdate()) as [Selling 2], '
    SET @SQL = @SQL + ' dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost) as [GP %], '
    SET @SQL = @SQL + ' p.Min_Stock_Level AS [MSL],  '
    SET @SQL = @SQL + ' p.Min_Order_Qty AS [MIN],  '
    SET @SQL = @SQL + ' p.Max_Order_Qty AS [MAX],  '
    SET @SQL = @SQL + ' p.Service_Level AS [SL], '
    SET @SQL = @SQL + ' p.Pack_Size AS [Pack], '
    --SET @SQL = @SQL + ' p.Job_Reserved AS [Job Res], '
    --SET @SQL = @SQL + ' p.Sales_Order_Reserved AS [S/O Res], '
    --SET @SQL = @SQL + ' p.Quote_Reserved AS [Quot Res], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) AS [Job Res], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) AS [Quot Res], '
    
    SET @SQL = @SQL + ' uof.Description AS [Unit],  '
    SET @SQL = @SQL + ' p.Measure AS [Measure],  '
    SET @SQL = @SQL + ' p.Manufacturer_Code AS [Manuf Code],  '
    SET @SQL = @SQL + ' p.Manufacturer_Description AS [Manuf Description],  '
    SET @SQL = @SQL + ' pt.Description AS [Type],  '
    SET @SQL = @SQL + ' pg.Description AS [Group],  '
    SET @SQL = @SQL + ' pd.Description AS [Department],  '
    SET @SQL = @SQL + ' pl.Description AS [Location],  '
    SET @SQL = @SQL + ' p.Alternate_Code1 AS [Alt Code1],  '
    SET @SQL = @SQL + ' p.Alternate_Code2 AS [Alt Code2],  '
    SET @SQL = @SQL + ' p.Supercession AS [SuperCede],  '
    SET @SQL = @SQL + ' p.Pack_Volume AS [Pack Volume],  '
    SET @SQL = @SQL + ' mc.Description AS [Mass Code],  '
    SET @SQL = @SQL + ' p.Pack_Mass AS [Pack Mass],  '
    SET @SQL = @SQL + ' p.Strength AS [Strength],  '
    SET @SQL = @SQL + ' p.Last_Sale_Date AS [Last Sale],  '
    SET @SQL = @SQL + ' p.Serial_Number AS [Serial No],  '
    SET @SQL = @SQL + ' p.Date_Captured AS [Date],  '
    SET @SQL = @SQL + ' p.User_ID AS [UserID],  '
    SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID] '
    SET @SQL = @SQL + ' FROM AP_Products p   '

    SET @SQL = @SQL + ' LEFT OUTER JOIN AO_Suppliers s '
    SET @SQL = @SQL + '     ON s.AO_Suppliers_ID = p.Default_Supplier_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Mass_Codes mc '
    SET @SQL = @SQL + '     ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Locations pl '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Departments pd '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Types pt '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Groups pg '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Slu_AP_Units_Of_Measure uof '
    SET @SQL = @SQL + '     ON p.Slu_AP_Units_Of_Measure_ID = uof.Slu_AP_Units_Of_Measure_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Manufacturers pm '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    --> Product Bins
    SET @SQL = @SQL + ' LEFT OUTER JOIN AP_Products_Bins b '
    SET @SQL = @SQL + '     ON p.AP_Products_ID = b.AP_Products_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Bins pb '
    SET @SQL = @SQL + '     ON pb.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID '


    SET @SQL = @SQL + @Criteria


 	IF @FilterType = 1    --> Suppliers
        SET @SQL = @SQL + ' AND p.AP_Products_ID in (SELECT AP_Products_ID FROM AP_Products_Suppliers WHERE AO_Suppliers_ID = ' + Convert(Varchar(10), @FilterValue) + ') '
	ELSE 
	IF @FilterType = 2    --> Manufacturer
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Manufacturers_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 3    --> Type
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Types_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 4    --> Group
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Groups_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 5    --> Department
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Departments_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 6    --> Location
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Locations_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE
	IF @FilterType = 7 --> Below MSL
		SET @SQL = @SQL + ' AND p.Min_Stock_Level > 0  AND p.On_Hand <= p.Min_Stock_Level'
	ELSE
	IF @FilterType = 10 --> Bin
		SET @SQL = @SQL + ' AND pb.Lup_AP_Product_Bins_ID = ' + Convert(Varchar(10), @FilterValue) 
		
	IF @chkQtyOnHand = 1
	BEGIN
		SET @SQL = @SQL + ' AND b.On_Hand <> 0'
		SET @SQL = @SQL + ' AND p.On_Hand <> 0'
	END

    SET @SQL = @SQL + ' Order By p.Description, pb.Description '
    
    EXEC (@SQL)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--sp_AP_Select_Filtered_Promotion_Products 1, 0, 0, '165', '', ''

----------------------------------------------------------------------------
--Description   :sp_AP_Select_Filtered_Promotion_Products
--Functionality :Returns products matching search criteria in Promotions Manager
--Date          :2004/02/16
--Authors       :TB
--Version       :1.0.0
--MODS          :05/09/04 - Added select ACTIVE products only
----------------------------------------------------------------------------

CREATE                PROCEDURE sp_AP_Select_Filtered_Promotion_Products
    (
       @CompanyID int = -1,
       @FilterType int = -1,
       @FilterValue int = -1,
       @Criteria1 varchar(100) = '',
       @Criteria2 varchar(100) = '',
       @Criteria3 varchar(100) = ''
    )

AS

SET NOCOUNT ON

   DECLARE @Criteria varchar(2000), 
           @SQL varchar(6000),
           @FilterString varchar(2000),
           @StartDate datetime,
           @EndDate datetime

    SET @EndDate = getdate()
    SET @StartDate = DATEADD(Week, -24, @EndDate)

-- SET @CompanyID = 1
-- SET @FilterType = 0
-- SET @FilterValue = 0
-- SET @Criteria1 = '165'
-- SET @Criteria2  = ''
-- SET @Criteria3 = ''

       SET @Criteria = ''
    	
       IF @CompanyID > -1   
--           BEGIN
--              IF @Criteria = '' 
--                 SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
--              ELSE
--                 SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
--           END

          BEGIN
             IF @Criteria = '' 
                BEGIN
                    SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + ' '
                    SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '
                END
             ELSE
                BEGIN
                    SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + ' '
                    SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '
                END
          END

       IF @Criteria3 <> '' and @criteria2 <> '' and @criteria1 <> ''
          BEGIN
            IF @Criteria = '' 
               SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                       (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                                  (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
            END
    
        ELSE
        IF @Criteria2 <> '' and @criteria1 <> '' 
            BEGIN
                IF @Criteria = '' 
                    SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
    										(p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
                ELSE
                    SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                                       (p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
            END
    
        ELSE
        IF @Criteria1 <> ''   
            BEGIN
                IF @Criteria = '' 
                    SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%'')'
                ELSE
                    SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%''))'
            END
    
    
        SET @SQL = ' SELECT '
        SET @SQL = @SQL + '    p.AP_Products_ID as [ID], '
        SET @SQL = @SQL + '    p.Default_Supplier_ID AS [SupplierID], '
        SET @SQL = @SQL + '    p.Description AS [Product], ' 
        SET @SQL = @SQL + '    p.Product_Code AS [Code], '  
        SET @SQL = @SQL + '    CONVERT(CHAR(10), p.Last_Sale_Date, 121) AS [Last Sale],  '

    --> Sold Qty
        SET @SQL = @SQL + '   ( SELECT
                                CASE WHEN SUM(d.Quantity) IS NULL
                                     THEN 0
                                     ELSE SUM(d.Quantity)
                                     END
                                FROM AS_Transaction_Details d
                                    INNER JOIN AS_Transactions h
                                        ON d.AS_Transactions_ID = h.AS_Transactions_ID
                                WHERE d.AP_Products_ID = p.AP_Products_ID AND
                                     (h.Transaction_Date > ' + '''' + CONVERT(varchar(20), @StartDate) + ''' AND
                                      h.Transaction_Date <=  ' + '''' + CONVERT(varchar(20), @EndDate) + ''' ) AND
                                     (h.Sys_AW_Transaction_Types_ID = 3 OR
                                      h.Sys_AW_Transaction_Types_ID = 4)) AS [Sold], '

        SET @SQL = @SQL + '    p.On_Hand AS [On Hand], '

    --> On Order
        SET @SQL = @SQL + '   ( SELECT
                                CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) IS NULL
                                     THEN 0
                                     ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
                                     END
                                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 = p.AP_Products_ID ) AS [Ords], '

    --> Pending Orders
        SET @SQL = @SQL + '   ( SELECT
                                CASE WHEN (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty)) IS NULL
                                     THEN 0
                                     ELSE (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty))
                                     END
                                FROM AO_Order_Details od
                                    INNER JOIN AO_Orders o
                                        ON od.AO_Orders_ID = o.AO_Orders_ID
                                WHERE o.Date_Ordered IS NULL AND
                                      od.AP_Products_ID = p.AP_Products_ID ) AS [Pend], '
    
        SET @SQL = @SQL + '    dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Selling 1], '
        SET @SQL = @SQL + '    dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Selling 2], '

        SET @SQL = @SQL + '    p.Last_Cost AS [Last Cost], '
        SET @SQL = @SQL + '    p.Average_Cost AS [Avg Cost],  '
    
        SET @SQL = @SQL + '    dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), p.Last_Cost) as [GP %], '
        SET @SQL = @SQL + '    p.Min_Stock_Level AS [MSL],  '
        SET @SQL = @SQL + '    p.Min_Order_Qty AS [MIN],  '
        SET @SQL = @SQL + '    p.Max_Order_Qty AS [MAX],  '
        SET @SQL = @SQL + '    p.Service_Level AS [SL], '
        SET @SQL = @SQL + '    p.Pack_Size AS [Pack] '
        SET @SQL = @SQL + ' FROM AP_Products p '
    
    
        SET @SQL = @SQL + @Criteria + ' '
    
        BEGIN	
        	IF @FilterType = 0 --> All
        		SET @FilterString = ''
        
         	IF @FilterType = 1 --> Suppliers
        		SET @FilterString = 'AND p.AP_Products_ID in (SELECT AP_Products_ID
            				FROM AP_Products_Suppliers
            				WHERE AO_Suppliers_ID = ' + Convert(Varchar(10),@FilterValue) + ')'
        	ELSE 
        	IF @FilterType = 2 --> Manufacturer
        		SET @FilterString = 'AND p.Lup_AP_Product_Manufacturers_ID = ' + Convert(Varchar(10),@FilterValue) 
        
        	ELSE 
        	IF @FilterType = 3 --> Type
        		SET @FilterString = 'AND p.Lup_AP_Product_Types_ID = ' + Convert(Varchar(10),@FilterValue) 
        
        	ELSE 
        	IF @FilterType = 4 --> Group
        		SET @FilterString = 'AND p.Lup_AP_Product_Groups_ID = ' + Convert(Varchar(10),@FilterValue) 
        
        	ELSE 
        	IF @FilterType = 5 --> Department
        		SET @FilterString = 'AND p.Lup_AP_Product_Departments_ID = ' + Convert(Varchar(10),@FilterValue) 
        
        	ELSE 
        	IF @FilterType = 6 --> Location
        		SET @FilterString = 'AND p.Lup_AP_Product_Locations_ID = ' + Convert(Varchar(10),@FilterValue) 
        	
        	ELSE
        	IF @FilterType = 7 --> Below MSL
        		SET @FilterString = 'AND p.Min_Stock_Level > 0  AND p.On_Hand <= p.Min_Stock_Level'
        
        END 

        IF @FilterString = ''
            BEGIN
                EXEC (@SQL)
            END
        ELSE
            BEGIN
                EXEC (@SQL + @FilterString)
            END


SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AP_Select_Filtered_Sales_Order_Products
--Functionality :Returns products matching search criteria in Sales Orders
--Date          :2008/06/04
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Select_Filtered_Sales_Order_Products
    (
       @CompanyID int = -1,
       @FilterType int = -1,
       @FilterValue int = -1,
       @Criteria1 varchar(100) = '',
       @Criteria2 varchar(100) = '',
       @Criteria3 varchar(100) = ''
    )

AS

SET NOCOUNT ON

   DECLARE
        @Criteria varchar(4000), 
        @sql varchar(8000),
        @FilterString varchar(4000)

   SET @Criteria = ''
	
   IF @CompanyID > -1   
--       BEGIN
--          IF @Criteria = '' 
--             SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
--          ELSE
--             SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
--       END

      BEGIN
         IF @Criteria = '' 
            BEGIN
                SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + ' '
--                SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '
            END
         ELSE
            BEGIN
                SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + ' '
--                SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '
            END
      END

   IF @Criteria3 <> '' and @criteria2 <> '' and @criteria1 <> ''
      BEGIN
        IF @Criteria = '' 
           SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                   (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
        ELSE
            SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                              (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria2 <> '' and @criteria1 <> '' 
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
										(p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                                   (p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria1 <> ''   
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    SET @Criteria = @Criteria + ' AND p.Slu_AW_Active_ID = 1 '

    SET @sql = ' SELECT '
    SET @sql = @sql + '    p.AP_Products_ID as [ID], '
    SET @sql = @sql + '    p.Default_Supplier_ID AS [Supplier ID], '
    SET @sql = @sql + '    p.Description AS [Product], ' 
    SET @sql = @sql + '    p.Product_Code as [Code], '
    SET @sql = @sql + '    p.On_Hand as [On Hand], '
    SET @sql = @sql + '    p.Pack_Size AS [Pack], '
    SET @sql = @sql + '    p.Pack_Mass AS [Mass], '
    SET @sql = @sql + '    mc.Description AS [Mass Code], '
    SET @sql = @sql + '    p.Pack_Volume AS [Volume], '
    SET @sql = @sql + '    um.Description AS [Measure], '
    SET @sql = @sql + '    s.Supplier_Name as [Default Supplier], ' 
    SET @sql = @sql + '    dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1,getdate()) as [Selling 1], '
    SET @sql = @sql + '    p.Standard_Disc1 AS [Std. Disc1], '
    SET @sql = @sql + '    p.Standard_Disc2 AS [Std. Disc2], '
--    SET @sql = @sql + '    p.Last_Cost AS [Last Cost], '
--    SET @sql = @sql + '    p.Average_Cost AS [Avg Cost], '
--    SET @sql = @sql + '    p.Standard_Cost AS [Std. Cost], '
    SET @sql = @sql + '    dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2, Price2_Effective_Date, Price2_Price2,getdate()) as [Selling 2], '
    SET @sql = @sql + '    p.Last_Sale_Date AS [Last Sale], '
    SET @sql = @sql + '    p.Alternate_Code1 AS [Alt Code1], '
    SET @sql = @sql + '    p.Alternate_Code2 AS [Alt Code2], '
    SET @sql = @sql + '    p.Supercession AS [SuperCede], '
    SET @sql = @sql + '    p.Manufacturer_Code AS [Manuf Code], '
    SET @sql = @sql + '    p.Manufacturer_Description AS [Manuf Description], '
    SET @sql = @sql + '    p.Serial_Number AS [Serial No]  '
    SET @sql = @sql + ' FROM AP_Products p   '
    SET @sql = @sql + ' LEFT OUTER JOIN AO_Suppliers s '
    SET @sql = @sql + '     ON s.AO_Suppliers_ID = p.Default_Supplier_ID  '
    SET @sql = @sql + ' LEFT OUTER JOIN Lup_AP_Mass_Codes mc '
    SET @sql = @sql + '     ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID  '
    SET @sql = @sql + ' LEFT OUTER JOIN Slu_AP_Units_Of_Measure um '
    SET @sql = @sql + '     ON p.Slu_AP_Units_Of_Measure_ID = um.Slu_AP_Units_Of_Measure_ID  '
    SET @sql = @sql + ' LEFT OUTER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + @Criteria + ' '

    BEGIN	
     	IF @FilterType = 1 --> Suppliers
    		SET @FilterString = 'AND p.AP_Products_ID in (SELECT AP_Products_ID
    				FROM AP_Products_Suppliers
    				WHERE AO_Suppliers_ID = ' + Convert(Varchar(10),@FilterValue) + ')'
    	ELSE 
    	IF @FilterType = 2 --> Manufacturer
    		SET @FilterString = 'AND p.Lup_AP_Product_Manufacturers_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 3 --> Type
    		SET @FilterString = 'AND p.Lup_AP_Product_Types_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 4 --> Group
    		SET @FilterString = 'AND p.Lup_AP_Product_Groups_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 5 --> Department
    		SET @FilterString = 'AND p.Lup_AP_Product_Departments_ID = ' + Convert(Varchar(10),@FilterValue) 
    
    	ELSE 
    	IF @FilterType = 6 --> Location
    		SET @FilterString = 'AND p.Lup_AP_Product_Locations_ID = ' + Convert(Varchar(10),@FilterValue) 
    	
    END 
    
	IF @FilterString <> '' 
        SET @sql = + @sql + ' ' + @FilterString


EXEC (@sql)




SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Inventory_Adjustments
--Purpose       :Returns all Inventory Adjustments
--Functionality :
--Parameters    :	
--Date          :2002/02/09
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE      Procedure sp_AP_Select_Inventory_Adjustments
    (
        @Option bit = 0,
    	@Description varchar(50) = null,
    	@User_ID int = null,
    	@FromDate datetime = null,
    	@ToDate datetime = null,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnID int

    IF @Option = 0
        BEGIN

       		SELECT
                a.AP_Inventory_Adjustments_ID AS [ID],
                a.AP_Products_ID AS [ProductID],
                p.[Description] AS [Product],
                P.Product_Code AS [Code],
                a.Date_Captured AS [Date],
                u.FirstName + ' ' + u.Surname AS [User],
               (isnull(a.New_Last_Cost,0) *
                isnull(a.New_On_Hand,0)) -
               (isnull(a.Previous_Last_Cost,0) *
                isnull(a.Previous_On_Hand,0)) AS [Value],
                a.Previous_Last_Cost AS [Prev Cost],
                a.New_Last_Cost AS [New Cost],
                a.Previous_On_Hand AS [Prev O/H],
                a.New_On_Hand AS [New O/H],
                a.Previous_Job_Reserved AS [Prev Job Res],
                a.New_Job_Reserved AS [New Job Res],
                a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
                a.New_Sales_Order_Reserved  AS [New S/O Res],
                a.Previous_Quote_Reserved AS [Prev Quote Res],
                a.New_Quote_Reserved AS [New Quote Res],
                a.Note AS [Note]
--                a.[User_ID] AS [User],
--                a.AW_User_Companies_ID AS [Company], 
--                a.Slu_AW_Active_ID AS [Active],
--			sum(a.New_Last_Cost * a.New_On_Hand -a.Previous_Last_Cost * a.Previous_On_Hand) AS [Variance Total]
    		FROM AP_Inventory_Adjustments a
                LEFT JOIN AP_Products p 
    		        ON a.AP_Products_ID = P.AP_Products_ID
                LEFT JOIN AW_Users u
    		        ON a.[User_ID] = U.AW_Users_ID
    		WHERE a.AW_User_Companies_ID = @CompanyID
    		ORDER BY a.Date_Captured Desc
    		
    		set @ReturnID = 1
    
    	END 
     
    ELSE 
    IF @Description is not null AND
      	@User_ID is not null AND
    	@FromDate is not null AND
    	@ToDate is not null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE ((p.Description Like '%' + @Description + '%') or (p.Product_Code Like '%' + @Description + '%')) AND
    			IA.User_ID = @User_ID AND
    			datediff(d, IA.Date_Captured, @FromDate ) <= 0 AND
    			datediff(d, IA.Date_Captured, @ToDate) >= 0 AND	
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 2
    	END 
    
    ELSE 
    IF @Description is not null AND
      	@User_ID is not null AND
    	@FromDate is null AND
    	@ToDate is null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE ((p.Description Like '%' + @Description + '%') or (p.Product_Code Like '%' + @Description + '%')) AND
    			IA.User_ID = @User_ID AND
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 3
    
    	END
    
    ELSE 
    IF @Description is not null AND
      	@User_ID is null AND
    	@FromDate is null AND
    	@ToDate is null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE ((p.Description Like '%' + @Description + '%') or (p.Product_Code Like '%' + @Description + '%')) AND				
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 4
    
    	END
    
    ELSE 
    IF @Description is null AND
      	@User_ID is not null AND
    	@FromDate is null AND
    	@ToDate is null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE IA.User_ID = @User_ID AND	
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 5
    
    	END
    
    ELSE 
    IF @Description is null AND
      	@User_ID is not null AND
    	@FromDate is not null AND
    	@ToDate is not null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE IA.User_ID = @User_ID AND
    			datediff(d, IA.Date_Captured, @FromDate ) <= 0 AND
    			datediff(d, IA.Date_Captured, @ToDate) >= 0 AND	
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 6
    
    	END
    
    ELSE 
    IF @Description is null AND
      	@User_ID is null AND
    	@FromDate is not null AND
    	@ToDate is not null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE datediff(d, IA.Date_Captured, @FromDate ) <= 0 AND
    			datediff(d, IA.Date_Captured, @ToDate) >= 0 AND
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 7
    
    	END
    
    ELSE 
    IF @Description is not null AND
      	@User_ID is null AND
    	@FromDate is not null AND
    	@ToDate is not null
    	BEGIN
    		SELECT IA.AP_Inventory_Adjustments_ID AS [ID],
    			IA.AP_Products_ID AS [Product_ID],
    			P.[Description] AS [Product],
    			P.Product_Code AS [Product Code],
    			IA.Previous_Last_Cost AS [Prev Last Cost],
    			IA.New_Last_Cost AS [New Last Cost],
    			IA.Previous_On_Hand AS [Prev On Hand],
    			IA.New_On_Hand AS [New On Hand],
    			IA.Previous_Job_Reserved AS [Prev Job Reserved],
    			IA.New_Job_Reserved AS [New Job Reserved],
    			IA.Previous_Sales_Order_Reserved  AS [Prev S/Order Reserved],
    			IA.New_Sales_Order_Reserved  AS [New S/Order Reserved],
    			IA.Previous_Quote_Reserved AS [Prev Quote Reserved],
    			IA.New_Quote_Reserved AS [New Quote Reserved],
    			IA.Note AS [Note],
    			IA.Date_Captured AS [Date Changed],
    			IA.[User_ID] AS [User_ID],
    			U.FirstName + ' ' + U.Surname AS [Changed By],
    			IA.AW_User_Companies_ID AS [Company], 
    			IA.Slu_AW_Active_ID AS [Active],
    			(isnull(IA.New_Last_Cost,0) * isnull(IA.New_On_Hand,0)) - (isnull(IA.Previous_Last_Cost,0) * isnull(IA.Previous_On_Hand,0)) AS [Variance]
    		FROM AP_Inventory_Adjustments IA LEFT JOIN AP_Products P 
    		ON IA.AP_Products_ID = P.AP_Products_ID LEFT JOIN AW_Users U
    		ON IA.[User_ID] = U.AW_Users_ID
    		WHERE ((p.Description Like '%' + @Description + '%') or (p.Product_Code Like '%' + @Description + '%')) AND
    			datediff(d, IA.Date_Captured, @FromDate ) <= 0 AND
    			datediff(d, IA.Date_Captured, @ToDate) >= 0 AND	
    			IA.AW_User_Companies_ID = @CompanyID
    		ORDER BY IA.Date_Captured Desc
    
    		set @ReturnID = 8
    
    	END
    
    Return @ReturnID

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Inventory_Adjustments_COS
--Purpose       :Fetch Cost-of-Sales Stock Adjustments from a Date
--Functionality :
--Date          :2010/04/14
--Authors       :TB
--MODS:         :
--2004.5.2      :09/07/11 - Added Adjustment type 6 (Take-on) in @Option = 0
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Select_Inventory_Adjustments_COS
    (
        @Option tinyint,
        @LastPeriodProcedureDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ValuationMethod smallint

    --> Get Primary Costing method
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


    IF @Option = 0        --Qty and Take-on Adjustments
        BEGIN
            SELECT
                a.AP_Inventory_Adjustments_ID AS [ID],
                a.AP_Products_ID AS [ProductID],
                a.Date_Captured AS [Date],
                u.UserName AS [User],
                p.[Description] AS [Product],
                p.Product_Code AS [Code],
                CASE WHEN @ValuationMethod = 0
                         THEN (ISNULL(a.New_Average_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Average_Cost, 0) * ISNULL(a.Previous_On_Hand, 0))
                     WHEN @ValuationMethod = 1
                         THEN (ISNULL(a.New_Last_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Last_Cost, 0) * ISNULL(a.Previous_On_Hand, 0))
                     ELSE (ISNULL(a.New_Average_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Average_Cost, 0) * ISNULL(a.Previous_On_Hand, 0))
                     END AS [Amount],
                a.Previous_On_Hand AS [Prev O/H],
                a.New_On_Hand AS [New O/H],
                a.Previous_Average_Cost AS [Prev Ave. Cost],
                a.New_Average_Cost AS [New Ave. Cost],
                a.Previous_Last_Cost AS [Prev Last Cost],
                a.New_Last_Cost AS [New Last Cost],
                a.Note AS [Note]
            FROM AP_Inventory_Adjustments a
                LEFT JOIN AP_Products p
                        ON a.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN AW_Users u
                        ON a.[User_ID] = u.AW_Users_ID
            WHERE a.AW_User_Companies_ID = @companyID AND
                 (a.Sys_AP_Adjustment_Types_ID = 1 OR
                  a.Sys_AP_Adjustment_Types_ID = 6) AND
                  a.Date_Captured >= @LastPeriodProcedureDate
            ORDER BY [Date]
        END
    ELSE
    IF @Option = 1        --Reval/Deval Adjustments
        BEGIN
            SELECT
                a.AP_Inventory_Adjustments_ID AS [ID],
                a.AP_Products_ID AS [ProductID],
                a.Date_Captured AS [Date],
                u.UserName AS [User],
                p.[Description] AS [Product],
                p.Product_Code AS [Code],
                CASE WHEN @ValuationMethod = 0
                         THEN (ISNULL(a.New_Average_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Average_Cost, 0) * ISNULL(a.Previous_On_Hand, 0))
                     WHEN @ValuationMethod = 1
                         THEN (ISNULL(a.New_Last_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Last_Cost, 0) * ISNULL(a.Previous_On_Hand, 0))
                     ELSE (ISNULL(a.New_Average_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Average_Cost, 0) * ISNULL(a.Previous_On_Hand, 0))
                     END AS [Amount],
                a.Previous_On_Hand AS [Prev O/H],
                a.New_On_Hand AS [New O/H],
                a.Previous_Average_Cost AS [Prev Ave. Cost],
                a.New_Average_Cost AS [New Ave. Cost],
                a.Previous_Last_Cost AS [Prev Last Cost],
                a.New_Last_Cost AS [New Last Cost],
                a.Note AS [Note]
            FROM AP_Inventory_Adjustments a
                LEFT JOIN AP_Products p
                        ON a.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Sys_AP_Adjustment_Types t
                        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                LEFT JOIN AW_Users u
                        ON a.[User_ID] = u.AW_Users_ID
            WHERE a.AW_User_Companies_ID = @companyID AND
                  a.Sys_AP_Adjustment_Types_ID = 3 AND
                  a.Date_Captured >= @LastPeriodProcedureDate
            ORDER BY [Date]
        END


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Markup_Categories_As_PickList
--Purpose       :
--Functionality :Tables: Lup_AC_Markup_Categories
--Parameters    :
--Date          :2007/07/23
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------
CREATE      PROCEDURE sp_AP_Select_Markup_Categories_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AC_Markup_Categories_ID AS [ID],
          [Description] as [Markup Category] 
	FROM Lup_AC_Markup_Categories
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   : sp_AP_Select_Markup_Groups_As_PickList
--Purpose       : 
--Functionality : Tables: Lup_AP_Markup_Groups
--Parameters    : 
--Date          : 2002/02/09
--Authors       : TB
--MODS
-------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AP_Select_Markup_Groups_As_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Lup_AP_Markup_Groups_ID AS [ID],
		   [Description] as [Markup Groups] 
	FROM Lup_AP_Markup_Groups
	WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Non_Stock_Billing_Products
--Purpose       :Fetch all Non-Stock Products for Periodic Billing
--Functionality :
--Date          :2010/11/15
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Select_Non_Stock_Billing_Products
    (
         @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        AP_Products_ID AS [ProductID],
		Description + ' (' + ISNULL(Product_Code, '') + ')' AS [Description], 
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) AS [Unit Price]
	FROM AP_Products
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_YesNo_Non_Stock_Item = 1
    ORDER BY [Description]



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Online_Stock_Exchange_Products
--Purpose       :Select rs schema for POS Online Stock Exchange 
--Date          :2006/09/10
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Select_Online_Stock_Exchange_Products
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


	SET @sql = ' SELECT '
    SET @sql = @sql + ' AW_Remote_Access_ID AS [Branch ID], '
    SET @sql = @sql + ' NodeName AS [Branch], '
    SET @sql = @sql + ' Product_Description AS [Product], '
    SET @sql = @sql + ' Product_Code AS [Code], '
    SET @sql = @sql + ' On_Hand AS [On Hand], '
    SET @sql = @sql + ' On_Order AS [On Order], '
    SET @sql = @sql + ' Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' Average_Cost AS [Average Cost], '
    SET @sql = @sql + ' Count_Date AS [Count Date] '
    SET @sql = @sql + ' FROM AP_Stock_Exchange '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + ' ORDER BY Product_Description '


SET NOCOUNT OFF


EXEC (@sql)

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Price_Update_Products
--Purpose       :Select Product Price Update data
--Functionality :
--Date          :2004/01/01
--Authors       :TB
--Version       :1.0.0
--MODS          :18/06/04 - Replaced [Comment] with [Last Cost]
--2004.2.9      :02/06/06 - Removed comma from [Last Cost] field
--              :02/06/06 - Added DATEADD validation to select empty RS
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Select_Price_Update_Products
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)
   
	SET @sql = ' SELECT '
    SET @sql = @sql + ' AP_Products_ID AS [ProdID], '
    SET @sql = @sql + ' Product_Code AS [Product Code], '
    SET @sql = @sql + ' [Description] AS [Product Description], '
    SET @sql = @sql + ' Price1_Effective_Date AS [Effective Date], '
    SET @sql = @sql + ' Price1_Price1 AS [Price 1], '
    SET @sql = @sql + ' Price1_Price2 AS [Price 2], '
    SET @sql = @sql + ' Last_Cost AS [Last Cost] '
    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 [Product Description] '



SET NOCOUNT OFF


EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Cardex
--Purpose       :Retrieves Inventory physical movement
--Functionality :    uses UNION ALL
--Date          :2004/10/10
--Authors       :TB
--MODS:         :12/05/05 - Appended (AO_GRV_ID) to Supplier_Reference
--2004.3.4      :08/03/07 - Replaced gh.Supplier_Reference with
--              :           gh.Delivery_Note_Number to show Supplier Invoice Number
--2004.3.9      :13/06/08 - Changed [Supplier/Customer] field in ADJUSTMENTS section
--              :           and inserted [Note] from AP_Inventory_Adjustments table
--2004.4.2      :23/10/08 - Change SALES section from Sales Cost to Selling Price - RM
--              :           and renamed aliases [Unit Cost] to [Unit Price]
--              :           and [Total Cost] to [Total]
--2004.4.7      :12/09/09 - Added STOCK TRANSFER type in SALES section
--2004.4.9      :03/10/10 - Fixed STOCK TRANSFER type in SALES section. OMITTED to
--              :           add h.Sys_AW_Transaction_Types_ID = 23 in WHERE clause !!!!!
--              :03/10/10 - Added split STOCK TRANSFER types in SALES section
--              :           into 'TRF IN' and 'TRF OUT' based on d.Quantity value
--2004.5.1      :02/06/11 - Added h.Sys_AW_Transaction_Types_ID = 29 as 'GRVFAC'
--              :           in GOODS RECEIVED for Casing Tracking Factory GRV's
--              :15/06/11 - Added h.Sys_AW_Transaction_Types_ID = 23 as 'TRF IN/OUT'
--              :           in SALES section WHERE clause
--2004.5.2      :06/07/11 - Added h.Sys_AW_Transaction_Types_ID = 30 as 'GRNFAC'
--              :           in GOODS RETURNED for Casing Tracking Factory CLAIM REFUND
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 31 as 'CRV' and 
--              :            h.Sys_AW_Transaction_Types_ID = 32 as 'CRN' for consignment stock
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 33 as 'CON N' and 
--							h.Sys_AW_Transaction_Types_ID = 34 as 'CON S' and 
--              :           h.Sys_AW_Transaction_Types_ID = 35 as 'CON R' for consignment stock sales
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Cardex]
    (
        @StartDate as datetime,
        @ProductID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql			varchar(8000)
    DECLARE @DefaultBin		varchar(50)

-- SET @StartDate = '2004/09/01 00:00:01'
-- SET @ProductID = 271

	SELECT @DefaultBin = [Description]
	FROM Lup_AP_Product_Bins
	WHERE Lup_AP_Product_Bins_ID = 1

	IF ISNULL(@DefaultBin,'') = ''
		SET @DefaultBin = '<None>'

-------------------------------------------------------------------------------
-- GOODS RECEIVED
-------------------------------------------------------------------------------

    SET @sql = ' SELECT '

    SET @sql = @sql + '     gd.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), gh.Date_Received, 121)) AS [Date], '
    SET @sql = @sql + '     ISNULL(gh.Delivery_Note_Number, '''') '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), gh.AO_GRV_ID) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    --GRVs always done to and from default bin
    SET @sql = @sql + '''' + @DefaultBin + '''' + ' AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN gh.Sys_AW_Transaction_Types_ID = 19 '
    SET @sql = @sql + '          THEN ''GRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 20 '
    SET @sql = @sql + '          THEN ''RETURN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '          THEN ''GRVFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 30 '
    SET @sql = @sql + '          THEN ''GRNFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 31 '
    SET @sql = @sql + '          THEN ''CRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 32 '
    SET @sql = @sql + '          THEN ''CRN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 34 '
    SET @sql = @sql + '          THEN ''CON S'' '                
    SET @sql = @sql + '          ELSE ''NOGRV'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     ISNULL(gd.Qty, 0) AS [Qty], '
    SET @sql = @sql + '     ISNULL(gd.Unit_Price, 0) AS [Unit Price], '
    SET @sql = @sql + '     ISNULL(gd.Net_Amount, 0) AS [Total], '
    SET @sql = @sql + '     gd.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AO_GRV_Details gd '
    SET @sql = @sql + '         ON p.AP_Products_ID = gd.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_GRV gh '
    SET @sql = @sql + '         ON gd.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON gh.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON gh.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND gd.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (gh.Sys_AW_Transaction_Types_ID = 19 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 20 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 29 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 30 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 31 ' + ' '        
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 32 ' + ' '            
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 34) ' + ' '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- ADJUSTMENTS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.AP_Inventory_Adjustments_ID) AS [Ref No], '
    SET @sql = @sql + '     ISNULL(a.Note, '''') AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     CASE WHEN a.Sys_AP_Adjustment_Types_ID = 1 '
    SET @sql = @sql + '          THEN ''ADJUST'' '
    SET @sql = @sql + '          WHEN a.Sys_AP_Adjustment_Types_ID = 6 '
    SET @sql = @sql + '          THEN ''TAKEON'' '
    SET @sql = @sql + '          ELSE ''NOADJ'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ISNULL(a.New_Last_Cost, 0) AS [Unit Price], '
    SET @sql = @sql + '     ROUND((ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0)) * ISNULL(a.New_Last_Cost, 0), 2) AS [Total], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Inventory_Adjustments a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (a.Sys_AP_Adjustment_Types_ID = 1 ' + ' '
    SET @sql = @sql + '     OR a.Sys_AP_Adjustment_Types_ID = 6) ' + ' '
    SET @sql = @sql + '   AND ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) <> 0 ' + ' '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- SALES
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     d.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), h.Transaction_Date, 121)) AS [Date], '
    SET @sql = @sql + '     h.Transaction_Number AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('', '' + c.Firstnames, ''''))) AS [Supplier/Customer], '
	SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''SALE'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''REFUND'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) < 0) '
    SET @sql = @sql + '          THEN ''TRF IN'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) >= 0) '
    SET @sql = @sql + '          THEN ''TRF OUT'' '    
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 33  '
    SET @sql = @sql + '          THEN ''CON N'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 34  '
    SET @sql = @sql + '          THEN ''CON S'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 35  '
    SET @sql = @sql + '          THEN ''CON R'' '
    SET @sql = @sql + '          ELSE ''NOSALE'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     (ISNULL(d.Quantity, 0) * -1) AS [Qty], '

    SET @sql = @sql + '     CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '          THEN ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) / ISNULL(d.Quantity, 0), 2) '
    SET @sql = @sql + '          ELSE 0 '
    SET @sql = @sql + '     END AS [Unit Price], '

    SET @sql = @sql + '     ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)), 2) AS [Total], '
    SET @sql = @sql + '     d.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + '         ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN dbo.AC_Customers c '
    SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON d.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND d.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 23 OR '    
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 33 OR '    
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 34 OR '            
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 35) '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations From Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     ISNULL(a.From_Bin_New_On_Hand, 0) - ISNULL(a.From_Bin_Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.From_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations To Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     ISNULL(a.To_Bin_New_On_Hand, 0) - ISNULL(a.To_Bin_Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.To_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' ORDER BY [CompanyID], [Date Captured] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Catalog
--Purpose       :select's a specific Product's Catalog information 
--Functionality :
--Parameters    :
--Date          :2001/12/07
--Authors       :TB
--MODS          :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :                 Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :                 Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--2004.2.3      :12/05/05 - Added GL_Purchases_ID AS [GLPurchasesID]
--              :                 GL_Sales_ID AS [GLSalesID]
--              :           for simultaneous 'Stock' and 'Non-Stock' GRV posting
--              :19/05/05 - Added Standard_Cost AS [Standard Cost]
--2004.2.4      :23/10/05 - Added GL_COS_ID AS [GLCOSID] for GL Cost-of-Sales
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories_ID AS [PurchaseCategory]
--2004.3.7      :25/07/07 - Added Lup_AP_Markup_Groups_ID AS [CostPlus Group]
--              :26/08/07 - Added Slu_AW_YesNo_Cost_Plus_Item AS [CostPlusItem]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.5.7 RGL  :2012-10-17 - Added Slu_AW_YesNo_Levy_Item As [IsLevy]
--2004.5.7 RGL  :2012-10-17 - Added Slu_AW_Weight_ID As [ProductWeight]        
--2004.5.7 RGL  :2012-10-17 - Added Levy_Product_ID AS [Levy_Product]
--2004.6.0 RGL  :2014-04-10 - Added Slu_AW_YesNo_Sell_Below_Cost AS [Sell Below Cost]
--2004.6.0 RGL  :2014-05-07 - Changed On Hand, Job Reserved, On order and Sales Order values to 
--			      include transactions that could affect value
--V6.2 RL  :2015-06-10 - Added quantity of products out on consignment
---------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Catalog]
    (
        @Product_ID int,
        @Company_ID int 
    )
AS

SET NOCOUNT ON

    SELECT AP_Products_ID AS [ID], 
    	[Description] AS [Description], 
    	Print_Description AS [Print Description], 
    	Keywords AS [Search Keywords], 
    	Lup_AP_Product_Types_ID AS [Type], 
    	Lup_AP_Product_Groups_ID AS [Group], 
    	Lup_AP_Product_Departments_ID AS [Department], 
    	Lup_AP_Product_Locations_ID AS [Location], 
    	Lup_AP_Purchase_Categories_ID AS [PurchaseCategory], 
    	Serial_Number AS [Serial Number], 
    	Lup_AP_Product_Manufacturers_ID AS [Manufacturer], 
    	Manufacturer_Code AS [Manuf Code], 
    	Manufacturer_Description AS [Manuf Description], 
    	Default_Supplier_ID AS [Default Supplier], 
    	Product_Code AS [Product Code], 
    	SKU_Code AS [LCD Code], 
    	Supercession AS [Supercession], 
    	Alternate_Code1 AS [Alt Code 1], 
    	Alternate_Code2 AS [Alt Code 2],
     	Pack_Size AS [Pack Size], 
    	Measure AS [Measure], 
    	Slu_AP_Units_Of_Measure_ID AS [Unit of Measure], 
    	Strength AS [Unit Strength], 
    	Lup_AP_Mass_Codes_ID AS [Mass Code], 
    	Pack_Mass AS [Pack Mass], 
    	Pack_Volume AS [Pack Volume], 
    	Slu_AW_Active_ID AS [Active], 
    	Slu_AW_YesNo_Self_Managed AS [Self Managed], 
    	Price1_Effective_Date AS [Price 1 - Effective Date], 
    	Price1_Price1 AS [Price 1 - Price1], 
    	Price1_Price2 AS [Price 1 - Price2], 
    	Price2_Effective_Date AS [Price 2 - Effective Date], 
    	Price2_Price1 AS [Price 2 - Price1], 
    	Price2_Price2 AS [Price 2 - Price2], 
    	Lup_AP_Rounding_Codes_ID AS [Rounding Code], 
    	Sys_AW_Tax_Codes_ID AS [Tax Code], 
    	Lup_AP_Discount_Groups_ID AS [Sales Discount Group], 
    	Lup_AP_Markup_Groups_ID AS [CostPlus Group], 
    	Lup_AP_Commission_Groups_ID AS [Sales Commission Group], 
    	Slu_AW_YesNo_Edit_Price AS [Edit Price at POS], 
    	Slu_AW_YesNo_Edit_Discount AS [Edit Discount at POS], 
    	Max_Discount_Perc AS [MaxDiscPerc], 
    	Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc], 
    	PLU_Tab AS [Plu Tab Location], 
    	Lup_AP_Sell_By_Codes_ID AS [Sell By Code], 
    	--On_Hand AS [Qty On Hand], 
		--CONVERT(decimal(9, 3),(On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(AP_Products_ID))) as [Qty on Hand],
		On_Hand as [Qty on Hand],
    	--Job_Reserved AS [Job Reserved],
		CONVERT(decimal(18, 3), dbo.fn_AP_Products_Job_Reserved(AP_Products_ID)) as [Job Reserved], 
    	--Quote_Reserved AS [Quote Reserved],
    	CONVERT(decimal(18, 3), dbo.fn_AP_Products_Quoted(AP_Products_ID)) as [Quote Reserved], 
    	--Sales_Order_Reserved AS [Sales Order Reserved],
    	CONVERT(decimal(18, 3), dbo.fn_AP_Products_Sales_Order_Reserved(AP_Products_ID)) as [Sales Order Reserved], 
    	CONVERT(decimal(18, 3), dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID)) as [Out On Consignment], 
    	Min_Stock_Level AS [Min Stock Level], 
    	Last_Cost AS [Last Cost], 
    	Average_Cost AS [Average Cost], 
    	Standard_Cost AS [Standard Cost], 
    	Average_Markup AS [Average Markup %], 
    	Last_Sale_Date AS [Last Sale Date], 
    	Service_Level AS [Service Level], 
    	Max_Order_Qty AS [Max_Order_Qty], 
    	Min_Order_Qty AS [Min_Order_Qty],
    	--(SELECT (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
    	--        FROM AO_Order_Details od INNER JOIN AO_Orders o
    	--            ON od.AO_Orders_ID = o.AO_Orders_ID
    	--        WHERE o.Date_Ordered is not null AND
    	--              o.Complete <> 1 AND
    	--              od.AP_Products_ID = @Product_ID) AS [Qty on order],
		CONVERT(decimal(18, 3), dbo.fn_AO_Get_Qty_On_Order(AP_Products_ID)) as [Qty on order],
    	Slu_AW_YesNo_Assembly AS [Yes No Assembly],	
    	Memo AS [Notes], 
    	Show_Image AS [Show Image], 
    	Image_File_Name AS [Image Path], 
        Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--        Slu_AW_YesNo_Hide_Remote AS [HideRemote],
        Slu_AW_YesNo_Cost_Plus_Item AS [CostPlusItem],
        GL_Purchases_ID AS [GLPurchasesID],
        GL_Sales_ID AS [GLSalesID],
        GL_COS_ID AS [GLCOSID],      
        Lup_AP_AW_Weight_ID As [Weight Code],
        Product_Weight As [Product Weight],                       
        Slu_AW_YesNo_Levy_Item As [IsLevy],        
        Levy_AP_Product_ID AS [Levy Product],
        Levy_Weight_ID As [Levy Weight Code],    
        Slu_AW_YesNo_Sell_Below_Cost AS [Sell Below Cost],     
    	Date_Captured AS [Date Captured], 
    	[User_ID] AS [User ID], 
    	AW_User_Companies_ID AS [Company ID] 

    FROM AP_Products 
    WHERE AP_Products_ID = @Product_ID AND 
    	AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Catalog_Non_Stock
--Purpose       :Fetch all Non-Stock Products from Catalog
--Functionality :
--Date          :2009/04/30
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Catalog_Non_Stock]
    (
         @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        AW_User_Companies_ID AS [CompanyID],
        AP_Products_ID AS [ProductID],
		Description AS [Description], 
		ISNULL(Product_Code, '') AS [Code], 
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) AS [Unit Price],
		Last_Cost AS [Last Cost], 
		Average_Cost AS [Avg Cost], 
		Standard_Cost AS [Std Cost],
		On_Hand AS [On Hand],
        CONVERT(decimal(18, 3), dbo.fn_AP_SUM_Product_Job_Reserved(AP_Products_ID)) AS [Reserved]
	FROM AP_Products
    WHERE AW_User_Companies_ID =  @CompanyID AND
          Slu_AW_YesNo_Non_Stock_Item = 1



SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Exchange_Products
--Purpose       :Select Product Exchange Update data
--Functionality :
--Date          :2004/01/13
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Select_Product_Exchange_Products
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


	SET @sql = ' SELECT '
    SET @sql = @sql + ' AW_Remote_Access_ID AS [Branch ID], '
    SET @sql = @sql + ' NodeName AS [Branch], '
    SET @sql = @sql + ' AP_Products_ID AS [Product ID], '
    SET @sql = @sql + ' Product_Description AS [Product], '
    SET @sql = @sql + ' Product_Code AS [Code], '
    SET @sql = @sql + ' On_Hand AS [On Hand], '
    SET @sql = @sql + ' On_Order AS [On Order], '
    SET @sql = @sql + ' Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' Average_Cost AS [Average Cost], '
    SET @sql = @sql + ' Count_Date AS [Count Date] '
    SET @sql = @sql + ' FROM AP_Stock_Exchange '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + ' ORDER BY Product_Description '


SET NOCOUNT OFF


EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE  Procedure sp_AP_Select_Product_Links
    @ProductID int

AS

    SELECT 
        s1.Description AS Make, 
        s2.Description AS Model, 
        s3.Description AS [Year], 
        s1.AP_Switch1_ID AS S1_ID, 
        s2.AP_Switch2_ID AS S2_ID, 
        s3.AP_Switch3_ID AS S3_ID, 
        ps3.AP_Products_Switch3_ID AS [ID], 
        ps3.AP_Products_ID AS ProductID
    FROM AP_Switch1 s1 
        INNER JOIN AP_Switch2 s2
            ON s1.AP_Switch1_ID = s2.AP_Switch1_ID 
        INNER JOIN AP_Switch3 s3
            ON s2.AP_Switch2_ID = s3.AP_Switch2_ID 
        INNER JOIN AP_Products_Switch3 ps3
            ON s3.AP_Switch3_ID = ps3.AP_Switch3_ID
    WHERE ps3.AP_Products_ID = @ProductID 







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--REDUNDANT

--The Procedure to use for Lookups on the Product Edit/Add Mechanism
--The string used in the Program

CREATE    PROCEDURE sp_AP_Select_Product_Lookups
   @Which varchar(30) ='',
   @ID smallint = -1
AS
IF @Which = 'Lup Group'
   SELECT
      Lup_AP_Product_Groups_ID as ID, 
      Description as [Group] 
   FROM Lup_AP_Product_Groups
ELSE
IF @Which = 'Lup Department'
   SELECT
      Lup_AP_Product_Departments_ID as ID, 
      Description as [Department] 
   FROM  Lup_AP_Product_Departments
ELSE
IF @Which = 'Lup Location'
   SELECT 
      Lup_AP_Product_Locations_ID as ID, 
      Description as [Location] 
   FROM  Lup_AP_Product_Locations
ELSE
IF @Which = 'Lup Manufacturer'
   SELECT
      Lup_AP_Product_Manufacturers_ID as ID, 
      Description as [Manufacturer] 
   FROM Lup_AP_Product_Manufacturers
ELSE
IF @Which ='Lup Supplier'
   SELECT 
      AO_Suppliers_ID as ID, 
      Supplier_Name as [Supplier] 
   FROM AO_Suppliers
ELSE
IF @Which = 'Lup Unit Of Measure'
   SELECT 
      Slu_AP_Units_Of_Measure_ID as ID, 
      Description as [Unit of Measure] 
   FROM  Slu_AP_Units_Of_Measure
ELSE
IF @Which = 'Lup Mass Code'
   SELECT 
      Lup_AP_Mass_Codes_ID as ID, 
      Description as [Mass Code] 
   FROM  Lup_AP_Mass_Codes
ELSE
IF @Which = 'Lup Active'
   SELECT 
      Slu_AW_Active_ID as ID, 
      Description as [Active] 
   FROM  Slu_AW_Active
ELSE
IF @Which = 'Lup Self Managed'
   SELECT 
      Slu_AW_YesNo_ID as ID, 
      Description as [Self Managed] 
   FROM  Slu_AW_YesNo
ELSE
IF @Which = 'Lup Rounding Code'
   SELECT 
      Lup_AP_Rounding_Codes_ID as ID, 
      Description as [Rounding Code] 
   FROM  Lup_AP_Rounding_Codes
ELSE
IF @Which = 'Lup Tax Code'
   SELECT 
      Sys_AW_Tax_Codes_ID as ID, 
      Description as [Tax Code] 
   FROM  Sys_AW_Tax_Codes
ELSE
IF @Which ='Lup Sales Discount Group'
   SELECT 
      Lup_AP_Discount_Groups_ID as ID, 
      Description as [Sales Discount Group] 
   FROM  Lup_AP_Discount_Groups
ELSE
IF @Which = 'Lup Sales Commission Group'
   SELECT
      Lup_AP_Commission_Groups_ID as ID, 
      Description as [Sales Commission Group] 
   FROM Lup_AP_Commission_Groups
ELSE
IF @Which = 'Lup Edit Price at POS'
   SELECT 
      Slu_AW_YesNo_ID as ID, 
      Description as [Edit Price at POS] 
   FROM  Slu_AW_YesNo
ELSE
IF @Which = 'Lup Edit Discount at POS'
   SELECT
      Slu_AW_YesNo_ID as ID, 
      Description as [Edit Discount at POS] 
   FROM  Slu_AW_YesNo
ELSE
IF @Which = 'Lup Sell By Code'
   SELECT
      Lup_AP_Sell_By_Codes_ID as ID, 
      Description as [Sell By Code] 
   FROM  Lup_AP_sell_By_Codes
ELSE
IF @Which = 'Lup Restrict Product'
   SELECT
      Slu_AW_YesNo_ID as ID,
      Description as [Restrict Product] 
   FROM  Slu_AW_YesNo
ELSE
IF @Which = 'Lup Model Type'
   SELECT
      Lup_AP_Switch2_Types_ID as ID, 
      Description as [Model Type] 
   FROM  Lup_AP_Switch2_Types
ELSE
IF @Which = 'Lup Country'
   SELECT
      Slu_AW_Countries_ID as ID,
      Description as [Country] 
   FROM  Slu_AW_Countries
ELSE
IF @Which = 'Lup Type'
   SELECT
      Lup_AP_Product_Types_ID as ID,
      Description as [Type] 
   FROM Lup_AP_Product_Types
ELSE
IF @Which = 'Lup Purchase Price'
   SELECT
      Lup_AO_Purchase_Price_Types_ID as ID,
      Description as [Purchase Price] 
   FROM Lup_AO_Purchase_Price_Types
ELSE
IF @Which = 'Lup Trade Discount'
   SELECT
      AW_Formulas_ID as ID ,
      Description AS [Trade Discount] 
   FROM AW_Formulas
ELSE
IF @Which = 'Lup Other Discounts'
   SELECT
      AB_Accounts_ID AS ID,
      Description AS [Other Discounts] 
   FROM AB_Accounts
ELSE
IF @Which = 'Lup Rebate Formula'
   SELECT
      AW_Formulas_ID as ID,
      Description AS [Rebate Formula] 
   FROM AW_Formulas
ELSE
IF @Which = 'Lup Rebate Account'
   SELECT
      AB_Accounts_ID AS ID,
      Description AS [Rebate Account]
   FROM AB_Accounts
ELSE
IF @Which = 'Lup Credit Terms'
   SELECT
      Slu_AW_Credit_Terms_ID AS ID,
      Description as [Credit Terms] 
   FROM Slu_AW_Credit_Terms
ELSE
IF @Which = 'Lup Account Status'
   SELECT
      Sys_AC_Account_Status_ID as ID,
      Description as [Account Status]
   FROM Sys_AC_Account_Status









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Promotions
--Purpose       :Select Product Promotions Header
--Functionality :
--Date          :2004/02/16
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Select_Product_Promotions
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)
   
	SET @sql = ' SELECT '
    SET @sql = @sql + ' AP_Promotions_ID AS [PromoID], '
    SET @sql = @sql + ' [Description] AS [Promotion], '
    SET @sql = @sql + ' Start_Date AS [Start Date], '
    SET @sql = @sql + ' End_Date AS [End Date], '
    SET @sql = @sql + ' Slu_AW_Active_ID AS [Active] '
    SET @sql = @sql + ' FROM AP_Promotions '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + ' ORDER BY Start_Date DESC '



SET NOCOUNT OFF


EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Suppliers_Detail
--Purpose       :select a specific Product's Suppliers detail
--Functionality :
--Parameters    :
--Date          :2002/02/03
--Authors       :TB
--Version       :1.0.0
--MODS          :04/10/03 - Added NEW Trade_Disc_Perc for Nett Billing and
--              :           NEW Inventory Manager's Discount column
--              :04/10/03 - Added NEW Trade_Disc_Date for NEW Discount above
-----------------------------------------------------------------------------

CREATE   PROCEDURE sp_AP_Select_Product_Suppliers_Detail
    (
        @Product_Suppliers_ID int
    )

AS

SET NOCOUNT ON

    SELECT
        ps.AP_Products_Suppliers_ID AS [ID], 
        ps.AP_Products_ID AS [FK ID], 
        p.[Description] AS [Product],
        ps.AO_Suppliers_ID AS [Supplier ID],
        s.Supplier_Name AS [Supplier],
        ps.Trade_Disc_Perc AS [TradeDiscPerc],
        ps.Trade_Disc_Date AS [TradeDiscDate],
        ps.Lead_Time AS [Lead Time], 
        ps.Start_Date AS [Start Date], 
        ps.AW_Trade_Discount_Formula_ID AS [Trade_Disc_Formula],
        ps.AW_Rebate_Discount_Formula_ID AS [Rebate_Disc_Formula],
        ps.Slu_AW_Active_ID AS [Active]
    FROM AP_Products_Suppliers ps
        INNER JOIN AP_Products p
            ON ps.AP_Products_ID = p.AP_Products_ID 
        INNER JOIN AO_Suppliers s
            ON ps.AO_Suppliers_ID = s.AO_Suppliers_ID
    WHERE AP_Products_Suppliers_ID = @Product_Suppliers_ID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Products_For_PickList
--Purpose       :Select all Products for the Picklist
--Functionality :
--Parameters    :
--Date          :2001/12/22
--Authors       :TB
--Version       :1.0.0
--MODS          :01/09/04 - Added ISNULL validation to prevent NULL value error
--              :           in UI Picklist field data conversions (T2K m.o.)
--2004.5.0      "12/03/11 - Added SKU_Code to Alternate_Code2 product code fields
-----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Select_Products_For_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AP_Products_ID AS [ID],
           ISNULL(Product_Code, '') AS [Code],
           ISNULL([Description], '') AS [Product],
           ISNULL(SKU_Code, '') AS [SKU_Code],
           ISNULL(Supercession, '') AS [Supercession],
           ISNULL(Alternate_Code1, '') AS [Alternate_Code1],
           ISNULL(Alternate_Code2, '') AS [Alternate_Code2]
	FROM AP_Products
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY [Description]

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Products_For_PickList_W
--Purpose       :Select all Products for the Picklist on WEB
--Functionality :
--Parameters    :
--Date          :2003/09/01
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Select_Products_For_PickList_W
    (
        @Search varchar(50),
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AP_Products_ID AS [ID],
           ISNULL(Product_Code, '') AS [Code],
           ISNULL([Description], '') AS [Product]
	FROM AP_Products
	WHERE AW_User_Companies_ID = @Company_ID AND
          [Description] LIKE @Search
    ORDER BY [Description]

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Products_For_PickList_With_Movement
--Purpose       :Select all Products WITH MOVEMENT for the Picklist
--Parameters    :
--Date          :2004/10/16
--Authors       :TB
--Version       :1.0.0
--MODS          :
-----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Select_Products_For_PickList_With_Movement
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AP_Products_ID AS [ID],
           ISNULL(Product_Code, '') AS [Code],
           ISNULL([Description], '') AS [Product]
    FROM AP_Products
	WHERE AW_User_Companies_ID = @Company_ID AND
          dbo.fn_AP_Product_Has_Movement(AP_PRoducts_ID) = 1
    ORDER BY [Description]

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Products_Lups
--Purpose       :Product Catalog Lookups
--Functionality :
--Parameters    :
--Date          :2001/11/13
--Authors       :TB
--MODS          :11/07/02 - Modified SORT ORDER of most LUPS to ALPHA
--2004.2.4      :23/10/05 - Modified Choice 17 and added ALIAS [Plu Tabs]
--              :           causing list field not displaying in Catalog 
--2004.3.4      :26/02/07 - Added Choice 18 as [Purchase Categories]
--2004.4.0      :25/07/07 - Added Choice 19 as [CostPlusGroup]
--2004.5.7 RGL	:2012-10-23 - Added 20 as Unit Weight and 21 as Product Levy
--2004.5.8 RGL  :2013-02-20 - Added <None> as Levy LU
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Products_Lups]
    (
    	@Choice int,
    	@CompanyID int 
    )
AS

SET NOCOUNT ON

    --> 1 - Product Types
    	IF @Choice = 1
    		SELECT Lup_AP_Product_Types_ID AS [ID], 
    		[Description] AS [Product Types] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 2 - Product Groups
    	ELSE 
    	IF @Choice = 2	
    		SELECT Lup_AP_Product_Groups_ID AS [ID], 
    		[Description] AS [Product Groups] 
    		FROM Lup_AP_Product_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 3 - Product Departments
    	ELSE 
    	IF @Choice = 3	
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    		[Description] AS [Product Departments] 
    		FROM Lup_AP_Product_Departments	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 4 - Product Locations
    	ELSE 
    	IF @Choice = 4	
    		SELECT Lup_AP_Product_Locations_ID AS [ID], 
    		[Description] AS [Product Locations] 
    		FROM Lup_AP_Product_Locations	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 5 - Product Manufacturers
    	ELSE 
    	IF @Choice = 5
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID], 
    		[Description] AS [Product Manufacturer] 
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 6 - Default Supplier
    	ELSE 
    	IF @Choice = 6
    		SELECT AO_Suppliers_ID AS [ID], 
    		[Supplier_Name] AS [Default Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Supplier_Name]
    
    --> 7 - Units Of Measure
    	IF @Choice = 7
    		SELECT Slu_AP_Units_Of_Measure_ID AS [ID], 
    		[Description] AS [Units Of Measure] 
    		FROM Slu_AP_Units_Of_Measure
            ORDER BY [Description]
    
    --> 8 - Mass Codes
    	ELSE
    	IF @Choice = 8
    		SELECT Lup_AP_Mass_Codes_ID AS [ID],
    		[Description] As [Mass Codes] 
    		FROM Lup_AP_Mass_Codes
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 9 - Active
    	ELSE
    	IF @Choice = 9
    		SELECT Slu_AW_Active_ID AS [ID],
    		[Description] As [Status] 
    		FROM Slu_AW_Active
    
    --> 10 - AW YesNO
    	ELSE
    	IF @Choice = 10
    		SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [AW YesNo] 
    		FROM Slu_AW_YesNo
    
    --> 11 - Rounding Codes
    	ELSE
    	IF @Choice = 11
    		SELECT Lup_AP_Rounding_Codes_ID AS [ID],
    		[Description] As [Rounding Codes] 
    		FROM Lup_AP_Rounding_Codes		
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 12 - Tax Codes
    	ELSE
    	IF @Choice = 12
    		SELECT Sys_AW_Tax_Codes_ID AS [ID],
    		[Description] As [Tax Codes] 
    		FROM sys_AW_Tax_Codes
    
    --> 13 - Sales Discount Groups
    	ELSE
    	IF @Choice = 13
    		SELECT Lup_AP_Discount_Groups_ID AS [ID],
    		[Description] As [Discount Groups] 
    		FROM Lup_AP_Discount_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 14 - Sales Commissions Group
    	ELSE
    	IF @Choice = 14
    		SELECT Lup_AP_Commission_Groups_ID AS [ID],
    		[Description] As [Commissions Group] 
    		FROM Lup_AP_Commission_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 15 - Sell By Codes
    	ELSE
    	IF @Choice = 15
    		SELECT Lup_AP_Sell_By_Codes_ID AS [ID],
    		[Description] As [Sell By Codes] 
    		FROM Lup_AP_Sell_By_Codes
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 16 - Formulas
    	ELSE
    	IF @Choice = 16
    		SELECT AW_Formulas_ID AS [ID],
    		[Description] As [Formulas] 
    		FROM AW_Formulas
    		WHERE AW_User_Companies_ID = @CompanyID
    
    --> 17 - PLU TAB Location
    	ELSE
    	IF @Choice = 17
    		SELECT Lup_AP_PLU_Tabs_ID AS [ID],
    		[Description] As [Plu Tabs] 
    		FROM Lup_AP_PLU_Tabs
    		WHERE AW_User_Companies_ID = @CompanyID

    --> 18 - Purchase Categories
    	ELSE 
    	IF @Choice = 18	
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    		[Description] AS [Purchase Categories] 
    		FROM Lup_AP_Purchase_Categories	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]

    --> 19 - Cost+Plus Groups
    	ELSE
    	IF @Choice = 19
    		SELECT Lup_AP_Markup_Groups_ID AS [ID],
    		[Description] As [CostPlusGroup] 
    		FROM Lup_AP_Markup_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    --> 20 - Unit Weight
    	ELSE
    	IF @Choice = 20
    		SELECT Lup_AP_AW_Weight_ID AS [ID],
    		[Description] As [Unit Weight] 
    		FROM Lup_AP_AW_Weight
            ORDER BY [Description]
    --> 21 - Levy Product
    	ELSE
    	IF @Choice = 21
			SELECT 0 AS [ID],
    		'<None>' As [Levy] 
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            UNION
    		SELECT AP_Products_ID AS [ID],
    		[Description] As [Levy]
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            ORDER BY 2

SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Products_PickList_ProductID
--Purpose       :Select all Products for the Picklist ORDER BY Product_ID
--Functionality :Used to DELETE Products added by ProductID sequentially
--Date          :2008/05/19
--Authors       :TB
--MODS          :
--2004.5.0      "12/03/11 - Added SKU_Code to Alternate_Code2 product code fields
-----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Select_Products_PickList_ProductID
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT AP_Products_ID AS [ID],
           ISNULL(Product_Code, '') AS [Code],
           ISNULL([Description], '') AS [Product],
           ISNULL(SKU_Code, '') AS [SKU_Code],
           ISNULL(Supercession, '') AS [Supercession],
           ISNULL(Alternate_Code1, '') AS [Alternate_Code1],
           ISNULL(Alternate_Code2, '') AS [Alternate_Code2]
	FROM AP_Products
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY AP_Products_ID ASC

SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Price_Update_Products
--Purpose       :Select Promotion Product data
--Functionality :
--Date          :2004/02/16
--Authors       :TB
--Version       :1.0.0
--MODS          :11/03/04 - Added Product Description and Product Code to table and
--              :           Removed JOIN with AP_Products for rs updateability
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Select_Promotion_Products
    (
        @PromotionID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)
   
	SET @sql = ' SELECT '
    SET @sql = @sql + ' pp.AP_Promotion_Products_ID AS [PromoProductID], '
    SET @sql = @sql + ' pp.AP_Promotions_ID AS [PromoID], '
    SET @sql = @sql + ' pp.AP_Products_ID AS [ProdID], '
    SET @sql = @sql + ' pp.[Description] AS [Product], '
    SET @sql = @sql + ' pp.Product_Code AS [Code], '
    SET @sql = @sql + ' pp.Start_Date AS [Starts], '
    SET @sql = @sql + ' pp.End_Date AS [Ends], '
    SET @sql = @sql + ' pp.Slu_AW_Credit_Terms_ID AS [Terms], '
    SET @sql = @sql + ' pp.Selling_Price AS [Selling], '
    SET @sql = @sql + ' pp.Qty_Projected_Sales AS [Projected], '
    SET @sql = @sql + ' pp.Qty_Cutoff AS [Cutoff], '
    SET @sql = @sql + ' pp.Qty_Sold AS [Sold], '
    SET @sql = @sql + ' pp.Slu_AW_Active_ID AS [Status] '

    SET @sql = @sql + ' FROM AP_Promotion_Products pp '
--     SET @sql = @sql + '     INNER JOIN AP_Products p '
--     SET @sql = @sql + '         ON pp.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' WHERE pp.AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + '   AND pp.AP_Promotions_ID = ' + CONVERT(varchar(20), @PromotionID) + ' '
    SET @sql = @sql + ' ORDER BY pp.[Description] '




SET NOCOUNT OFF


EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Promotions_PickList
--Purpose       :Select Promotions for the Picklist
--Functionality :
--Parameters    :
--Date          :2004/02/17
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Select_Promotions_PickList
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT
            AP_Promotions_ID AS [ID],
            [Description] AS [Description],
            Start_Date AS [Starts],
            End_Date AS [Ends],
            Slu_AW_Active_ID AS [ActiveID]
	FROM AP_Promotions
	WHERE AW_User_Companies_ID = @Company_ID
    ORDER BY AP_Promotions_ID DESC


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Redundant_Products
--Purpose       :SELECT Redundant UNUSED Products with ZERO STOCK in target DB
--Date          :2007/04/27
--Authors       :TB
--MODS:         :
--2004.5.7 RGL	: 2012-11-01 Exclude levy Products
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Redundant_Products]
	(
        @CompanyID int
	)
AS

SET NOCOUNT ON

        SELECT a.AP_Products_ID AS [ProductID]
        FROM AP_Products a
            FULL OUTER JOIN AS_Transaction_Details b
                ON a.AP_Products_ID = b.AP_Products_ID
            FULL OUTER JOIN AO_GRV_Details c
                ON a.AP_Products_ID = c.AP_Products_ID
            FULL OUTER JOIN AO_Order_Details d
                ON a.AP_Products_ID = c.AP_Products_ID
        WHERE a.AW_User_Companies_ID = 1 AND
              b.AP_Products_ID IS NULL AND
              c.AP_Products_ID IS NULL AND
              d.AP_Products_ID IS NULL AND
              a.On_Hand = 0 AND
              a.Slu_AW_YesNo_Levy_Item = 0 AND
              IsNull(a.Slu_AW_YesNo_Levy_Item,0) = 0

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------
--Description   :sp_AP_Select_Reserved_Stock
--Purpose       :Fetches RESERVED for ONE ProductID in POS
--Date          :2009/06/04
--Authors       :TB
--MODS          :
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
---------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Reserved_Stock]
	(
        @CompanyID int,
    	@ProductID int
	)

AS

SET NOCOUNT ON


    SELECT  h.AW_User_Companies_ID AS [CompanyID],
            h.Sys_AW_Transaction_Types_ID AS [TranTypeID],
            h.AS_Transactions_ID AS [TranID],
            tt.[Description] AS [Type],
            ISNULL(c.Surname, '') + ISNULL(' ' + c.Firstnames, '')
            + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
            (d.Quantity + d.Back_Order) AS [Qty],
            d.Unit_Price AS [Unit Price],
            h.Transaction_Number AS [No],
            h.Transaction_Date AS [Date],
            ISNULL(h.Customer_Reference,'') AS [Order],
            ISNULL(h.Comment, '') AS [Comment],
            ISNULL(u.UserName, '') AS [User]
    FROM AS_Transactions h
         INNER JOIN AS_Transaction_Details d
             ON h.AS_Transactions_ID = d.AS_Transactions_ID
         INNER JOIN AC_Customers c
             ON c.AC_Customers_ID = h.AC_Customers_ID
         INNER JOIN Sys_AW_Transaction_Types tt
             ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
         INNER JOIN AW_Users u
             ON h.Lup_AS_Cashiers_ID = u.AW_Users_ID
    WHERE h.AW_User_Companies_ID = @CompanyID AND
          h.Slu_AW_Active_ID = 1 AND
          d.AP_Products_ID = @ProductID AND
         (h.Sys_AW_Transaction_Types_ID = 2 OR
          h.Sys_AW_Transaction_Types_ID = 16)
    ORDER BY [CompanyID], [TranTypeID], [Date]

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















---------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Exchange_Product
--Purpose       :Fetches Stock On Hand for ONE PRODUCT from Stock Exchange
--Date          :2004/01/13
--Authors       :TB
--MODS          :
--2004.3.2      :03/11/06 - Added @ShowCost parameter
---------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Select_Stock_Exchange_Product
	(
    	@ProductCode varchar(20),
        @ShowCost tinyint
	)

AS

SET NOCOUNT ON

	SELECT AP_Stock_Exchange_ID AS [ID],
           ISNULL(NodeName, '') AS [Branch],
           ISNULL(Product_Description, '') AS [Product],
           ISNULL(Product_Code, '') AS [Code],
           ISNULL(On_Hand, 0) AS [On Hand],
           ISNULL(On_Order, 0) AS [On Order],

           CASE WHEN @ShowCost = 1
                THEN Last_Cost
                ELSE 0
           END AS [Last Cost],

           CASE WHEN @ShowCost = 1
                THEN Average_Cost
                ELSE 0
           END AS [Average Cost],

           Count_Date AS [Count Date]
	FROM AP_Stock_Exchange
    WHERE Product_Code = @ProductCode
    ORDER BY On_Hand DESC


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Exchange_Products
--Purpose       :Select Product Exchange Update data
--Functionality :
--Date          :2004/01/13
--Authors       :TB
--Version       :1.0.0
--MODS          :10/05/06 - Renamed the is Stock Exchange procedure from
--              :           sp_AP_Select_Product_Exchange_Products to
--              :           sp_AP_Select_Stock_Exchange_Products
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AP_Select_Stock_Exchange_Products
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


	SET @sql = ' SELECT '
    SET @sql = @sql + ' AW_Remote_Access_ID AS [Branch ID], '
    SET @sql = @sql + ' NodeName AS [Branch], '
    SET @sql = @sql + ' AP_Products_ID AS [Product ID], '
    SET @sql = @sql + ' Product_Description AS [Product], '
    SET @sql = @sql + ' Product_Code AS [Code], '
    SET @sql = @sql + ' On_Hand AS [On Hand], '
    SET @sql = @sql + ' On_Order AS [On Order], '
    SET @sql = @sql + ' Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' Average_Cost AS [Average Cost], '
    SET @sql = @sql + ' Count_Date AS [Count Date] '
    SET @sql = @sql + ' FROM AP_Stock_Exchange '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + ' ORDER BY Product_Description '


SET NOCOUNT OFF


EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Transfer_Back_Orders
--Purpose       :
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2 RL	2015-11-29	:Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Stock_Transfer_Back_Orders]
    (
    	@CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @OrderType tinyint = 0,
        @SortOption tinyint = 0
    )

AS

SET NOCOUNT ON


    IF @OrderType = 0        --Back Orders
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Back_Order AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Back_Order <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Back_Order AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Back_Order <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Product], s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Back_Order AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Back_Order <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], s.Date_Captured
                END
        END

    ELSE                    --Stock Transfers
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Quantity AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Quantity <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Quantity AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						b.Description As [Bin],                       
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Quantity <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Product], s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Quantity AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Quantity <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], s.Date_Captured
                END
        END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Transfer_Customers
--Purpose       :Customer Lookup by filter arguments
--              :Lifted from sp_AS_POS_Customers_Select
--Parameters    :
--Date          :2009/08/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_AP_Select_Stock_Transfer_Customers
	(    
    	 @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT DISTINCT '        -- DISTINCT is NB NB
    SET @sql = @sql + ' a.Surname AS [Name], '
    SET @sql = @sql + ' a.Firstnames AS [FirstNames], '
    SET @sql = @sql + ' a.Cell_No AS [CellNo], '
    SET @sql = @sql + ' a.Street_Address AS [StreetAddress], '

    SET @sql = @sql + ' a.City AS [City], '
    SET @sql = @sql + ' a.Initials AS [Initials], '
    SET @sql = @sql + ' a.Tax_Number AS [TaxNumber], '
    SET @sql = @sql + ' a.Suburb AS [Suburb], '
    SET @sql = @sql + ' a.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' a.Home_Tel_No AS [HomeTelNo], '
    SET @sql = @sql + ' ISNULL(a.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '         SELECT SUM(ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0)) '
    SET @sql = @sql + '         FROM AS_Transactions h '
    SET @sql = @sql + '         WHERE h.AC_Customers_ID = a.AC_Customers_ID AND '
    SET @sql = @sql + '               ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) <> 0 AND '
    SET @sql = @sql + '              (h.Sys_AW_Transaction_Types_ID = 3 OR '      --Invoice
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 4 OR '      --Refund
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 5 OR '      --Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 7 OR '      --Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 15 OR '     --Interest Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 18 OR '     --Settlement Discount
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 21 OR '     --Back Office Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 22) '       --EFT Payment
    SET @sql = @sql + '         ), 0) AS [AccountBalance], '

    SET @sql = @sql + ' a.Work_Email AS [WorkEmail], '
    SET @sql = @sql + ' a.Notes AS [Notes], '
    SET @sql = @sql + ' a.Sys_AC_Account_Status_ID AS [AccountStatusID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Types_ID AS [CustomerTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Groups_ID AS [CustomerGroupID], '
    SET @sql = @sql + ' s.[Description] AS [AccountStatus], '
    SET @sql = @sql + ' ct.[Description] AS [CustomerType], '
    SET @sql = @sql + ' g.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' a.[User_ID] AS [UserID], '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' -1 as [ActorTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Discount_Categories_ID, '
    SET @sql = @sql + ' a.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(tc.Tax_Rate, 0) AS [CustTaxRate], '
    SET @sql = @sql + ' a.Slu_AW_Credit_Terms_ID AS [TermsID], '
    SET @sql = @sql + ' e.Terms_Value AS [TermsValue], '
    SET @sql = @sql + ' f.[Description] AS [AccountType], '
    SET @sql = @sql + ' a.Sys_AC_Account_Types_ID AS [AccountTypeID], '
    SET @sql = @sql + ' a.AW_YesNo_Net_Billing_ID AS [NetBilling], '
    SET @sql = @sql + ' a.AW_YesNo_Purchase_Order_ID AS [PurchaseOrder], '
    SET @sql = @sql + ' a.AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling], '
    SET @sql = @sql + ' a.Lup_AC_Markup_Categories_ID AS [CostPlusCategory], '
    SET @sql = @sql + ' a.Delivery_Post_Code AS [DelPostCode], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Credit_Limit AS [OverrideLimit], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Overdue AS [OverrideOverdue] '
    SET @sql = @sql + ' FROM AC_Customers a '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions b '
    SET @sql = @sql + '         ON a.AC_Customers_ID = b.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Comments c '
    SET @sql = @sql + '         ON c.AW_Comments_ID = b.AW_Comments_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Types ct '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '         ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Credit_Terms e '
    SET @sql = @sql + '         ON a.Slu_AW_Credit_Terms_ID = e.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Types f '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Groups g '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Groups_ID = g.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       a.Sys_AC_Account_Types_ID = 3 AND '
    SET @sql = @sql + '       a.Slu_AW_Active_ID = 1 '


    SET @sql = @sql + '   ORDER BY [Name] '



EXEC (@sql)




SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Transfer_Lups
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AP_Select_Stock_Transfer_Lups
    (
       	@Choice int,
       	@CustomerID int,
    	@CompanyID int
    )

AS

        IF @Choice = 1    --'Reps  **'
          	SELECT Lup_AS_Reps_ID AS [ID], Description 
            FROM Lup_AS_Reps
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]

        ELSE
        IF @Choice = 2    --'Active'
          	SELECT Slu_AW_Active_ID AS [ID],
                   [Description] AS [Description] 
            FROM Slu_AW_Active 
            ORDER BY [Description]

        ELSE
        IF @Choice = 3    --'Active' for Deactivate Transactions
          	SELECT Slu_AW_Active_ID AS [ID],
                   [Description] AS [Active] 
            FROM Slu_AW_Active 

        ELSE
        IF @Choice = 4    --Transaction Types
            SELECT Sys_AW_Transaction_Types_ID as [ID],
                   [Description]
            FROM Sys_AW_Transaction_Types
            WHERE Sys_AW_Transaction_Types_ID = 3 or 
                  Sys_AW_Transaction_Types_ID = 4 or 
                  Sys_AW_Transaction_Types_ID = 23
            ORDER BY Description

        ELSE
        IF @Choice = 5    --Customer E-Mail addresses
            BEGIN
                SELECT Orders_URL as [EMail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CustomerID

                UNION

                SELECT Home_Email as [EMail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CustomerID

                UNION

                SELECT Work_Email as [EMail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CustomerID
            END   

        ELSE
        IF @Choice = 6    --Volume Discount
        	SELECT Slu_AS_Volume_Discounts_ID as [ID],
                   ISNULL(Sales_Qty, 0) as [SalesQty],
                   ISNULL(Discount_Perc, 0) as [DiscPerc]
        	FROM Slu_AS_Volume_Discounts
            WHERE Slu_AW_Active_ID = 1
            ORDER BY [SalesQty]

        ELSE
        IF @Choice = 7    --Years
            BEGIN
            	SELECT Slu_AW_Years_ID AS [ID], 
                    	[Description] AS [Year] 
            	FROM Slu_AW_Years
            END
    
        ELSE 
        IF @Choice = 8    --Months
            BEGIN
            	SELECT Slu_AW_Months_ID AS [ID], 
                    	[Description] AS [Month] 
            	FROM Slu_AW_Months
            END












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Transfer_Products
--Purpose       :NEW sp_AP_Select_Stock_Transfer_Products select products for stock transfer
--				 sp_AS_POS_Products_Select was old proc used, but needed to change to new 
--				 to accommodate product bins
--Date          :2016/10/03
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Stock_Transfer_Products]
    (    
        @CompanyID int,
        @Filter1 varchar(50) = '',
        @Filter2 varchar(50) = '',
        @Filter3 varchar(50) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @SearchType tinyint

	IF @Filter3 <> ''
		BEGIN
			SET @Filter3 = '%' +  @Filter3 + '%'
			SET @Filter2 = '%' +  @Filter2 + '%'
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT 
        		p.AP_Products_ID as [ID],        	
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.On_Hand AS [Total On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        		
                pb.Description AS [Bin],
                b.On_Hand as [Qty On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock],
				--Job_Reserved AS [Job Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Res], 
				--Sales_Order_Reserved AS [S/O Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], 
				--Quote_Reserved AS [Quote Reserved]
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Res],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		p.Average_Cost AS [Avg Cost], 
        		p.Last_Cost AS [Last Cost], 
        		p.Pack_Size AS [Qty],
        		p.Standard_Cost AS [Std Cost],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],  
        		tc.Tax_Rate as [Tax Rate],                 
                pb.Lup_AP_Product_Bins_ID AS [Bin ID],
                
           		p.Slu_AW_YesNo_Edit_Price AS [Edit Price],
           		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                0 as [Discount %],
                0 as [Discount],
				p.Pack_Mass AS [Pack Mass]
                
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  p.Description like @Filter2 AND
                  p.Description like @Filter3 ) OR 
                 (p.Product_Code like @Filter1 AND
                  p.Product_Code like @Filter2 AND
                  p.Product_Code like @Filter3) OR
                 (p.SKU_Code like @Filter1 AND
                  p.SKU_Code like @Filter2 AND
                  p.SKU_Code like @Filter3) OR
                 (p.Supercession like @Filter1 AND
                  p.Supercession like @Filter2 AND
                  p.Supercession like @Filter3) OR
                 (p.Alternate_Code1 like @Filter1 AND
                  p.Alternate_Code1 like @Filter2 AND
                  p.Alternate_Code1 like @Filter3) OR
                 (p.Alternate_Code2 like @Filter1 AND
                  p.Alternate_Code2 like @Filter2 AND
                  p.Alternate_Code2 like @Filter3) OR
                 (p.Keywords like @Filter1 AND
                  p.Keywords like @Filter2 AND
                  p.Keywords like @Filter3))
			ORDER BY [Qty on Hand] DESC, p.Description


		END
	ELSE
	IF @Filter2 <>''
		BEGIN 
			SET @Filter2 = '%' +  @Filter2 + '%'
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT 
        		p.AP_Products_ID as [ID],        	
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.On_Hand AS [Total On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        		
                pb.Description AS [Bin],
                b.On_Hand as [Qty On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Qty],
				--Job_Reserved AS [Job Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Res], 
				--Sales_Order_Reserved AS [S/O Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], 
				--Quote_Reserved AS [Quote Reserved]
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Res],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		p.Average_Cost AS [Avg Cost], 
        		p.Last_Cost AS [Last Cost], 
        		p.Pack_Size AS [Qty],
        		p.Standard_Cost AS [Std Cost],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],  
        		tc.Tax_Rate as [Tax Rate],                 
                pb.Lup_AP_Product_Bins_ID AS [Bin ID],
                
           		p.Slu_AW_YesNo_Edit_Price AS [Edit Price],
           		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                0 as [Discount %],
                0 as [Discount],
				p.Pack_Mass AS [Pack Mass]
                
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  p.Description like @Filter2) OR 
                 (p.Product_Code like @Filter1 AND
                  p.Product_Code like @Filter2) OR
                 (p.SKU_Code like @Filter1 AND
                  p.SKU_Code like @Filter2) OR
                 (p.Supercession like @Filter1 AND
                  p.Supercession like @Filter2) OR
                 (p.Alternate_Code1 like @Filter1 AND
                  p.Alternate_Code1 like @Filter2) OR
                 (p.Alternate_Code2 like @Filter1 AND
                  p.Alternate_Code2 like @Filter2) OR
                 (p.Keywords like @Filter1 AND
                  p.Keywords like @Filter2))
			ORDER BY [Qty on Hand] DESC, p.Description


		END
	ELSE
	IF @Filter1 <> ''
		BEGIN
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT 
        		p.AP_Products_ID as [ID],        	
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.On_Hand AS [Total On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        		
                pb.Description AS [Bin],
                b.On_Hand as [Qty On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Qty],
				--Job_Reserved AS [Job Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Res], 
				--Sales_Order_Reserved AS [S/O Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], 
				--Quote_Reserved AS [Quote Reserved]
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Res],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		p.Average_Cost AS [Avg Cost], 
        		p.Last_Cost AS [Last Cost], 
        		p.Pack_Size AS [Qty],
        		p.Standard_Cost AS [Std Cost],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],  
        		tc.Tax_Rate as [Tax Rate],                 
                pb.Lup_AP_Product_Bins_ID AS [Bin ID],
                
           		p.Slu_AW_YesNo_Edit_Price AS [Edit Price],
           		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                0 as [Discount %],
                0 as [Discount],
				p.Pack_Mass AS [Pack Mass]
                
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                 (p.Description like @Filter1 OR
                  p.Product_Code like @Filter1 OR
                  p.SKU_Code like @Filter1 OR
                  p.Supercession like @Filter1 OR
                  p.Alternate_Code1 like @Filter1 OR
                  p.Alternate_Code2 like @Filter1 OR
                  p.Keywords like @Filter1)
			ORDER BY [Qty on Hand] DESC, p.Description

		END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-----------------------------------------------------------------------------
--Description  :sp_AP_Select_Stock_Valuations
--Purpose      :Retrieves Stock On-Hand Data for Inventory Month-End
--Date         :2002/02/19
--Revised      :
--Authors      :TB
--Version      :1.0.0
-----------------------------------------------------------------------------

CREATE        PROC sp_AP_Select_Stock_Valuations
    (
        @ProcedureTypeID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AW_Period_Procedures_ID as [ID],
          [Description],
           Date_Captured as [Date]
    FROM AW_Period_Procedures
    WHERE Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Date_Captured DESC

SET NOCOUNT OFF





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Top_Product_ID
--Purpose       :Select FIRST ot LAST Product ID
--Functionality :
--Date          :2002/09/05
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Select_Top_Product_ID
	(
    	@CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AP_Products_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AP_Products_ID
            FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AP_Products_ID
        END

    ELSE

--> Get the LAST AP_Products_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AP_Products_ID
            FROM AP_Products
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AP_Products_ID DESC
        END

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















--EXEC sp_AO_Select_Products_With_Sales 1, '2003/01/01 00:00:01', '2003/08/01 23:59:59'

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Touched_Products
--Purpose       :Selects products for inventory replenishment with attributes:
--              :    Conditional upon:
--              :    1.    Product has sales
--              :    2.    Product has stock
--              :    3.    MSL <> 0
--              :    4.    MIN <> 0
--              :    5.    MAX <> 0
--              :    6.    Product has Outstanding Orders (possibly NEW product)
--              :    7.    Product is ACTIVE
--Functionality :Uses TABLE datatype
--Date          :2004/12/07
--Authors       :TB
--Version       :19/10/03 - Added NEW temp table method.
--              :           This drops execution time from 4 minutes to 5 seconds.
--              :23/10/03 - Modified to use TABLE datatype instead of a #TempTable
--              :           and now selects ORDERS from SALES instead of SALES
--              :           from ORDERS which improves execution speed a further 2x
--2004.4.9      :03/10/10 - Replaced '1' with @CompanyID in each WHERE clause !!!!!
--2004.5.2      :06/07/11 - Added Inventory Adjustments and GRV Details sections
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Select_Touched_Products
    (
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime
    )
AS

SET NOCOUNT ON

---------------------------------------------
--> NEW 23/10/03 using TABLE datatype
---------------------------------------------
    DECLARE @ActiveProducts table
                (
                    [AP_Products_ID] int
                )

    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AS_Transaction_Details
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AO_Order_Details od
        INNER JOIN AO_Orders oh
            ON od.AO_Orders_ID = oh.AO_Orders_ID
    WHERE oh.AW_User_Companies_ID = @CompanyID AND
          oh.Slu_AW_Active_ID = 1 AND
          oh.Date_Ordered IS NOT NULL AND
          oh.Complete <> 1 AND
          ISNULL(od.Order_Qty, 0) +
          ISNULL(od.Back_Order_Qty, 0) -
          ISNULL(od.Received_Qty, 0) > 0 AND
          dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AP_Inventory_Adjustments
    WHERE AW_User_Companies_ID = @CompanyID AND
         (Sys_AP_Adjustment_Types_ID = 1 OR
          Sys_AP_Adjustment_Types_ID = 6) AND
          ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0 AND
          Date_Captured >= @StartDate


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AO_GRV_Details
    WHERE AW_User_Companies_ID = @CompanyID AND
          ISNULL(Qty, 0) <> 0 AND
          Date_Captured >= @StartDate


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AP_Products
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          (
              On_Hand <> 0 OR
              Min_Stock_Level <> 0 OR
              Min_Order_Qty <> 0 OR
              Max_Order_Qty <> 0
          )


	SELECT DISTINCT a.AP_Products_ID AS [ID],
           ISNULL(b.Product_Code, '') AS [Code],
           ISNULL(b.[Description], '') AS [Product]
    FROM @ActiveProducts a
        INNER JOIN AP_Products b
            ON a.AP_Products_ID = b.AP_Products_ID
    ORDER BY [Product]



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--------------------------------------------------------------------------------
--Description   :sp_AP_Set_Stock_Take_Count
--Purpose       :Assign Stock Take Count = Variance
--Date          :2009/04/29
--Authors       :TB
--Mods          :
--------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Set_Stock_Take_Count
    (
    	@StockTakeProcedureID int,
        @UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int


    BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
        BEGIN TRANSACTION


            UPDATE AP_Products_Stock_Takes
            SET Count1 = ISNULL(On_Hand, 0),
                Total_Count = ISNULL(On_Hand, 0),
                Variance = ISNULL(On_Hand, 0) - ISNULL(On_Hand, 0),
                User_ID = @UserID
            WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
                  AW_User_Companies_ID = @CompanyID AND
                  ISNULL(On_Hand, 0) <> 0 AND
                  Total_Count = 0


	    COMMIT TRANSACTION

        SET @ReturnValue = 1

    END



RETURN @ReturnValue


SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Shape_Stock_Transfer_Detail
--Purpose       :Selects Customer Stock Transfer Detail Shaped
--Date          :21 AUG 2009
--Authors       :TB
--Mods          :
--V6.2 RL	2015-11-29	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Shape_Stock_Transfer_Detail] 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON


    SELECT d.AS_Transaction_Details_ID AS [ID],
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product],
           p.Product_Code AS [Code],
           d.Unit_Price AS [Unit Price],
           d.Quantity AS [Qty],
           d.Back_Order AS [B/O],
           d.Discount_Amount AS [Discount],
           CONVERT(money, (d.Extended_Amount - d.Tax_Amount)) AS [Amount],
           d.Tax_Amount AS [Tax],
           d.Extended_Amount AS [Total],
           d.Original_Price AS [Orig Price],
           CASE WHEN (d.Extended_Amount - d.Tax_Amount) <> 0
                THEN CONVERT(decimal(9, 3), ROUND((d.Tax_Amount / (d.Extended_Amount - d.Tax_Amount)) * 100, 2))
                ELSE 0.00
           END AS [Tax Rate],
           d.Unit_Cost AS [Unit Cost],
           b.Description As [Bin]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN Lup_AP_Product_Bins b
			On b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
    WHERE d.AS_Transactions_ID = @TransactionID
    ORDER BY [ID]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Shape_Stock_Transfer_Header
--Purpose       :Selects Customer Stock Transfer Header Shaped
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AP_Shape_Stock_Transfer_Header
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @Option tinyint = 0
	)

AS

SET NOCOUNT ON


    IF @Option = 0        --> All Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [TRF No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(ch.Transaction_Number, '') AS [Doc No],
                ISNULL(ch.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                LEFT JOIN AS_Transactions_Xref_Sources xd
                    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                LEFT JOIN AS_Transactions_Xref xh
                    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                LEFT JOIN AS_Transactions ch
                    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 1        --> Uninvoiced Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [TRF No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(ch.Transaction_Number, '') AS [Doc No],
                ISNULL(ch.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                LEFT JOIN AS_Transactions_Xref_Sources xd
                    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                LEFT JOIN AS_Transactions_Xref xh
                    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                LEFT JOIN AS_Transactions ch
                    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID = 1 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 2        --> Invoiced Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [TRF No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(ch.Transaction_Number, '') AS [Doc No],
                ISNULL(ch.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                LEFT JOIN AS_Transactions_Xref_Sources xd
                    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                LEFT JOIN AS_Transactions_Xref xh
                    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                LEFT JOIN AS_Transactions ch
                    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID = 0 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 3        --> Cancelled Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [TRF No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(ch.Transaction_Number, '') AS [Doc No],
                ISNULL(ch.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                LEFT JOIN AS_Transactions_Xref_Sources xd
                    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                LEFT JOIN AS_Transactions_Xref xh
                    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                LEFT JOIN AS_Transactions ch
                    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID > 1 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AP_Shipping_Product_Select
--Purpose       :Stock Transfer
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Shipping_Product_Select
    (    
        @ProductID int
    )

AS

SET NOCOUNT ON


	SELECT 
		p.AP_Products_ID as [ID],
		p.Description,
		ISNULL(p.Product_Code, '') as [Code],
		p.Last_Cost AS [Last Cost],
		p.Average_Cost AS [Avg Cost],
		p.Standard_Cost AS [Std Cost],
		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
		tc.Tax_Rate as [Tax Rate]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
	WHERE p.AP_Products_ID = @ProductID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-----------------------------------------------------------------------------
--Description   :sp_AP_Stock_Bonded_Lups
--Purpose       :Bonded Stock Lookups
--Date          :2010/09/08
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Stock_Bonded_Lups
    (
    	@Choice int,
        @Value int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON


    --> Shipping Agents
        IF @Choice = 1
        	SELECT Lup_AP_Shipping_Agents_ID as [ID],
                   Description as [Agent],
                   Customer_Code as [Customer Code],
                   Warehouse_No as [Warehouse No]
        	FROM Lup_AP_Shipping_Agents
        	WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Agent]

    --> Shipping Agent Files (Bonded Stock Interfaces)
        ELSE
        IF @Choice = 2
        	SELECT Lup_AP_Shipping_Agent_Files_ID as [ID],
                   Description as [Description],
                   Server_Name as [Server Name],
                   Login_Name as [Login Name],
                   Login_Password as [Password],
                   Folder as [Folder]
        	FROM Lup_AP_Shipping_Agent_Files
        	WHERE AW_User_Companies_ID = @CompanyID AND
                  Lup_AP_Shipping_Agents_ID = @Value AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Years
        ELSE
        IF @Choice = 3 
        	SELECT Slu_AW_Years_ID AS [ID], 
            [Description] AS [Year] 
        	FROM Slu_AW_Years
        
    --> Months
        ELSE 
        IF @Choice = 4
        	SELECT Slu_AW_Months_ID AS [ID], 
            [Description] AS [Month] 
        	FROM Slu_AW_Months

	--> User
    	ELSE 
    	IF @Choice = 5
            SELECT AW_Users_ID AS [ID],
                   ISNULL(UserName, '') AS [User]
            FROM AW_Users
            ORDER BY [User]


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :sp_AP_Stock_Take_Lups
--Purpose       :Product Stock Take Lookups
--Date          :2009/02/15
--Authors       :TB
--MODS          :
--2004.4.4      :30/04/09 - Added Choice 10 - User
--V6.2	RL	2015-12-01	:Added Product Bins
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Stock_Take_Lups]
    (
    	@Choice int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

    --> 1 - Product Types
    	IF @Choice = 1
    		SELECT Lup_AP_Product_Types_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 2 - Product Groups
    	ELSE 
    	IF @Choice = 2	
    		SELECT Lup_AP_Product_Groups_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 3 - Product Departments
    	ELSE 
    	IF @Choice = 3	
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Departments	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 4 - Product Locations
    	ELSE 
    	IF @Choice = 4	
    		SELECT Lup_AP_Product_Locations_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Locations	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 5 - Product Manufacturers
    	ELSE 
    	IF @Choice = 5
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 6 - Default Supplier
    	ELSE 
    	IF @Choice = 6
    		SELECT AO_Suppliers_ID AS [ID], 
    		[Supplier_Name] AS [Supplier_Name] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Supplier_Name]
    
    --> 7 - Purchase Categories
    	ELSE 
    	IF @Choice = 7	
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Purchase_Categories	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]

    --> Years
        ELSE
        IF @Choice = 8 
        	SELECT Slu_AW_Years_ID AS [ID], 
            [Description] AS [Year] 
        	FROM Slu_AW_Years
        
    --> Months
        ELSE 
        IF @Choice = 9
        	SELECT Slu_AW_Months_ID AS [ID], 
            [Description] AS [Month] 
        	FROM Slu_AW_Months

	--> User
    	ELSE 
    	IF @Choice = 10
            SELECT AW_Users_ID AS [ID],
                   ISNULL(UserName, '') AS [User]
            FROM AW_Users
            ORDER BY [User]

	--> Product Bins
    	ELSE 
    	IF @Choice = 11
            SELECT Lup_AP_Product_Bins_ID AS [ID],
                   [Description] AS [Description] 
            FROM Lup_AP_Product_Bins
            ORDER BY [Description]

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AP_Stock_Takes_Picklist
--Purpose       :Fetch a list of Stock Take Procedures
--Date          :2003/08/15
--Authors       :TB
--MODS          :
--2004.4.3      :15/02/09 - Removed @ProcedureTypeID inout parameter - redundant
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Stock_Takes_Picklist
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT AP_Stock_Take_Procedures_ID AS [ID],
           Procedure_Date AS [Date],
           [Description]
    FROM AP_Stock_Take_Procedures
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY Date_Captured DESC


SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_AP_Stock_Transfer_GL_Insert
--Purpose       :Post Stock Transfer GL Journal to Stock-in-Transit and
--              :UPDATE the Stock Transfer Log
--Date          :22 AUG 2009
--Authors       :TB
--Mods          :
--2004.4.9      :03/10/10 - Added @TransferType input parameter
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AP_Stock_Transfer_GL_Insert
	(
        @CustomerName varchar(40),
        @ASTranHeaderID int,
        @MonthID int,
        @YearID int,
        @TransferType varchar(30),
        @TotalCost money,
        @TotalAmount money,
        @TotalTax money,
        @TotalTotal money,
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @GLVATControl int,
            @GLSTIControl int,
            @GLInventoryControl int,
            @GLStockInTransitControl int,
            @TranDate DateTime,
            @RefNo varchar(20),
            @NextGLTranNo varchar(20),
            @JNLHeaderID int,
            @GLTranID int,
            @ABSourceRef varchar(20),
            @Narration varchar(50),
            @GPIncome money,
            @Comment varchar(20),
            @InsertGLTran bit,
            @RetCode int


    SET @NextGLTranNo = ''
    SET @JNLHeaderID = 0
    SET @ABSourceRef = CONVERT(varchar(20), @ASTranHeaderID)

    SET @TranDate = getdate()
    SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
    SET @RetCode = 0


    -------------------------------------------------------------------------------
    --> UPDATE GL TRANSACTIONS
    -------------------------------------------------------------------------------

    --> Get V.A.T. CONTROL
    SELECT @GLVATControl = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 401


    --> Get STOCK TRANSFER INCOME CONTROL
    SELECT @GLSTIControl = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 108


    --> Get INVENTORY CONTROL
    SELECT @GLInventoryControl = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 601


    --> Get STOCK-IN-TRANSIT CONTROL
    SELECT @GLStockInTransitControl = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 602


    SET @Narration = LEFT(@TransferType + @CustomerName, 50)

    --> INSERT NORMAL JOURNAL header
    EXEC @NextGLTranNo = sp_AB_Next_Transaction_Number 15, @CompanyID


    EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                            @TranDate,
                            @NextGLTranNo,
                            @Narration,
                            @MonthID,
                            @YearID,
                            @UserID,
                            @CompanyID


    --> INSERT JOURNAL DETAIL for STOCK-IN-TRANSIT CONTROL
    EXEC sp_AB_Insert_Journal_Detail
            @JNLHeaderID,
            @GLStockInTransitControl,
            @TotalTotal,
            @Narration,
            @UserID,
            @CompanyID,
            @InsertGLTran

    --> INSERT GL TRANSACTION for STOCK-IN-TRANSIT CONTROL and GET the NEW GLTranID
    EXEC @GLTranID = sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLStockInTransitControl,
                            @TranDate,
                            @ABSourceRef,
                            @MonthID,
                            @YearID,
                            @NextGLTranNo,
                            @TotalTotal,
                            @UserID,
                            @CompanyID


    SET @GPIncome =  @TotalAmount - @TotalCost        --If PROFIT @GPIncome = POSITIVE

    IF @GPIncome <> 0
        BEGIN
            SET @GPIncome = @GPIncome * -1

            --> INSERT JOURNAL DETAIL for STOCK TRANSFER INCOME CONTROL
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @GLSTIControl,
                    @GPIncome,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> INSERT GL TRANSACTION for STOCK TRANSFER INCOME CONTROL
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @GLSTIControl,
                    @TranDate,
                    @ABSourceRef,
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @GPIncome,
                    @UserID,
                    @CompanyID
        END


    IF @TotalTax <> 0
        BEGIN
            SET @TotalTax = @TotalTax * -1

            --> INSERT JOURNAL DETAIL for V.A.T. CONTROL
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @GLVATControl,
                    @TotalTax,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> INSERT GL TRANSACTION for V.A.T. CONTROL
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @GLVATControl,
                    @TranDate,
                    @ABSourceRef,
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @TotalTax,
                    @UserID,
                    @CompanyID
        END


    --> Reverse signs to balance double entry
    SET @TotalCost = @TotalCost * -1

    --> INSERT JOURNAL DETAIL for INVENTORY CONTROL
    EXEC sp_AB_Insert_Journal_Detail
            @JNLHeaderID,
            @GLInventoryControl,
            @TotalCost,
            @Narration,
            @UserID,
            @CompanyID,
            @InsertGLTran

    --> INSERT GL TRANSACTION for INVENTORY CONTROL
    EXEC sp_AB_Insert_GL_Transactions
            @Narration,
            15,
            @GLInventoryControl,
            @TranDate,
            @ABSourceRef,
            @MonthID,
            @YearID,
            @NextGLTranNo,
            @TotalCost,
            @UserID,
            @CompanyID


    --> UPDATE Stock Transfer Log
		UPDATE AP_Stock_Transfer_Log
        SET AB_GL_Transactions_ID = @GLTranID,
            AB_Transaction_Ref = @NextGLTranNo,
            AB_Source_Ref = @ABSourceRef
        WHERE AS_Transactions_ID = @ASTranHeaderID


    SET @RetCode = @GLTranID


RETURN @RetCode













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Stock_Transfer_Log
--Purpose       :Selects Stock Transfer Log
--Date          :27 AUG 2009
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Stock_Transfer_Log]
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint = 0
	)

AS

SET NOCOUNT ON


        IF @SortOrder = 0
            BEGIN
                SELECT
                    l.AS_Transactions_ID AS [ID],
                    l.AC_Customers_ID AS [CustomerID],
                    l.AP_Products_ID AS [ProductID],
                    l.AB_GL_Transactions_ID AS [SITGLID],
                    l.AB_Transaction_Ref AS [GLRefID],
                    l.AB_Source_Ref AS [GLSourceRef],
                    l.Transaction_Date AS [Tranfer Date],
                    ISNULL(c.Surname, '') AS [Customer],
                    ISNULL(h.Transaction_Number, '') AS [Trf No],
                    ISNULL(gl.Description, '') AS [GL Account],
                    m.[Description] AS [Month],
                    y.[Description] AS [Year],
                    CONVERT(datetime, CONVERT(CHAR(10), l.Date_Received, 121)) AS [Received], 
                    l.AO_GRV_ID AS [GRV No],
                    tu.UserName AS [SIT User],
                    ISNULL(p.Description, '') AS [Product],
                    ISNULL(p.Product_Code, '') AS [Code],
                    l.Quantity AS [Qty],
                    b.Description As [Bin],
                    l.Original_Price AS [Orig Price],
                    l.Unit_Cost AS [Cost],
                    l.Unit_Price AS [Unit Price],
                    l.Discount_Amount AS [Discount],
                    l.Amount AS [Amount],
                    l.Tax_Amount AS [Tax],
                    l.Extended_Amount AS [Total],
                    h.Comment AS [Notes],
                    u.UserName AS [User]
                FROM AP_Stock_Transfer_Log l
                    INNER JOIN AS_Transactions h
                        ON l.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AC_Customers c
                        ON l.AC_Customers_ID = c.AC_Customers_ID
                    INNER JOIN AP_Products p
                        ON l.AP_Products_ID = p.AP_Products_ID
                    INNER JOIN AB_GL_Transactions gt
                        ON l.AB_GL_Transactions_ID = gt.AB_GL_Transactions_ID
                    INNER JOIN AB_Accounts gl
                        ON gt.AB_Accounts_ID = gl.AB_Accounts_ID
                    LEFT JOIN Slu_AW_Months m
                        ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                        ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                    LEFT JOIN AW_Users u
                        ON l.TRF_User_ID = u.AW_Users_ID
                    LEFT JOIN AW_Users tu
                        ON l.SIT_User_ID = tu.AW_Users_ID
					LEFT JOIN Lup_AP_Product_Bins b
						On b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Transaction_Date, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Transaction_Date, @EndDate) >= 0)
                ORDER BY [Tranfer Date]
            END
        ELSE
        IF @SortOrder = 1
            BEGIN
                SELECT
                    l.AS_Transactions_ID AS [ID],
                    l.AC_Customers_ID AS [CustomerID],
                    l.AP_Products_ID AS [ProductID],
                    l.AB_GL_Transactions_ID AS [SITGLID],
                    l.AB_Transaction_Ref AS [GLRefID],
                    l.AB_Source_Ref AS [GLSourceRef],
                    l.Transaction_Date AS [Tranfer Date],
                    ISNULL(c.Surname, '') AS [Customer],
                    ISNULL(h.Transaction_Number, '') AS [Trf No],
                    ISNULL(gl.Description, '') AS [GL Account],
                    m.[Description] AS [Month],
                    y.[Description] AS [Year],
                    CONVERT(datetime, CONVERT(CHAR(10), l.Date_Received, 121)) AS [Received], 
                    l.AO_GRV_ID AS [GRV No],
                    tu.UserName AS [SIT User],
                    ISNULL(p.Description, '') AS [Product],
                    ISNULL(p.Product_Code, '') AS [Code],
                    l.Quantity AS [Qty],
                    b.Description As [Bin],
                    l.Original_Price AS [Orig Price],
                    l.Unit_Cost AS [Cost],
                    l.Unit_Price AS [Unit Price],
                    l.Discount_Amount AS [Discount],
                    l.Amount AS [Amount],
                    l.Tax_Amount AS [Tax],
                    l.Extended_Amount AS [Total],
                    h.Comment AS [Notes],
                    u.UserName AS [User]
                FROM AP_Stock_Transfer_Log l
                    INNER JOIN AS_Transactions h
                        ON l.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AC_Customers c
                        ON l.AC_Customers_ID = c.AC_Customers_ID
                    INNER JOIN AP_Products p
                        ON l.AP_Products_ID = p.AP_Products_ID
                    INNER JOIN AB_GL_Transactions gt
                        ON l.AB_GL_Transactions_ID = gt.AB_GL_Transactions_ID
                    INNER JOIN AB_Accounts gl
                        ON gt.AB_Accounts_ID = gl.AB_Accounts_ID
                    LEFT JOIN Slu_AW_Months m
                        ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                        ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                    LEFT JOIN AW_Users u
                        ON l.TRF_User_ID = u.AW_Users_ID
                    LEFT JOIN AW_Users tu
                        ON l.SIT_User_ID = tu.AW_Users_ID
					LEFT JOIN Lup_AP_Product_Bins b
						On b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Transaction_Date, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Transaction_Date, @EndDate) >= 0)
                ORDER BY [Product], [Tranfer Date]
            END
        ELSE
        IF @SortOrder = 2
            BEGIN
                SELECT
                    l.AS_Transactions_ID AS [ID],
                    l.AC_Customers_ID AS [CustomerID],
                    l.AP_Products_ID AS [ProductID],
                    l.AB_GL_Transactions_ID AS [SITGLID],
                    l.AB_Transaction_Ref AS [GLRefID],
                    l.AB_Source_Ref AS [GLSourceRef],
                    l.Transaction_Date AS [Tranfer Date],
                    ISNULL(c.Surname, '') AS [Customer],
                    ISNULL(h.Transaction_Number, '') AS [Trf No],
                    ISNULL(gl.Description, '') AS [GL Account],
                    m.[Description] AS [Month],
                    y.[Description] AS [Year],
                    CONVERT(datetime, CONVERT(CHAR(10), l.Date_Received, 121)) AS [Received], 
                    l.AO_GRV_ID AS [GRV No],
                    tu.UserName AS [SIT User],
                    ISNULL(p.Description, '') AS [Product],
                    ISNULL(p.Product_Code, '') AS [Code],
                    l.Quantity AS [Qty],
                    b.Description As [Bin],
                    l.Original_Price AS [Orig Price],
                    l.Unit_Cost AS [Cost],
                    l.Unit_Price AS [Unit Price],
                    l.Discount_Amount AS [Discount],
                    l.Amount AS [Amount],
                    l.Tax_Amount AS [Tax],
                    l.Extended_Amount AS [Total],
                    h.Comment AS [Notes],
                    u.UserName AS [User]
                FROM AP_Stock_Transfer_Log l
                    INNER JOIN AS_Transactions h
                        ON l.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AC_Customers c
                        ON l.AC_Customers_ID = c.AC_Customers_ID
                    INNER JOIN AP_Products p
                        ON l.AP_Products_ID = p.AP_Products_ID
                    INNER JOIN AB_GL_Transactions gt
                        ON l.AB_GL_Transactions_ID = gt.AB_GL_Transactions_ID
                    INNER JOIN AB_Accounts gl
                        ON gt.AB_Accounts_ID = gl.AB_Accounts_ID
                    LEFT JOIN Slu_AW_Months m
                        ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                        ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                    LEFT JOIN AW_Users u
                        ON l.TRF_User_ID = u.AW_Users_ID
                    LEFT JOIN AW_Users tu
                        ON l.SIT_User_ID = tu.AW_Users_ID
					LEFT JOIN Lup_AP_Product_Bins b
						On b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Transaction_Date, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Transaction_Date, @EndDate) >= 0)
                ORDER BY [Customer], [Tranfer Date]
            END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AP_Stock_Transfer_Log_Insert_Update
--Purpose       :Insert/Update Stock Transfer Log
--Date          :27 AUG 2009
--Authors       :TB
--MODS          :
--V6.2 RL	2015-11-29	:Added Product Bins
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Stock_Transfer_Log_Insert_Update]
	(
        @ASTranID int = NULL,
        @CustomerID int = NULL, 
        @ProductID int = NULL, 
        @GLTranID int = NULL, 
        @GLTranRef int = NULL, 
        @GLSourceRef varchar(20) = NULL, 
        @Qty decimal(12, 3) = NULL, 
        @OrigPrice money = NULL, 
        @UnitCost money = NULL, 
        @UnitPrice money = NULL, 
        @DiscAmount money = NULL, 
        @Amount money = NULL, 
        @TaxAmount money = NULL, 
        @TotalAmount money = NULL, 
        @GRVID int = NULL, 
        @DateReceived datetime = NULL, 
        @BinID	int,
        @SITUserID int = NULL, 
        @TRFUserID int = NULL, 
        @CompanyID int = NULL, 
        @TrfLogID int = NULL OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @TranDate datetime,
            @DateCaptured datetime


    SET @TranDate = getdate()
    SET @DateCaptured = @TranDate


    IF @ASTranID > 0
        BEGIN
            SELECT @TranDate = Transaction_Date,
                   @DateCaptured = Date_Captured
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @ASTranID
        END


	IF @TrfLogID IS NULL OR @TrfLogID = 0
		BEGIN
			INSERT AP_Stock_Transfer_Log
                (
                    AS_Transactions_ID,
                    AC_Customers_ID,
                    AP_Products_ID,
                    AB_GL_Transactions_ID,
                    AB_Transaction_Ref,
                    AB_Source_Ref,
                    Transaction_Date,
                    Quantity,
                    Original_Price,
                    Unit_Cost,
                    Unit_Price,
                    Discount_Amount,
                    Amount,
                    Tax_Amount,
                    Extended_Amount,
                    AO_GRV_ID,
                    Date_Received,
                    SIT_User_ID,
                    Date_Captured,
                    TRF_User_ID,
                    AW_User_Companies_ID,
                    Lup_AP_Product_Bins_ID
                )
			VALUES
				(
                    @ASTranID,
                    @CustomerID,
                    @ProductID,
                    @GLTranID,
                    @GLTranRef,
                    @GLSourceRef,
                    @TranDate,
                    @Qty,
                    @OrigPrice,
                    @UnitCost,
                    @UnitPrice,
                    @DiscAmount,
                    @Amount,
                    @TaxAmount,
                    @TotalAmount,
                    @GRVID,
                    @DateReceived,
                    @SITUserID,
                    @DateCaptured,
                    @TRFUserID,
                    @CompanyID,
                    @BinID
				)
			SELECT @TrfLogID = Scope_Identity()
		END		
	ELSE
        BEGIN
    		UPDATE AP_Stock_Transfer_Log
            SET AS_Transactions_ID = @ASTranID,
                AC_Customers_ID = @CustomerID,
                AP_Products_ID =  @ProductID,
                AB_GL_Transactions_ID = @GLTranID,
                AB_Transaction_Ref = @GLTranRef,
                AB_Source_Ref = @GLSourceRef,
                Transaction_Date = @TranDate,
                Quantity = @Qty,
                Original_Price = @OrigPrice,
                Unit_Cost = @UnitCost,
                Unit_Price = @UnitPrice,
                Discount_Amount = @DiscAmount,
                Amount = @Amount,
                Tax_Amount = @TaxAmount,
                Extended_Amount = @TotalAmount,
                AO_GRV_ID = @GRVID,
                Date_Received = @DateReceived,
                SIT_User_ID = @SITUserID,
                Date_Captured = @DateCaptured,
                TRF_User_ID = @TRFUserID,
                AW_User_Companies_ID = @CompanyID,
                Lup_AP_Product_Bins_ID = @BinID
            WHERE AP_Stock_Transfer_Log_ID = @TrfLogID
        END


	RETURN @TrfLogID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE  PROCEDURE sp_AP_Switch1_Select
	(
		@CompanyID int
	)
AS
	SET NOCOUNT OFF
	SELECT 
		AP_Switch1_ID as ID, 
		Description as Make,
		AW_User_Companies_ID as Company_ID
	FROM AP_Switch1
	WHERE AW_User_Companies_ID = @CompanyID
			AND Slu_AW_Active_ID <> 0 







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE PROCEDURE sp_AP_Switch2_Select
(
	@Switch1ID int
)
AS
	SELECT 
		AP_Switch2_ID as ID, 
		Description as Model , 
		AP_Switch1_Id as FKID,
		Lup_AP_Switch2_Types_ID as Type
		--Rim_Front,
		--Rim_Rear,
		--Tyre_Front,
		--Tyre_Rear,
		--Front_Susp1,
		--Front_Susp2,
		--Rear_Susp1,
		--Rear_Susp2
	FROM dbo.AP_Switch2 
	WHERE Slu_AW_Active_ID <> 0 AND
		AP_Switch1_ID = @Switch1ID





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








CREATE    PROCEDURE sp_AP_Switch3_Select
(
	@Switch2ID int
)
AS
	SELECT 
    	AP_Switch3_ID as ID,
    	Description as [Year],
    	From_Year,
    	To_Year,
    	AP_Switch2_ID as FKID
	FROM dbo.AP_Switch3
	WHERE Slu_AW_Active_ID <> 0  AND
		AP_Switch2_ID = @Switch2ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description    : Gets the switches
--Purpose        :
--Used By        :
--Functionality  :
--Parameters     :
--Date           : 2000/12/08
--Authors        : TB,GL
--Version        :
-------------------------------------------------------------------------------------------------
--To Do
--
-------------------------------------------------------------------------------------------------
--Mods

-------------------------------------------------------------------------------------------------

CREATE  Procedure sp_AP_Switches
(
		@Parameter1 int = 1 ,
		@Parameter2 int = 0,
		@Parameter3 int = 0,
		@Parameter4 int = 0,
        @Parameter5 int = 0
)
As
	set nocount on
--Switches-----------------------------------------------------------------------------------
--@Parameter1 Contains the SwitchType
    IF @Parameter1 = 400   --SwitchType
        SELECT Distinct AP_Products_ID as ID, 
    		Description ,
            Packs_BarCode 
    		Units_Barcode   
        FROM vw_AP_Switches
        WHERE Switch1_ID = @Parameter2 
          AND Switch2_ID = @Parameter3 
          AND Switch3_ID = @Parameter4 
          AND Switch4_ID = @Parameter5
    ELSE
    IF @Parameter1 = 401
    	SELECT DISTINCT Switch1_ID as ID, 
                        Switch1_Description 
        FROM vw_AP_Switches
	ELSE
 	IF @Parameter1 = 402
        BEGIN
            IF @Parameter2 = 0 
        		SELECT Distinct Switch2_ID as ID, 
                                Switch2_Description as Description
                FROM vw_AP_Switches
            ELSE
                SELECT Distinct Switch2_ID, 
                                Switch2_Description as Description
                FROM vw_AP_Switches 
                WHERE Switch1_ID = @Parameter2
        END
	ELSE
    IF @Parameter1 = 403
        BEGIN
            IF @Parameter2 = 0 
                SELECT DISTINCT Switch3_ID as ID, 
                                Switch3_Description as Description
                FROM vw_AP_Switches
            ELSE
            IF @Parameter3 = 0
                SELECT DISTINCT Switch3_ID as ID, 
                                Switch3_Description as Description
                FROM vw_AP_Switches 
                WHERE Switch1_ID = @Parameter2
            ELSE
                SELECT DISTINCT Switch3_ID as ID, 
                                Switch3_Description as Description
                FROM vw_AP_Switches 
                WHERE Switch1_ID = @Parameter2 
                  AND Switch2_ID = @Parameter3
        END
	ELSE
    IF @Parameter1 = 404
		BEGIN
            IF @Parameter2 = 0 
        		SELECT Distinct Switch4_ID as ID, 
                                Switch4_Description as Description
                FROM vw_AP_Switches
            ELSE
            IF @Parameter3 = 0
                SELECT DISTINCT Switch4_ID as ID, 
                                Switch4_Description as Description
                FROM vw_AP_Switches 
                WHERE Switch1_ID = @Parameter2
            ELSE
            IF @Parameter4 = 0
                SELECT DISTINCT Switch4_ID as ID, 
                                Switch4_Description as Description
                FROM vw_AP_Switches 
                WHERE Switch1_ID = @Parameter2 
                  AND Switch2_ID = @Parameter3
            ELSE
                SELECT DISTINCT Switch4_ID as ID, 
                                Switch4_Description as Description
                FROM vw_AP_Switches 
                WHERE Switch1_ID = @Parameter2 
                  AND Switch2_ID = @Parameter3 
                  AND Switch3_ID = @Parameter4
        END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















----------------------------------------------------------------------------
--Description   :sp_AP_Transfer_SIT_To_GL
--Purpose       :Transfers SIT GLAccount Transaction to another GLAccount
--Date          :2009/08/26
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AP_Transfer_SIT_To_GL
    (
        @FromGLAccountID int,
        @ToGLAccountID int,
        @GRVID int,
        @GRVDate datetime,
        @GLTranID int,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @TranDate datetime,
            @NextGLTranNo varchar(20),
            @JNLHeaderID int,
            @Amount money,
            @TranTypeID tinyint,
            @Narration varchar(50),
            @GLNarration varchar(50),
            @JNLNarration varchar(200),
            @ABSourceRef varchar(20),
            @ABTranRef int,
            @MonthID int,
            @YearID int,
            @GRVNo varchar(20),
            @Year varchar(4),
            @Month varchar(2),
            @Day varchar(2),
            @Date varchar(10),
            @NewGLTranID int,
            @InsertGLTran bit,
            @RetCode int


    SET @NextGLTranNo = ''
    SET @JNLHeaderID = 0

    SET @TranDate = getdate()
    SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
    SET @GRVNo = CONVERT(varchar(20), @GRVID)
    SET @RetCode = 0


    ------------------------------------------------------------
    --> Format the GRV DATE
    ------------------------------------------------------------
    SET @Year = CONVERT(varchar(4), DATEPART(yy, @GRVDate))
    SET @Month = CONVERT(varchar(2), DATEPART(mm, @GRVDate))
    SET @Day = CONVERT(varchar(2), DATEPART(dd, @GRVDate))

    IF LEN(RTRIM(LTRIM(@Month))) = 1
        SET @Month = '0' + @Month

    IF LEN(RTRIM(LTRIM(@Day))) = 1
        SET @Day = '0' + @Day

    SET @Date = @Year + '/' + @Month + '/' + @Day
    ------------------------------------------------------------


    SELECT @Amount = ISNULL(AB_Transaction_Amount, 0),
           @TranTypeID = Sys_AB_Transaction_Types_ID,
           @Narration = RTRIM(LTRIM(Description)),
           @ABSourceRef = RTRIM(LTRIM(AB_Source_Ref)),
           @ABTranRef = AB_Transaction_Ref,
           @MonthID = Slu_AW_Months_ID,
           @YearID = Slu_AW_Years_ID
    FROM AB_GL_Transactions
    WHERE AB_GL_Transactions_ID = @GLTranID


    SET @JNLNarration = @Narration + ' - Received on GRV ' + @GRVNo + ' ' + @Date
    SET @JNLNarration = LEFT(@JNLNarration, 200)

    SET @GLNarration = LEFT(@Narration + ' GRV ' + @GRVNo + ' ' + @Date, 50)


    ------------------------------------------------------------
    --> UPDATE STOCK-IN-TRANSIT Journal
    ------------------------------------------------------------
    UPDATE AB_Journals
    SET Journal_Narration = @JNLNarration
    WHERE AB_Journals_ID = @ABTranRef


    UPDATE AB_Journal_Details
    SET Notes = @GLNarration,
        AB_Accounts_ID = @ToGLAccountID
    WHERE AB_Journals_ID = @ABTranRef


    ------------------------------------------------------------
    --> MOVE transaction from STOCK-IN-TRANSIT to SELECTED Account
    ------------------------------------------------------------
	UPDATE AB_GL_Transactions
    SET Description = @GLNarration,
        AB_Accounts_ID = @ToGLAccountID
	WHERE AB_GL_Transactions_ID = @GLTranID
    ------------------------------------------------------------

    IF @TranTypeID = 15            --General Journal
        BEGIN
            UPDATE AB_Accounts
            SET AB_Account_Balance = AB_Account_Balance - @Amount
            WHERE AB_Accounts_ID = @FromGLAccountID
        
            UPDATE AB_Accounts
            SET AB_Account_Balance = AB_Account_Balance + @Amount
            WHERE AB_Accounts_ID = @ToGLAccountID
        END


    ------------------------------------------------------------
    --> UPDATE STOCK-IN-TRANSIT Log
    ------------------------------------------------------------
	UPDATE AP_Stock_Transfer_Log
    SET AO_GRV_ID = @GRVID,
        Date_Received = @GRVDate,
        SIT_User_ID = @UserID
	WHERE AB_GL_Transactions_ID = @GLTranID
    ------------------------------------------------------------



    SET @RetCode = 1


    RETURN @RetCode




SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Adjusted_Inventory_Details
--Purpose       :Inserts Stock Adjustments
--   			:    NB: Any mods must sync with sp_AP_Update_Inventory_Details
--              :    that is used for Goods Received and Returned Vouchers (GRV)
--Functionality :Handles Stock Adjustment Types 1, 3, 6
--Date          :2002/02/13
--Authors       :TB
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Moved the Reval/Deval Adjustment here from
--              :           sp_AO_Insert_OR_Update_GRV_Detail
--              :04/06/02 - Added text to @Note for normal Stock Adjustments
--              :                and ensured that AP_Inventory_Adjustments is
--              :                for new LastCost AND OnHand adjustments
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :31/05/03 - Added calculate and update AVERAGE COST in AP_Products
--              :08/01/04 - Added Inventory Adjustment Type field Sys_AP_Adjustment_Types_ID
--              :09/09/04 - Added @AdjustmentType = 6 code to ID if Stock Take-on
--2004.4.0      :09/07/08 - Add new update General Ledger with the value of Stock Adjustments.
--              :           A General Journal is created for each adjustment and posted to the
--              :           Inventory and Cost-of-Sales GL accounts
--              :09/07/08 - Added @Month and @Year input parameters for GL entry
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--2004.4.5      :15/07/09 - Reworked update General Ledger with the value of Stock Adjustments.
--              :           Previous Qty Adjustment was NOT inserted in GL if Costs not also adjusted
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.0      :06/04/11 - Reworked to prevent behaviour at TC Germiston Manufacturing that
--              :           writes ONLY ONE leg of the Journal and GL Transaction entries, but
--              :           increments ID of GLTran table BUT DOES NOT WRITE THE TRANSACTION 
--              :           then puts GL out of balance !!!!!!!!!!!!!!!!
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--V6.2 RL	2015-11-29	:Removed Job Reserved, Sales Order Reserved and Quote Reserved
--						 These values are calculation based on active transactions and not the what is in the AP_Products table
--V6.2 RL	2015-11-29	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Adjusted_Inventory_Details]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Average_Cost money,
        @ProductBinID int,
    	@New_Bin_On_Hand decimal(9,3), --From V6.2 This is the bin on hand qty
    	@Note varchar(70),
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
        	@Prev_On_Hand decimal(9,3),
	    	@New_Job_Reserved decimal(9,3),
	    	@New_Sales_Order_Reserved decimal(9,3),
	    	@New_Quote_Reserved decimal(9,3),        	
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @Prev_Average_Cost money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_On_Hand_Value money,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount1 int,
            @GLControlAccount2 int,
            @Diff_On_Hand decimal(9,3),
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @ProductRef varchar(30),
            @Prev_On_Hand_Bin decimal(9,3),
            @On_Hand_Diff_Bin decimal(9,3),
            @Prev_On_Hand_Adj decimal(9,3),
            @New_On_Hand_Adj decimal(9,3),

            @New_On_Hand decimal(9,3),            
            @On_Hand_Diff decimal(9,3),

            @AP_Products_Bins_History_ID int,
            @Batch_No int,
            @ConsignmentStock    decimal(9,3),
            @StockOffSite		decimal(9,3) 

    SET @AdjustmentsID = 0
    SET @AdjustmentType = 1            --Intialize as 'Adjustment' type
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()
    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    SET @Batch_No = 0

    -- Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT

	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
		   @Prev_On_Hand = ISNULL(On_Hand, 0),
		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
    	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
           @Prev_Average_Cost = ISNULL(Average_Cost, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID

	--RL V6.2 2016-05-01 Consignment stock must not be added to average cost calculation
	--Consignment stock is not GRV'd stock
	SET @ConsignmentStock = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID),0)
	SET @StockOffSite = ISNULL(dbo.fn_AP_Get_Products_Out_On_Consignment(@ProductID),0)
	
--Insert Into Temp_Debug Values('@ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))  	
--Insert Into Temp_Debug Values('@StockOffSite',Convert(Varchar(100),@StockOffSite))  	
--Insert Into Temp_Debug Values('@Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))  	
--Insert Into Temp_Debug Values('@New_Bin_On_Hand',Convert(Varchar(100),@New_Bin_On_Hand))  	

	--> Calculate Product on hand diff
	SELECT @Prev_On_Hand_Bin = On_Hand
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND Lup_AP_Product_Bins_ID = @ProductBinID

--Insert Into Temp_Debug Values('@Prev_On_Hand_Bin',Convert(Varchar(100),@Prev_On_Hand_Bin))  	

	SELECT @On_Hand_Diff = @New_Bin_On_Hand - @Prev_On_Hand_Bin
	SELECT @New_On_Hand = @Prev_On_Hand + @On_Hand_Diff
	
--Insert Into Temp_Debug Values('@On_Hand_Diff',Convert(Varchar(100),@On_Hand_Diff))  	
--Insert Into Temp_Debug Values('@New_On_Hand',Convert(Varchar(100),@New_On_Hand))  	

	
	--Use these to calculate the inventory GL changes
	--Consignment stock must not be taken into consideration for this calulation
	--Consignment stock that is out at customers must be taken into consideration. This might be consignment stock.
	SET @Prev_On_Hand_Adj = @Prev_On_Hand + (@StockOffSite - @ConsignmentStock)
	SET @New_On_Hand_Adj = @New_On_Hand + (@StockOffSite - @ConsignmentStock)
	
--Insert Into Temp_Debug Values('@Prev_On_Hand_Adj',Convert(Varchar(100),@Prev_On_Hand_Adj))  	
--Insert Into Temp_Debug Values('@New_On_Hand_Adj',Convert(Varchar(100),@New_On_Hand_Adj))  	
	
	--Update Bin Qty
	IF @On_Hand_Diff <> 0
	BEGIN
		EXEC sp_AP_Products_Bins_Update_Insert 
			@ProductID,		--@ProductID int,
			@ProductBinID,	--@ProductBinID int,
    		@On_Hand_Diff,	--@Qty decimal(9,3)
    		'STOCK ADJ',	--@Source varchar(10),
    		0,				--@Batch_No
    		@UserID,		--@UserID int,
    		@CompanyID		--@CompanyID int
	END	
	
	--V6.2 RL Left in here for now
	--I need to check if this get updated anywhere else in the system
	SET @New_Job_Reserved =  @Prev_Job_Reserved
	SET	@New_Sales_Order_Reserved = @Prev_Sales_Order_Reserved
    SET @New_Quote_Reserved = @Prev_Quote_Reserved

    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'

    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Average_Cost,
        On_Hand = @New_On_Hand,
--        Job_Reserved = @New_Job_Reserved,
--        Sales_Order_Reserved = @New_Sales_Order_Reserved,
--        Quote_Reserved = @New_Quote_Reserved,
        [User_ID] = @UserID
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Average_Cost <> @New_Average_Cost OR
       --@Prev_On_Hand <> @New_On_Hand
       @Prev_On_Hand_Adj <> @New_On_Hand_Adj       
		BEGIN

            SET @Diff_On_Hand = 0
            SET @Diff_Value = 0

            ------------------------------------------------------------
            --> Assign Qty Adjustment Type
            ------------------------------------------------------------
            IF @Prev_On_Hand_Adj <> @New_On_Hand_Adj
                BEGIN
                    SET @Diff_On_Hand = @New_On_Hand_Adj - @Prev_On_Hand_Adj

                    SET @AdjustmentType = 1        --QTY Adjustment ONLY
                END

            ------------------------------------------------------------
            --> IF NOT Qty Adjustment then USE Previous On_Hand
            ------------------------------------------------------------
            IF @Diff_On_Hand = 0
                BEGIN
                    SET @Diff_On_Hand = @Prev_On_Hand_Adj
                END

            ------------------------------------------------------------
            --> Assign Reval/Deval Adjustment Type
            ------------------------------------------------------------
            IF @Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost
                BEGIN
                    SET @AdjustmentType = 3        --COST Adjustment ONLY
                END

            ------------------------------------------------------------
            --> Assign Stock Take-On Adjustment Type
            ------------------------------------------------------------
    		IF @Prev_On_Hand_Adj <> @New_On_Hand_Adj AND
              (@Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost)
    			BEGIN
                    SET @AdjustmentType = 6       --QTY AND COST Adjustment
                END


            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            IF @AdjustmentType = 1        --QTY Adjustment ONLY (@Diff_*_Cost = 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Qty by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Average_Cost), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Last_Cost), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 3        --COST Adjustment ONLY (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Costs by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Average_Cost - @Prev_Average_Cost)), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 6        --QTY AND COST Adjustment (Stock Take-On) (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Take-On by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                           SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand_Adj) - (@Prev_Average_Cost * @Prev_On_Hand_Adj), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
							--RL V6.0 2014-10-15
                           --SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Last_Cost * @Prev_On_Hand), 2)
                           SET @Diff_Value = ROUND((@New_Last_Cost * @New_On_Hand_Adj) - (@Prev_Last_Cost * @Prev_On_Hand_Adj), 2)
                        END
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)


            ------------------------------------------------------------------------------
            --> INSERT GL Entries here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    --> Create NORMAL JOURNAL header
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END

                    --> Update INVENTORY CONTROL
                    SELECT @GLControlAccount1 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 601


                    --> Create JOURNAL DETAIL for Inventory Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount1,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Inventory Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount1,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID


                    --> Update NEW Inventory Adjustments CONTROL
    				SELECT @GLControlAccount2 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 107


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for Cost Of Sales Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount2,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Cost Of Sales Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount2,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------

            IF LTRIM(RTRIM(@Note)) = ''
                BEGIN
                    IF @AdjustmentType = 1
                        BEGIN
                            SET @Note = 'Stock Adjust Qty by '
                        END
                    ELSE
                    IF @AdjustmentType = 3
                        BEGIN
                            SET @Note = 'Stock Adjust Costs by '
                        END
                    ELSE
                    IF @AdjustmentType = 6
                        BEGIN
                            SET @Note = 'Stock Adjust Take-On by '
                        END
                END
            ELSE
                BEGIN
                    SET @Note = RTRIM(LTRIM(@Note)) + ' by '
                END


			SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


            ------------------------------------------------------------
            --> INSERT the Adjustment
            ------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        		    @Prev_Job_Reserved,
        			@Prev_Sales_Order_Reserved,
        		    @Prev_Quote_Reserved,
        			@New_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@New_Job_Reserved ,
        			@New_Sales_Order_Reserved,
        			@New_Quote_Reserved,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID,
        			@ProductBinID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Adjusted_Inventory_Details_Split_Types
--Purpose       :Inserts SPLIT Stock Adjustments by PRODUCT TYPE and UPDATE GL
--              :    1. Inventory Control or
--              :    2. Split Inventory Control by PRODUCT TYPE if parameter is set
--              :
--   			:NB: Any mods must sync with sp_AP_Update_Inventory_Details
--              :    that is used for Goods Received and Returned Vouchers (GRV)
--Functionality :Handles Stock Adjustment Types 1, 3, 6
--Date          :2009/02/12
--Authors       :TB
--Mods          :
--2004.4.5      :15/07/09 - Reworked update General Ledger with the value of Stock Adjustments.
--              :           Previous Qty Adjustment was NOT inserted in GL if Costs not also adjusted
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.0      :06/04/11 - Moved SELECT @User_Name outside 'If Adjustment has AN INVENTORY VALUE ...' section
--V6.0	RL	2014-09-01	:Added Product audit trail info
--V6.2 RL	2015-11-29	:Removed Job Reserved, Sales Order Reserved and Quote Reserved
--						 These values are calculation based on active transactions and not the what is in the AP_Products table
--V6.2 RL	2015-11-29	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Adjusted_Inventory_Details_Split_Types]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Average_Cost money,
        @ProductBinID int,
    	@New_Bin_On_Hand decimal(9,3), --From V6.2 This is the bin on hand qty
    	@Note varchar(70),
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
        	@Prev_On_Hand decimal(9,3),
	    	@New_Job_Reserved decimal(9,3),
	    	@New_Sales_Order_Reserved decimal(9,3),
	    	@New_Quote_Reserved decimal(9,3),        	        	
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @Prev_Average_Cost money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_On_Hand_Value money,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount int,
            @Diff_On_Hand decimal(9,3),
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @SplitGRVparameter varchar(10),
            @SplitGRVTypes int,
            @TypeDescription varchar(50),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ProductRef varchar(30),
            @Bin_Prev_On_Hand decimal(9,3),
            @On_Hand_Diff decimal(9,3),
            @New_On_Hand decimal(9,3),
            @AP_Products_Bins_History_ID int,
            @Batch_No int           


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 1            --Intialize as 'Adjustment' type
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()
    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    SET @Batch_No = 0

    --> Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


    --> Get the CURRENT Product values
	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
		   @Prev_On_Hand = ISNULL(On_Hand, 0),
		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
    	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
           @Prev_Average_Cost = ISNULL(Average_Cost, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID

	--> Calculate Product on hand diff
	SELECT @Bin_Prev_On_Hand = On_Hand
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND Lup_AP_Product_Bins_ID = @ProductBinID
	
	SELECT @On_Hand_Diff = @New_Bin_On_Hand - @Bin_Prev_On_Hand
	SELECT @New_On_Hand = @Prev_On_Hand + @On_Hand_Diff
	
	--Update Bin Qty
	IF @On_Hand_Diff <> 0
	BEGIN
		EXEC sp_AP_Products_Bins_Update_Insert 
		@ProductID,--@ProductID int,
        @ProductBinID,--@ProductBinID int,
    	@On_Hand_Diff,--@Qty decimal(9,3)
    	'STOCK ADJ',--@Source varchar(10),
    	0,--@Batch_No
    	@UserID,--@UserID int,
    	@CompanyID--@CompanyID int
	END	
	
	--V6.2 RL Left in here for now
	--I need to check if this get updated anywhere else in the system
	SET @New_Job_Reserved =  @Prev_Job_Reserved
	SET	@New_Sales_Order_Reserved = @Prev_Sales_Order_Reserved
    SET @New_Quote_Reserved = @Prev_Quote_Reserved


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Average_Cost,
        On_Hand = @New_On_Hand,
        Job_Reserved = @New_Job_Reserved,
        Sales_Order_Reserved = @New_Sales_Order_Reserved,
        Quote_Reserved = @New_Quote_Reserved,
        [User_ID] = @UserID
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Average_Cost <> @New_Average_Cost OR
       @Prev_On_Hand <> @New_On_Hand
		BEGIN 
            -------------------------------------------------------
            --> Get Split GRV Stock Receipts to GL INVENTORY accounts parameter
            -------------------------------------------------------
            SET @SplitGRVparameter = '0'

            SELECT @SplitGRVparameter = Control_Value
            FROM Sys_AW_Options
            WHERE Control_Type = 'CheckBox' AND
                  Control_Name = 'chkUseProductPurchasesGL' AND
                  Control_Index = 0 AND
                  AW_User_Companies_ID = @CompanyID


            -------------------------------------------------------
            --> ONLY set @SplitGRVTypes if @SplitGRVparameter = '1'
            -------------------------------------------------------
            SET @SplitGRVTypes = 0

            IF @SplitGRVparameter = '1'
                BEGIN
                    SET @SplitGRVTypes = 1
                END
            -------------------------------------------------------


            -------------------------------------------------------
            --> Get the INVENTORY CONTROL if NOT Split GRV Stock Receipts parameter
            -------------------------------------------------------
            --> Update INVENTORY CONTROL
            SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 601        --Inventory Control
            -------------------------------------------------------


            ------------------------------------------------------------
            --> CALC Inventory Value Increase/Decrease
            ------------------------------------------------------------
            SET @Diff_On_Hand = 0
            SET @Diff_Value = 0

            ------------------------------------------------------------
            --> Assign Qty Adjustment Type
            ------------------------------------------------------------
            IF @Prev_On_Hand <> @New_On_Hand
                BEGIN
                    SET @Diff_On_Hand = @New_On_Hand - @Prev_On_Hand

                    SET @AdjustmentType = 1        --QTY Adjustment ONLY
                END

            ------------------------------------------------------------
            --> IF NOT Qty Adjustment then USE Previous On_Hand
            ------------------------------------------------------------
            IF @Diff_On_Hand = 0
                BEGIN
                    SET @Diff_On_Hand = @Prev_On_Hand
                END

            ------------------------------------------------------------
            --> Assign Reval/Deval Adjustment Type
            ------------------------------------------------------------
            IF @Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost
                BEGIN
                    SET @AdjustmentType = 3        --COST Adjustment ONLY
                END

            ------------------------------------------------------------
            --> Assign Stock Take-On Adjustment Type
            ------------------------------------------------------------
    		IF @Prev_On_Hand <> @New_On_Hand AND
              (@Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost)
    			BEGIN
                    SET @AdjustmentType = 6       --QTY AND COST Adjustment
                END


            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            IF @AdjustmentType = 1        --QTY Adjustment ONLY (@Diff_*_Cost = 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Qty by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Average_Cost), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Last_Cost), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 3        --COST Adjustment ONLY (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Costs by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Average_Cost - @Prev_Average_Cost)), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 6        --QTY AND COST Adjustment (Stock Take-On) (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Take-On by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                           SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Average_Cost * @Prev_On_Hand), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                           SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Last_Cost * @Prev_On_Hand), 2)
                        END
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> NEW 2004.4.3 - Get the Product TYPE Description
            ------------------------------------------------------------------------------
            SET @TypeDescription = ''

			SELECT @TypeDescription = ISNULL(t.Description, '')
			FROM AP_Products p
                LEFT JOIN Lup_AP_Product_Types t
                    ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
			WHERE p.AP_Products_ID = @ProductID


            SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)


            ------------------------------------------------------------------------------
            --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    ---------------------------------------------------------------------
                    --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                    ---------------------------------------------------------------------
                    SET @GLAdjustID = 0

                    SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @AdjustGLDescription AND
                          Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                          Slu_AW_Active_ID = 1


                    IF @GLAdjustID = 0
                        BEGIN
             				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                    @AdjustGLDescription,
                                                    14,
                                                    @UserID,
                                                    @CompanyID
                        END


                    ---------------------------------------------------------------------
                    --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                    ---------------------------------------------------------------------
                    IF @SplitGRVTypes = 1
                        BEGIN
                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0

                            SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @InventoryGLDescription AND
                                  Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                  Slu_AW_Active_ID = 1


                            IF @GLInventoryID = 0
                                BEGIN
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END
                            ---------------------------------------------------------------------
                        END
                    ---------------------------------------------------------------------


                --> Create NORMAL JOURNAL header for ADJUSTMENT
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    IF @SplitGRVTypes = 1
                        BEGIN
                        --> Create JOURNAL DETAIL for Inventory Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran


                        --> Create GL TRANSACTION for SPLIT GL Inventory Account
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLInventoryID,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END
                    ELSE
                        BEGIN
                        --> Create JOURNAL DETAIL for Inventory Control 601
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                        --> Create GL TRANSACTION for Inventory Control 601
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLControlAccount,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END


                --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAdjustID,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLAdjustID,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END    --IF @Diff_Value <> 0
            ------------------------------------------------------------------------------



            ------------------------------------------------------------------------------
            --> INSERT STOCK ADJUSTMENT table here
            ------------------------------------------------------------------------------
            IF LTRIM(RTRIM(@Note)) = ''
                BEGIN
                    IF @AdjustmentType = 1
                        BEGIN
                            SET @Note = 'Stock Adjust Qty by '
                        END
                    ELSE
                    IF @AdjustmentType = 3
                        BEGIN
                            SET @Note = 'Stock Adjust Costs by '
                        END
                    ELSE
                    IF @AdjustmentType = 6
                        BEGIN
                            SET @Note = 'Stock Adjust Take-On by '
                        END
                END
            ELSE
                BEGIN
                    SET @Note = RTRIM(LTRIM(@Note)) + ' by '
                END


			SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


            --> Stock Reval/Deval Adjustment for Last_Cost changes
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        		    @Prev_Job_Reserved,
        			@Prev_Sales_Order_Reserved,
        		    @Prev_Quote_Reserved,
        			@New_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@New_Job_Reserved ,
        			@New_Sales_Order_Reserved,
        			@New_Quote_Reserved,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID,
        			@ProductBinID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Cost_Adjustments
--Purpose       :
--Date          :2007/02/15
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AP_Update_Cost_Adjustments
	(
        @ProductID int,
        @LastCost money,
        @AverageCost money,
        @StandardCost money
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0



    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        )
        BEGIN
            UPDATE AP_Products
            SET Last_Cost = @LastCost,
                Average_Cost = @AverageCost,
                Standard_Cost = @StandardCost
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1
        END



RETURN @ReturnValue












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inbound_Transfer_Cost
--Source        :Lifted from sp_AP_Update_Inventory_Details (Stock Receipt GRV)
--Purpose       :Updates Product Last_Cost, On_Hand for ONE product in INbound Stock Transfer
--   			:Also inserts GL Inventory Adjustments for Reval/Deval
--   			:    NB: Any mods must sync with sp_AP_Update_Adjusted_Inventory_Details
--              :    that is used for Stock Adjustments
--Functionality :Handles Stock Adjustment Types 2, 4, 5
--Date          :2010/10/02
--Authors       :TB
--Mods          :
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--V6.2 RL	2016-06-25	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Inbound_Transfer_Cost]
    (
        @TransferID int,
    	@ProductID int,
        @MonthID tinyint,
        @YearID smallint,
        @TransferType varchar(30),
    	@Transfer_Qty decimal(9,3),
    	@New_Unit_Cost money,
    	@New_Amount money,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @New_Average_Cost money,
            @New_Qty decimal(9,3),
            @COS_Adjust money,
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @ProdCode varchar(20),
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @GLControlAccount int,
            @InsertGLTran bit,
            @GLTranDate datetime,
            @GRInventoryCOS varchar(10),
            @RefNo varchar(20),
            @AdjustmentType tinyint,
            @ProductRef varchar(30),
            @Note varchar(70)


    SET @AdjustmentType = 5    --Intialize as 'Goods Received' type


    BEGIN
    	SELECT @ProdCode = ISNULL(Product_Code, ''),
               @Prev_Last_Cost = ISNULL(Last_Cost, 0),
               @Prev_Average_Cost = ISNULL(Average_Cost, 0),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0)
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID


        SET @New_Qty = @Prev_On_Hand + @Transfer_Qty
        SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


        SET @COS_Adjust = 0
        SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details

------------------------------------------------------------------------
--> NEW 04/06/03: Calculate AVERAGE COST
------------------------------------------------------------------------
    --> Initialises Average_Cost
        IF @Prev_Average_Cost = 0
            BEGIN
                SET @New_Average_Cost = @New_Unit_Cost
            END

        IF @Prev_On_Hand < 0            -- On_Hand was negative
            BEGIN
                IF @New_Qty <= 0        -- On_Hand still negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Unit_Cost - @Prev_Average_Cost) * @New_Qty, 2)
                        SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
                    END
                ELSE                    -- On_Hand comes out of negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Unit_Cost - @Prev_Average_Cost) * ABS(@Prev_On_Hand), 2)
                        SET @New_Average_Cost = @New_Unit_Cost
                    END
            END
        ELSE                            -- On_Hand was positive
            BEGIN
                IF @Transfer_Qty <> 0    -- Create a NEW Average Cost
                    BEGIN
                        SET @New_Average_Cost = ROUND(((@Prev_On_Hand * @Prev_Average_Cost) +
                                                       (@Transfer_Qty * @New_Unit_Cost)) / @New_Qty, 2)
                    END
            END
------------------------------------------------------------------------

    	UPDATE AP_Products
        SET Last_Cost = @New_Unit_Cost,
            Average_Cost = @New_Average_Cost,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID


    --> INSERT a GL COST-OF-SALES adjustment for CONTINOUS INVENTORY ONLY
    --                if item was sold when it was in NEGATIVE On-Hand
        IF @COS_Adjust <> 0
            BEGIN

            --> Get Continuous Inventory settings
                SELECT @GRInventoryCOS = Control_Value
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkGRVtoInventoryCOS' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID


                IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = Continuous Inventory = Yes
                    BEGIN
                        SET @RefNo = @TransferType + CONVERT(varchar(10), @TransferID)
                        SET @RefNo = LEFT(@RefNo, 20)

                        SET @Narration = LEFT(@TransferType + 'C.O.S. Reval/Deval for ' + @ProductRef, 200)
        
                    --> Create NORMAL JOURNAL header for the C.O.S. Adjustment
         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                15,
                                @CompanyID

                        SET @GLTranDate = getdate()

        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                @GLTranDate,
                                @NextGLTranID,
                                @Narration,
                                @MonthID,
                                @YearID,
                                @UserID,
                                @CompanyID

                    --> Update INVENTORY ADJUSTMENTS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 107    --Inventory Adjustments Control
        
                    --> Create JOURNAL DETAIL for Cost Of Sales
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                    --> Create GL TRANSACTION for Cost Of Sales
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @MonthID,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID
        
                    --> Reverse signs to balance double entry
                        SET @COS_Adjust = @COS_Adjust * -1
        
                    --> Update INVENTORY CONTROL
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 601    --Inventory
        
                    --> Create JOURNAL DETAIL for Inventory
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                    --> Create GL TRANSACTION for Inventory
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @MonthID,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID

                    END
            END


    --> Moved here from sp_AO_Insert_OR_Update_GRV_Detail
		IF @Prev_Last_Cost <> @New_Unit_Cost OR
           @Prev_On_Hand <> @Transfer_Qty
			BEGIN 

                --> Assign the Adjustment Type
                IF @Prev_Last_Cost <> @New_Unit_Cost
                    BEGIN
                        SET @AdjustmentType = 5    --TRF Reval/Deval
                    END
                ELSE
                    BEGIN
                        SET @AdjustmentType = 4    --TRF Adjustment
                    END

				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID


                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                        IF @Prev_Last_Cost <> @New_Unit_Cost
                            SET @Note = @TransferType + 'Reval/Deval by '
                        ELSE
                            SET @Note = @TransferType + 'Adjustment by '
                    END
                ELSE
                IF @Note = @TransferType + 'by '    --set in sp_AO_Insert_OR_Update_GRV_Detail
                    BEGIN
                        SET @AdjustmentType = 2    --Goods Received
                    END


				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 

                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID,
            			Lup_AP_Product_Bins_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    0,
            			0,
            		    0,
            			@New_Unit_Cost,
                        @New_Average_Cost,
            			@Transfer_Qty,
            			0 ,
            			0,
            			0,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID,
            			1 --Defaulted to 1
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    
    END 			

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inventory_Cost_Adjustments
--Purpose       :Inserts Inventory Cost Adjustments
--Functionality :Handles Inventory Cost Adjustment Types 3 - Reval/Deval
--              :INSERT Stock Adjustment ONLY IF EITHER LastCost or AvgCost changed
--              :UPDATE GL ONLY IF ((NewLastCost or NewAvgCost) * OnHand) change has a VALUE 
--Date          :2011/04/17
--Authors       :TB
--Mods          :
--V6.0	RL	2014-09-01	:Added Product audit trail info
--V6.2 RL	2016-06-25	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Inventory_Cost_Adjustments]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Avg_Cost money,
    	@New_Std_Cost money,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Avg_Cost money,
        	@OnHand decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount1 int,
            @GLControlAccount2 int,
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 3            --Reval/Deval
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    -- Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
           @Prev_Avg_Cost = ISNULL(Average_Cost, 0),
		   @OnHand = ISNULL(On_Hand, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Avg_Cost,
        Standard_Cost = @New_Std_Cost,
        [User_ID] = @UserID
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> ONLY If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Avg_Cost <> @New_Avg_Cost
		BEGIN
            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            SET @Diff_Value = 0
            SET @Narration = 'Cost Adjusment by '

            IF @ValuationMethod = 0        -- Average Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Avg_Cost - @Prev_Avg_Cost)), 2)
                END
            ELSE
            IF @ValuationMethod = 1        -- Last Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> INSERT GL Entries here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    --> Create NORMAL JOURNAL header
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END

                    --> Update INVENTORY CONTROL
                    SELECT @GLControlAccount1 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 601


                    --> Create JOURNAL DETAIL for Inventory Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount1,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Inventory Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount1,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID


                    --> Update NEW Inventory Adjustments CONTROL
    				SELECT @GLControlAccount2 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 107


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for Cost Of Sales Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount2,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Cost Of Sales Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount2,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Avg_Cost,
        			@OnHand ,
        		    0,
        			0,
        		    0,
        			@New_Last_Cost,
                    @New_Avg_Cost,
        			@OnHand,
        			0 ,
        			0,
        			0,
        			@Narration,
        			@AdjustDate,
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inventory_Cost_Adjustments_Split_Types
--Purpose       :Inserts SPLIT Cost Adjustments by PRODUCT TYPE and UPDATE GL
--              :    1. Inventory Control or
--              :    2. Split Inventory Control by PRODUCT TYPE if parameter is set
--Functionality :Handles Inventory Cost Adjustment Types 3 - Reval/Deval
--              :INSERT Stock Adjustment ONLY IF EITHER LastCost or AvgCost changed
--              :UPDATE GL ONLY IF ((NewLastCost or NewAvgCost) * OnHand) change has a VALUE 
--Date          :2011/04/17
--Authors       :TB
--Mods          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--V6.2 RL	2016-06-25	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Avg_Cost money,
    	@New_Std_Cost money,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Avg_Cost money,
        	@OnHand decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount int,
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @SplitGRVparameter varchar(10),
            @SplitGRVTypes int,
            @TypeDescription varchar(50),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 3            --Reval/Deval
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    --> Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


    --> Get the CURRENT Product values
	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
           @Prev_Avg_Cost = ISNULL(Average_Cost, 0),
		   @OnHand = ISNULL(On_Hand, 0)		   
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Avg_Cost,
        Standard_Cost = @New_Std_Cost,
		[User_ID] = @UserID        
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Avg_Cost <> @New_Avg_Cost
		BEGIN 
            -------------------------------------------------------
            --> Get Split GRV Stock Receipts to GL INVENTORY accounts parameter
            -------------------------------------------------------
            SET @SplitGRVparameter = '0'

            SELECT @SplitGRVparameter = Control_Value
            FROM Sys_AW_Options
            WHERE Control_Type = 'CheckBox' AND
                  Control_Name = 'chkUseProductPurchasesGL' AND
                  Control_Index = 0 AND
                  AW_User_Companies_ID = @CompanyID

            -------------------------------------------------------
            --> ONLY set @SplitGRVTypes if @SplitGRVparameter = '1'
            -------------------------------------------------------
            SET @SplitGRVTypes = 0

            IF @SplitGRVparameter = '1'
                BEGIN
                    SET @SplitGRVTypes = 1
                END

            -------------------------------------------------------
            --> Get the INVENTORY CONTROL if NOT Split GRV Stock Receipts parameter
            -------------------------------------------------------
            --> Update INVENTORY CONTROL
            SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 601        --Inventory Control

            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            SET @Diff_Value = 0
            SET @Narration = 'Cost Adjusment by '

            IF @ValuationMethod = 0        -- Average Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Avg_Cost - @Prev_Avg_Cost)), 2)
                END
            ELSE
            IF @ValuationMethod = 1        -- Last Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> NEW 2004.4.3 - Get the Product TYPE Description
            ------------------------------------------------------------------------------
            SET @TypeDescription = ''

			SELECT @TypeDescription = ISNULL(t.Description, '')
			FROM AP_Products p
                LEFT JOIN Lup_AP_Product_Types t
                    ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
			WHERE p.AP_Products_ID = @ProductID


            SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)

            ------------------------------------------------------------------------------
            --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    ---------------------------------------------------------------------
                    --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                    ---------------------------------------------------------------------
                    SET @GLAdjustID = 0

                    SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @AdjustGLDescription AND
                          Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                          Slu_AW_Active_ID = 1


                    IF @GLAdjustID = 0
                        BEGIN
             				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                    @AdjustGLDescription,
                                                    14,
                                                    @UserID,
                                                    @CompanyID
                        END

                    ---------------------------------------------------------------------
                    --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                    ---------------------------------------------------------------------
                    IF @SplitGRVTypes = 1
                        BEGIN
                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0

                            SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @InventoryGLDescription AND
                                  Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                  Slu_AW_Active_ID = 1


                            IF @GLInventoryID = 0
                                BEGIN
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END
                            ---------------------------------------------------------------------
                        END
                    ---------------------------------------------------------------------


                    --> Create NORMAL JOURNAL header for ADJUSTMENT
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    IF @SplitGRVTypes = 1
                        BEGIN
                            --> Create JOURNAL DETAIL for Inventory Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran


                            --> Create GL TRANSACTION for SPLIT GL Inventory Account
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLInventoryID,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END
                    ELSE
                        BEGIN
                            --> Create JOURNAL DETAIL for Inventory Control 601
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for Inventory Control 601
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLControlAccount,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAdjustID,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLAdjustID,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Avg_Cost,
        			@OnHand ,
        		    0,
        			0,
        		    0,
        			@New_Last_Cost,
                    @New_Avg_Cost,
        			@OnHand,
        			0 ,
        			0,
        			0,
        			@Narration,
        			@AdjustDate,
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--> NEW 05/06/03: Calculate AVERAGE COST
--------------------------------------------------------------------------------
--Description   :sp_AP_Product_Inventory_Details
--Purpose       :Updates Product Last_Cost, On_Hand & Reserved for ONE product in GRV
--   			:Also inserts GL Inventory Adjustments for Reval/Deval
--   			:    NB: Any mods must sync with sp_AP_Update_Adjusted_Inventory_Details
--              :    that is used for Stock Adjustments
--Functionality :Handles Stock Adjustment Types 2, 4, 5
--Date          :2002/02/13
--Authors       :TB
--Version       :1.0.0
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Moved the Reval/Deval Adjustment here from
--              :           sp_AO_Insert_OR_Update_GRV_Detail
--              :04/06/02 - Added text to @Note for normal Stock Adjustments
--              :                and ensured that AP_Inventory_Adjustments is
--              :                for new LastCost AND OnHand adjustments
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :05/06/03 - Added calculate and update AVERAGE COST in AP_Products
--              :05/06/03 - Added COST-OF-SALES / INVENTORY GL adjustments
--              :           GL Journal and GL Transaction for INVENTORY CONTROL
--              :           entries if @COS_Adjust <> 0
--              :06/08/03 - Modified C.O.S. Adjustment GL Transaction Type
--              :           from 22 (Accounts Receivable - Journal)
--              :           to 15 (General Journal - Normal)
--              :04/09/03 - Added to GL Post Purchases/Sales to Inventory/C.O.S.
--              :           ONLY IF chkGRVtoInventoryCOS parameter is vbChecked
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :18/10/03 - Added @GRV_ID input parameter to get the GRV
--              :           Delivery_Note_Number as GLTran RefNo
--              :08/01/04 - Added Inventory Adjustment Type field Sys_AP_Adjustment_Types_ID
--              :26/05/05 - Added match the Accounting Period of the CALENDAR DAY
--              : ********  FIX the above LATER to match the Accounting Period of the GRV
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.0      :08/08/08 - Removed setting @New_Average_Cost = 0 if On_Hand now 0
--              :           in NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--2004.4.5      :16/07/09 - Removed check 'IF @NextGLTranID = 0' when creating NORMAL JOURNAL header
--              :           for the C.O.S. Adjustment if item was sold when it was in NEGATIVE On-Hand
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.1      :04/05/11 - Cleaned up comments
--2004.5.2      :06/07/11 - Removed writing an Adjustment if On_Hand is changed
--              :           CANNOT find a reason WHY an Adjustment is required
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--V6.0	RL	2014-05-13	:Inventory Adjustment is always done useing Last Cost??????????????????????????????????????????
--						 Should it not be done depending on the system option setup of Average Cost, Last Cost or Standard Cost
--V6.2	RL		:2015-12-01	:Product Bin qty changes
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Inventory_Details]
    (
        @GRV_ID int,
    	@ProductID int,
    	@New_Last_Cost money,
    	@New_On_Hand decimal(9,3),
    	@New_Job_Reserved decimal(9,3),
    	@New_Sales_Order_Reserved decimal(9,3),
    	@New_Quote_Reserved decimal(9,3),
    	@Note varchar(70),
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @Prev_Average_On_Hand_Value money,
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @Qty decimal(9,3),
            @COS_Adjust money,
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @ProductDesc varchar(50),
            @ProdCode varchar(20),
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
    		@Month tinyint,
    		@Year int,
    		@YearID int,
            @GLControlAccount int,
            @InsertGLTran bit,
            @GLTranDate datetime,
            @GRInventoryCOS varchar(10),
            @RefNo varchar(20),
            @AdjustmentType tinyint,
            @ProductRef varchar(30),
            @AP_Products_Bins_History_ID int,
            @Batch_No int,
            @ConsignmentStock    decimal(9,3),
			@ProductOffSite	decimal(9,3)       


    SET @AdjustmentType = 5    --Intialize as 'Goods Received' type


    BEGIN
    	SELECT @ProductDesc = ISNULL([Description], ''),
               @ProdCode = ISNULL(Product_Code, ''),
               @Prev_Last_Cost = ISNULL(Last_Cost, 0),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
    		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
               @Prev_Average_Cost = ISNULL(Average_Cost, 0)
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID
    
--Insert Into Temp_Debug Values('***Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))   	
--Insert Into Temp_Debug Values('***Prev_Last_Cost',Convert(Varchar(100),@Prev_Last_Cost))   	
--Insert Into Temp_Debug Values('***Prev_Average_Cost',Convert(Varchar(100),@Prev_Average_Cost))   	

--Insert Into Temp_Debug Values('New_On_Hand',Convert(Varchar(100),@New_On_Hand))
--Insert Into Temp_Debug Values('Qty',Convert(Varchar(100),@Qty))

		SET @ProductOffSite = dbo.fn_AP_Get_Products_Out_On_Consignment(@ProductID)

--Insert Into Temp_Debug Values('***ProductOffSite',Convert(Varchar(100),@ProductOffSite))

    	SET @ConsignmentStock = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID),0)
    	
--Insert Into Temp_Debug Values('***ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))

--Insert Into Temp_Debug Values('***New_On_Hand',Convert(Varchar(100),@New_On_Hand)) 
   	
    	SET @Qty = (@New_On_Hand) - (@Prev_On_Hand)
    	
--Insert Into Temp_Debug Values('***Qty',Convert(Varchar(100),@Qty)) 
   	
    	SET @New_On_Hand = (@New_On_Hand) - (@ConsignmentStock - @ProductOffSite)

--Insert Into Temp_Debug Values('***New_On_Hand',Convert(Varchar(100),@New_On_Hand))     	
    	
--Insert Into Temp_Debug Values('1Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))   	
--Insert Into Temp_Debug Values('1ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))
--Insert Into Temp_Debug Values('1New_On_Hand',Convert(Varchar(100),@New_On_Hand))
--Insert Into Temp_Debug Values('1Qty',Convert(Varchar(100),@Qty))
    	    
    	--RL V6.2 2016-05-01 Consignment stock must not be added to average cost calculation
    	--Consignment stock is not GRV'd stock
		IF @Note = 'Consignment Returned - No Affect On Average Cost!!!!'
		BEGIN	
			--Need to take qty in to consideration here because fn_AP_Get_Consignment_Stock_Qty retrieves from 
			--AO_GRV_Details which has already been updated in calling procedure 
			SELECT @Prev_On_Hand = (@Prev_On_Hand ) - (@ConsignmentStock - @ProductOffSite) - (@Qty * -1)		
			--SET @Prev_On_Hand = @Prev_On_Hand - (@Qty * -1)		
		END
		ELSE
		BEGIN
			SELECT @Prev_On_Hand = (@Prev_On_Hand ) - (@ConsignmentStock - @ProductOffSite)
			--SET @Prev_On_Hand = @Prev_On_Hand
		END
		    	
--Insert Into Temp_Debug Values('***Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))     	
		    	
--Insert Into Temp_Debug Values('2Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))   	
--Insert Into Temp_Debug Values('2ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))
--Insert Into Temp_Debug Values('2New_On_Hand',Convert(Varchar(100),@New_On_Hand))
--Insert Into Temp_Debug Values('2Qty',Convert(Varchar(100),@Qty))

        SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'

        SET @COS_Adjust = 0
        SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
	    SET @AP_Products_Bins_History_ID = 0
		SET @Batch_No = 0

		--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
		--date the products were received and not the date it was captured.
		SELECT @GLTranDate = Date_Received
		FROM AO_GRV
		WHERE AO_GRV_ID = @GRV_ID

        ------------------------------------------------------------------------
        --> Calculate AVERAGE COST
        ------------------------------------------------------------------------
        --> Initialise Average_Cost
        IF @Prev_Average_Cost = 0
            BEGIN
                SET @Prev_Average_Cost = @New_Last_Cost
            END

		SET @New_Average_Cost = @Prev_Average_Cost

--Insert Into Temp_Debug Values('***Prev_Average_Cost',Convert(Varchar(100),@Prev_Average_Cost))     	
--Insert Into Temp_Debug Values('***New_Average_Cost',Convert(Varchar(100),@New_Average_Cost))     	

        --> If On Hand NEGATIVE then do a Cost Adjustment 
        IF @Prev_On_Hand < 0            -- On_Hand was negative
            BEGIN
                IF @New_On_Hand <= 0    -- On_Hand still negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * @Qty, 2)
                        SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
                        --cONSIGNMENT
                        --SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
                    END
                ELSE                    -- On_Hand comes out of negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * ABS(@Prev_On_Hand), 2)
                        SET @New_Average_Cost = @New_Last_Cost
                    END
            END
        ELSE                            -- On_Hand was positive
            BEGIN
                IF @New_On_Hand <> 0    -- Create a NEW Average Cost
                    BEGIN
                        SET @New_Average_Cost = ROUND(((@Prev_On_Hand * @Prev_Average_Cost) +
                                                       (@Qty * @New_Last_Cost)) / @New_On_Hand, 2)
                    END
                    ELSE
                    BEGIN
						--RL V6.2 2015-05-27
						--@New_Average_Cost Equal NULL if New Qty = 0                   
						SET @New_Average_Cost = @New_Last_Cost
                    END                   
            END
        ------------------------------------------------------------------------
--Insert Into Temp_Debug Values('***@New_Average_Cost',Convert(Varchar(100),@New_Average_Cost))
--Insert Into Temp_Debug Values('***@Note',Convert(Varchar(100),@Note))
--Insert Into Temp_Debug Values('***@Qty',Convert(Varchar(100),@Qty))


		--RL V6.2	2016-05-01
		--If Last Cost and Average Cost was triggered by Consignment Stock returned
		--It should not affect the last cost and average cost!!!!!!!!!!!!!!!
		IF ( (@Note = 'Consignment Returned - No Affect On Average Cost!!!!') AND
			(@Qty < 0) )
		BEGIN
    		UPDATE AP_Products
			SET On_Hand = On_Hand + @Qty,
				[User_ID] = @UserID
    		WHERE AP_Products_ID = @ProductID		
--Insert Into Temp_Debug Values('In Qty Update',@Note)
		END
		ELSE
		BEGIN
    		UPDATE AP_Products
			SET Last_Cost = @New_Last_Cost,
				Average_Cost = @New_Average_Cost,
				--On_Hand = @New_On_Hand + @ConsignmentStock,
				On_Hand = On_Hand + @Qty, --+ @ConsignmentStock,
				Job_Reserved = @New_Job_Reserved,
				Sales_Order_Reserved = @New_Sales_Order_Reserved,
				Quote_Reserved = @New_Quote_Reserved,
				[User_ID] = @UserID
    		WHERE AP_Products_ID = @ProductID
--Insert Into Temp_Debug Values('In NORMAL Update',@Note)
		END
		--Update Bin Qty
		IF @Qty <> 0
		BEGIN
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				1,				--@ProductBinID int,
    			@Qty,			--@Qty decimal(9,3)
    			'ProdUpdate',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int
		END	
					
        --> CONTINUOUS INVENTORY ONLY - INSERT a GL COST-OF-SALES adjustment
        --                if item was sold when it was in NEGATIVE On-Hand
        IF @COS_Adjust <> 0
            BEGIN

                --> Get CONTINUOUS INVENTORY parameter setting
                SELECT @GRInventoryCOS = Control_Value
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkGRVtoInventoryCOS' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID


                IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
                    BEGIN

						--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
						--date the products were received and not the date it was captured.
                        --> The above should match the Accounting Period of the GRV !!
                        --SET @Month = DATEPART(mm, getdate())
                        --SET @Year = DATEPART(yy, getdate())
                        SET @Month = DATEPART(mm, @GLTranDate)
                        SET @Year = DATEPART(yy, @GLTranDate)

                        SELECT @YearID = Slu_AW_Years_ID
                        FROM Slu_AW_Years
                        WHERE [Description] = CONVERT(varchar(10), @Year)

                        IF @Month = 0 OR @YearID = 0
                            BEGIN
                                SELECT @Month = Slu_AW_Months_ID,
                                       @YearID = Slu_AW_Years_ID
                                FROM AW_User_Companies
                                WHERE AW_User_Companies_ID = @CompanyID
                            END

                        SET @RefNo = 'GRV ' + CONVERT(varchar(10), @GRV_ID)
                        SET @RefNo = LEFT(@RefNo, 20)

                        SET @Narration = LEFT('GRV C.O.S. Reval/Deval for ' + @ProductRef, 200)
        
                        --> Create NORMAL JOURNAL header for the C.O.S. Adjustment
         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                15,
                                @CompanyID

                        SET @GLTranDate = getdate()

        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                @GLTranDate,
                                @NextGLTranID,
                                @Narration,
                                @Month,
                                @YearID,
                                @UserID,
                                @CompanyID

                        --> Update INVENTORY ADJUSTMENTS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 107    --Inventory Adjustments Control
        
                        --> Create JOURNAL DETAIL for Cost Of Sales
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                        --> Create GL TRANSACTION for Cost Of Sales
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @Month,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID
        
                        --> Reverse signs to balance double entry
                        SET @COS_Adjust = @COS_Adjust * -1
        
                        --> Update INVENTORY CONTROL
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 601    --Inventory
        
                        --> Create JOURNAL DETAIL for Inventory
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                        --> Create GL TRANSACTION for Inventory
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @Month,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID

                    END
            END


        --> Moved here from sp_AO_Insert_OR_Update_GRV_Detail - Commented 2004.5.2
-- 		IF @Prev_Last_Cost <> @New_Last_Cost OR
--            @Prev_On_Hand <> @New_On_Hand

        -- NEW 2004.5.2 - CANNOT find a reason WHY an Adjustment is required if On_Hand is changed
		IF @Prev_Last_Cost <> @New_Last_Cost


			BEGIN

                --> Assign the Adjustment Type
                IF @Prev_Last_Cost <> @New_Last_Cost
                    BEGIN
                        SET @AdjustmentType = 5    --GRV Reval/Deval
                    END
                ELSE
					--RL V6.0 It will never go in here!!!!!
                    BEGIN
                        SET @AdjustmentType = 4    --GRV Adjustment
                    END


				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID


                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                        IF @Prev_Last_Cost <> @New_Last_Cost
                            SET @Note = 'Goods Received Reval/Deval by '
                        ELSE
                            SET @Note = 'Goods Received Adjustment by '
                    END
                ELSE
                IF @Note = 'Goods Received by '    --set in sp_AO_Insert_OR_Update_GRV_Detail
                    BEGIN
                        SET @AdjustmentType = 2    --Goods Received
                    END


				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID,
            			Lup_AP_Product_Bins_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    @Prev_Job_Reserved,
            			@Prev_Sales_Order_Reserved,
            		    @Prev_Quote_Reserved,
            			@New_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			@New_Job_Reserved ,
            			@New_Sales_Order_Reserved,
            			@New_Quote_Reserved,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID,
            			1 --Defaulted to 1
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    END 			


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inventory_Details_CRV
--Purpose       :Updates Product On_Hand for ONE product in CRV
--   			:Also inserts GL Inventory Adjustments for Reval/Deval
--   			:    NB: Any mods must sync with sp_AP_Update_Adjusted_Inventory_Details
--              :    that is used for Stock Adjustments
--Functionality :Handles Stock Adjustment Types 2, 4, 5
--Date          :2015/03/27
--Authors       :RL
--Version       :6.0.2
--V6.2	RL		:2015-12-01	:Product Bin qty changes
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inventory_Details_CRV]
    (
        @GRV_ID int,
    	@ProductID int,
    	@New_Last_Cost money,
    	@New_On_Hand decimal(9,3),
    	@New_Job_Reserved decimal(9,3),
    	@New_Sales_Order_Reserved decimal(9,3),
    	@New_Quote_Reserved decimal(9,3),
    	@Note varchar(70),
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @Prev_Average_On_Hand_Value money,
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @Qty decimal(9,3),
            @COS_Adjust money,
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @ProductDesc varchar(50),
            @ProdCode varchar(20),
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
    		@Month tinyint,
    		@Year int,
    		@YearID int,
            @GLControlAccount int,
            @InsertGLTran bit,
            @GLTranDate datetime,
            @GRInventoryCOS varchar(10),
            @RefNo varchar(20),
            @AdjustmentType tinyint,
            @ProductRef varchar(30)


    --SET @AdjustmentType = 8    --Intialize as 'Goods Received' type


    BEGIN
    	SELECT @ProductDesc = ISNULL([Description], ''),
               @ProdCode = ISNULL(Product_Code, ''),
               @Prev_Last_Cost = ISNULL(Last_Cost, 0),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
    		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
               @Prev_Average_Cost = ISNULL(Average_Cost, 0)
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID


        SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


        SET @Qty = @New_On_Hand - @Prev_On_Hand
        --SET @COS_Adjust = 0
        --SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details

		--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
		--date the products were received and not the date it was captured.
		--SELECT @GLTranDate = Date_Received
		--FROM AO_GRV
		--WHERE AO_GRV_ID = @GRV_ID

        --> If On Hand NEGATIVE then do a Cost Adjustment 
        --IF @Prev_On_Hand < 0            -- On_Hand was negative
        --    BEGIN
        --        IF @New_On_Hand <= 0    -- On_Hand still negative
        --            BEGIN
        --                SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * @Qty, 2)
        --                SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
        --            END
        --        ELSE                    -- On_Hand comes out of negative
        --            BEGIN
        --                SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * ABS(@Prev_On_Hand), 2)
        --                SET @New_Average_Cost = @New_Last_Cost
        --            END
        --    END
        --ELSE                            -- On_Hand was positive
        --    BEGIN
        --        IF @New_On_Hand <> 0    -- Create a NEW Average Cost
        --            BEGIN
        --                SET @New_Average_Cost = ROUND(((@Prev_On_Hand * @Prev_Average_Cost) +
        --                                               (@Qty * @New_Last_Cost)) / @New_On_Hand, 2)
        --            END
        --    END
        ------------------------------------------------------------------------

    	UPDATE AP_Products
        SET On_Hand = @New_On_Hand,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID

		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
		
			EXEC sp_AP_Products_Bins_Update_Insert 
			@ProductID,--@ProductID int,
			1,--@ProductBinID int,
    		@Qty,--@Qty decimal(9,3)
    		'CRV',--@Source varchar(10),
    		0,--@Batch_No
    		@UserID,--@UserID int,
    		@CompanyID--@CompanyID int
	    	
		END	

        --> CONTINUOUS INVENTORY ONLY - INSERT a GL COST-OF-SALES adjustment
        --                if item was sold when it was in NEGATIVE On-Hand
      --  IF @COS_Adjust <> 0
      --      BEGIN

      --          --> Get CONTINUOUS INVENTORY parameter setting
      --          SELECT @GRInventoryCOS = Control_Value
      --          FROM Sys_AW_Options
      --          WHERE Control_Type = 'CheckBox' AND
      --                Control_Name = 'chkGRVtoInventoryCOS' AND
      --                Control_Index = 0 AND
      --                AW_User_Companies_ID = @CompanyID


      --          IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
      --              BEGIN

						----RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
						----date the products were received and not the date it was captured.
      --                  --> The above should match the Accounting Period of the GRV !!
      --                  SET @Month = DATEPART(mm, @GLTranDate)
      --                  SET @Year = DATEPART(yy, @GLTranDate)

      --                  SELECT @YearID = Slu_AW_Years_ID
      --                  FROM Slu_AW_Years
      --                  WHERE [Description] = CONVERT(varchar(10), @Year)

      --                  IF @Month = 0 OR @YearID = 0
      --                      BEGIN
      --                          SELECT @Month = Slu_AW_Months_ID,
      --                                 @YearID = Slu_AW_Years_ID
      --                          FROM AW_User_Companies
      --                          WHERE AW_User_Companies_ID = @CompanyID
      --                      END

      --                  SET @RefNo = 'GRV ' + CONVERT(varchar(10), @GRV_ID)
      --                  SET @RefNo = LEFT(@RefNo, 20)

      --                  SET @Narration = LEFT('GRV C.O.S. Reval/Deval for ' + @ProductRef, 200)
        
      --                  --> Create NORMAL JOURNAL header for the C.O.S. Adjustment
      --   				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
      --                          15,
      --                          @CompanyID

      --                  SET @GLTranDate = getdate()

      --  				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
      --                          @GLTranDate,
      --                          @NextGLTranID,
      --                          @Narration,
      --                          @Month,
      --                          @YearID,
      --                          @UserID,
      --                          @CompanyID

      --                  --> Update INVENTORY ADJUSTMENTS CONTROL
      --  				SELECT @GLControlAccount = AB_Accounts_ID
      --                  FROM AB_Control_Accounts
      --                  WHERE Control_Number = 107    --Inventory Adjustments Control
        
      --                  --> Create JOURNAL DETAIL for Cost Of Sales
      --                  EXEC sp_AB_Insert_Journal_Detail
      --                          @JNLHeaderID,
      --                          @GLControlAccount,
      --                          @COS_Adjust,
      --                          @Narration,
      --                          @UserID,
      --                          @CompanyID,
      --                          @InsertGLTran
        
      --                  --> Create GL TRANSACTION for Cost Of Sales
      --                  EXEC sp_AB_Insert_GL_Transactions
      --                          @Narration,
      --                          15,
      --                          @GLControlAccount,
      --                          @GLTranDate,
      --                          @RefNo,
      --                          @Month,
      --                          @YearID,
      --                          @NextGLTranID,
      --                          @COS_Adjust,
      --                          @UserID,
      --                          @CompanyID
        
      --                  --> Reverse signs to balance double entry
      --                  SET @COS_Adjust = @COS_Adjust * -1
        
      --                  --> Update INVENTORY CONTROL
      --                  SELECT @GLControlAccount = AB_Accounts_ID
      --                  FROM AB_Control_Accounts
      --                  WHERE Control_Number = 601    --Inventory
        
      --                  --> Create JOURNAL DETAIL for Inventory
      --                  EXEC sp_AB_Insert_Journal_Detail
      --                          @JNLHeaderID,
      --                          @GLControlAccount,
      --                          @COS_Adjust,
      --                          @Narration,
      --                          @UserID,
      --                          @CompanyID,
      --                          @InsertGLTran
        
      --                  --> Create GL TRANSACTION for Inventory
      --                  EXEC sp_AB_Insert_GL_Transactions
      --                          @Narration,
      --                          15,
      --                          @GLControlAccount,
      --                          @GLTranDate,
      --                          @RefNo,
      --                          @Month,
      --                          @YearID,
      --                          @NextGLTranID,
      --                          @COS_Adjust,
      --                          @UserID,
      --                          @CompanyID

      --              END
      --      END


        --> Moved here from sp_AO_Insert_OR_Update_GRV_Detail - Commented 2004.5.2
-- 		IF @Prev_Last_Cost <> @New_Last_Cost OR
--            @Prev_On_Hand <> @New_On_Hand

        -- NEW 2004.5.2 - CANNOT find a reason WHY an Adjustment is required if On_Hand is changed
		--IF @Prev_Last_Cost <> @New_Last_Cost


		--	BEGIN

  --              --> Assign the Adjustment Type
  --              IF @Prev_Last_Cost <> @New_Last_Cost
  --                  BEGIN
  --                      SET @AdjustmentType = 5    --GRV Reval/Deval
  --                  END
  --              ELSE
		--			--RL V6.0 It will never go in here!!!!!
  --                  BEGIN
  --                      SET @AdjustmentType = 4    --GRV Adjustment
  --                  END


		--		SELECT @User_Name = ISNULL(FirstName, '')
		--		FROM AW_Users
		--		WHERE AW_Users_ID = @UserID


  --              IF LTRIM(RTRIM(@Note)) = ''
  --                  BEGIN
  --                      IF @Prev_Last_Cost <> @New_Last_Cost
  --                          SET @Note = 'Goods Received Reval/Deval by '
  --                      ELSE
  --                          SET @Note = 'Goods Received Adjustment by '
  --                  END
  --              ELSE
  --              IF @Note = 'Goods Received by '    --set in sp_AO_Insert_OR_Update_GRV_Detail
  --                  BEGIN
  --                      SET @AdjustmentType = 2    --Goods Received
  --                  END


		--		SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


  --              --> Stock Reval/Deval Adjustment for Last_Cost changes
  --          	INSERT INTO AP_Inventory_Adjustments
  --                  (
  --          			AP_Products_ID,
  --                      Sys_AP_Adjustment_Types_ID,
  --          			Previous_Last_Cost,
  --                      Previous_Average_Cost,
  --          			Previous_On_Hand,
  --          			Previous_Job_Reserved,
  --          			Previous_Sales_Order_Reserved,
  --          			Previous_Quote_Reserved,
  --          			New_Last_Cost,
  --                      New_Average_Cost,
  --          			New_On_Hand,
  --          			New_Job_Reserved,
  --          			New_Sales_Order_Reserved,
  --          			New_Quote_Reserved,
  --          			Note,
  --          			Date_Captured,
  --          			[User_ID],
  --          			AW_User_Companies_ID
  --                  )
  --          	VALUES
  --                  (
  --                      @ProductID,
  --                      @AdjustmentType,
  --          			@Prev_Last_Cost,
  --                      @Prev_Average_Cost,
  --          			@Prev_On_Hand ,
  --          		    @Prev_Job_Reserved,
  --          			@Prev_Sales_Order_Reserved,
  --          		    @Prev_Quote_Reserved,
  --          			@New_Last_Cost,
  --                      @New_Average_Cost,
  --          			@New_On_Hand,
  --          			@New_Job_Reserved ,
  --          			@New_Sales_Order_Reserved,
  --          			@New_Quote_Reserved,
  --          			@Note,
  --          			getdate(),
  --          			@UserID,
  --          			@CompanyID
  --                  )

  --          	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
  --          	RETURN @AdjustmentsID

  --          END
    END 			


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Link_Discount_Formulas
--Purpose       :Update Suppliers Discount Formulas for Products
--              :
--Functionality :Tables: AP_Products_Suppliers_ID
--              :
--Date          :2002/02/15
--Authors       :TB
--Version       :1.0.0
--MODS          :04/10/03 - Added Trade_Disc_Perc and Trade_Disc_Date from
--              :           AP_Products_Suppliers for Inventory Manager
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Update_Link_Discount_Formulas
	(
        @ProductsSuppliersID int,
        @TradeDiscPerc decimal(5,2),
        @TradeDiscDate datetime,
    	@SetTrade bit,
        @TradeID int,
        @SetRebate bit,
        @RebateID int
	)

AS

SET NOCOUNT ON


-------------------------------------------------------------------------------
-- DISCOUNT PERCENTAGE
-------------------------------------------------------------------------------

    IF @TradeDiscDate = '1899/12/31'
        BEGIN
            SET @TradeDiscDate = NULL
        END


    UPDATE AP_Products_Suppliers
    SET Trade_Disc_Perc = ISNULL(@TradeDiscPerc, 0),
        Trade_Disc_Date = @TradeDiscDate
    WHERE AP_Products_Suppliers_ID = @ProductsSuppliersID

-------------------------------------------------------------------------------
-- DISCOUNT FORMULAS
-------------------------------------------------------------------------------

--> Initialize variables
    IF @SetTrade is null
        SET @SetTrade = 0

    IF @SetRebate is null
        SET @SetRebate = 0

    IF @TradeID is null or @TradeID = 0
        SET @TradeID = 1

    IF @RebateID is null or @RebateID = 0
        SET @RebateID = 1

--> Update the formulas
    IF @SetTrade = 1 AND @SetRebate = 1
        UPDATE AP_Products_Suppliers
            SET AW_Trade_Discount_Formula_ID = @TradeID,
                AW_Rebate_Discount_Formula_ID = @RebateID
        WHERE AP_Products_Suppliers_ID = @ProductsSuppliersID

    ELSE
    IF @SetTrade = 1 AND @SetRebate = 0
        UPDATE AP_Products_Suppliers
            SET AW_Trade_Discount_Formula_ID = @TradeID
        WHERE AP_Products_Suppliers_ID = @ProductsSuppliersID

    ELSE
    IF @SetTrade = 0 AND @SetRebate = 1
        UPDATE AP_Products_Suppliers
            SET AW_Rebate_Discount_Formula_ID = @RebateID
        WHERE AP_Products_Suppliers_ID = @ProductsSuppliersID

SET NOCOUNT OFF	
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Null_Product_Codes
--Purpose       :Product Updates - Set NULL Product Codes
--Date          :2008/07/19
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Null_Product_Codes]
	(
        @CompanyID int,
        @UserID		int
	)
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    UPDATE AP_Products
    SET Product_Code = 'Null',
		[User_ID] = @UserID
    WHERE AW_User_Companies_ID = @CompanyID AND
          (Product_Code IS NULL OR
           RTRIM(LTRIM(Product_Code)) = '')


    SET @ReturnValue = 1

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Price_Adjustments
--Purpose       :
--Date          :2004/07/20
--Authors       :TB
--MODS          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Price_Adjustments]
	(
        @ProductID int,
        @Selling11 money,
        @Selling12 money,
        @Date1 datetime,
        @Selling21 money,
        @Selling22 money,
        @Date2 datetime,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Price1_Effective_Date = @Date1,
                Price1_Price1 = @Selling11,
                Price1_Price2 = @Selling12,
                Price2_Effective_Date = @Date2,
                Price2_Price1 = @Selling21,
                Price2_Price2 = @Selling22,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_CostPlus_Groups
--Purpose       :
--Date          :2007/07/29
--Authors       :TB
--MODS          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Product_CostPlus_Groups]
	(
        @ProductID int,
        @IsCostPlus tinyint,
        @CostPlusGroup int,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Slu_AW_YesNo_Cost_Plus_Item = @IsCostPlus,
                Lup_AP_Markup_Groups_ID = @CostPlusGroup,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Discount_Groups
--Purpose       :
--Date          :2006/10/07
--Authors       :TB
--MODS          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Discount_Groups]
	(
        @ProductID int,
        @Group int,
        @UserID	int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Lup_AP_Discount_Groups_ID = @Group,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Filters
--Purpose       :
--Date          :2005/04/27
--Authors       :TB
--MODS          :
--2004.3.4      :20/02/07 - Added Product Location field
--              :20/02/07 - Added Purchase Category field
--2004.3.5      :15/06/07 - Added @chkLinkOnly input parameter
--2004.5.7 RGL  :2012-10-20 - Added @Weight and @Levy_Product input parameter
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Filters]
	(
        @ProductID int,
        @Type int,
        @Group int,
        @Department int,
        @Location int,
        @Supplier int,
        @Manufacturer int,
        @Purchase int,
        @Active int,
        @chkLinkOnly tinyint,
        @Levy int,
        @Weight decimal(9,3),
        @UserID int      
	)
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0
  
    IF @chkLinkOnly = 1
        BEGIN
            IF EXISTS
                (
                    SELECT AP_Products_ID
                    FROM AP_Products
                    WHERE AP_Products_ID = @ProductID
        
                )
                BEGIN
                    UPDATE AP_Products
                    SET Lup_AP_Product_Types_ID = @Type,
                        Lup_AP_Product_Groups_ID = @Group,
                        Lup_AP_Product_Departments_ID = @Department,
                        Lup_AP_Product_Locations_ID = @Location,
                        Lup_AP_Product_Manufacturers_ID = @Manufacturer,
                        Lup_AP_Purchase_Categories_ID = @Purchase,
                        Slu_AW_Active_ID = @Active,
                        Levy_AP_Product_ID = @Levy,
                        Lup_AP_AW_Weight_ID = 2, --RGL 2012-10-26 Kilogram No more space on product filter screen
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                        
                    WHERE AP_Products_ID = @ProductID
        
                    SET @ReturnValue = 1
        
                END
        END
    ELSE
        BEGIN
            IF EXISTS
                (
                    SELECT AP_Products_ID
                    FROM AP_Products
                    WHERE AP_Products_ID = @ProductID
        
                )
                BEGIN
                    UPDATE AP_Products
                    SET Lup_AP_Product_Types_ID = @Type,
                        Lup_AP_Product_Groups_ID = @Group,
                        Lup_AP_Product_Departments_ID = @Department,
                        Lup_AP_Product_Locations_ID = @Location,
                        Default_Supplier_ID = @Supplier,
                        Lup_AP_Product_Manufacturers_ID = @Manufacturer,
                        Lup_AP_Purchase_Categories_ID = @Purchase,
                        Slu_AW_Active_ID = @Active,
                        Levy_AP_Product_ID = @Levy,
                        Lup_AP_AW_Weight_ID = 2, --RGL 2012-10-26 Kilogram No more space on product filter screen
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                        
                    WHERE AP_Products_ID = @ProductID
        
                    SET @ReturnValue = 1
        
                END
        END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Prices
--Purpose       :UPDATE Price Update Products in CURSOR using Product Code & Size
--Date          :2006/06/13
--Authors       :TB
--MODS:         :
--2004.4.0      :19/07/08 - Added validation if Price Update for this Product
--              :           HAS NOT ALREADY BEEN LOADED. If NO then LOAD update
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Prices]
	(
        @ProductCode varchar(20),
        @EffectiveDate datetime,
        @Price1 money,
        @Price2 money,
        @LastCost money,
        @ChkReplaceCost int,
        @ChkActiveOnly int,
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ProductID int,
            @Price1EffectiveDate datetime,
            @Price1Price1 money,
            @Price1Price2 money,
            @Price2EffectiveDate datetime,
            @Price2Price1 money,
            @Price2Price2 money,
            @AllreadyLoaded tinyint


    SET @AllreadyLoaded = 0


    IF @ChkActiveOnly = 1        --Update only ACTIVE Products that match Product Code
        BEGIN
        	DECLARE Product_Cursor CURSOR FOR
                (
                    SELECT AP_Products_ID,
                           Price1_Effective_Date,
                           Price1_Price1,
                           Price1_Price2,
                           Price2_Effective_Date,
                           Price2_Price1,
                           Price2_Price2
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode
                      AND AW_User_Companies_ID = @CompanyID
                      AND Slu_AW_Active_ID = 1
                )
        END
    ELSE                         --Update ALL Products that match Product Code
        BEGIN
        	DECLARE Product_Cursor CURSOR FOR
                (
                    SELECT AP_Products_ID,
                           Price1_Effective_Date,
                           Price1_Price1,
                           Price1_Price2,
                           Price2_Effective_Date,
                           Price2_Price1,
                           Price2_Price2
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode
                      AND AW_User_Companies_ID = @CompanyID
                )
        END



	OPEN Product_Cursor

    	FETCH NEXT FROM Product_Cursor 
    	INTO
            @ProductID,
            @Price1EffectiveDate,
            @Price1Price1,
            @Price1Price2,
        	@Price2EffectiveDate,
            @Price2Price1,
            @Price2Price2


    	WHILE @@FETCH_STATUS = 0
    	BEGIN

            SET @AllreadyLoaded = 0


            --> Validate if ALREADY LOADED
            IF @Price1EffectiveDate IS NOT NULL
                BEGIN
                    IF @Price1EffectiveDate = @EffectiveDate AND @Price1Price1 = @Price1
                        BEGIN
                            SET @AllreadyLoaded = 1
                        END
                END

            IF @Price2EffectiveDate IS NOT NULL
                BEGIN
                    IF @Price2EffectiveDate = @EffectiveDate AND @Price2Price1 = @Price1
                        BEGIN
                            SET @AllreadyLoaded = 1
                        END
                END


            IF @AllreadyLoaded = 0
                BEGIN
                    --> If Price1 is OLDEST price
                    --IF @Price1EffectiveDate <= @Price2EffectiveDate
                    --RL 2014-10-15 Added ISNULL check. Need to test
					IF @Price1EffectiveDate <= ISNULL(@Price2EffectiveDate,'1900-01-01')                    
                        BEGIN
                        	UPDATE AP_Products
                            SET Price1_Effective_Date = @EffectiveDate,
                                Price1_Price1 = @Price1,
                                Price1_Price2 = @Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END

                    --> If Price2 is OLDEST price
                    ELSE
                    IF ISNULL(@Price2EffectiveDate,'1900-01-01') <= @Price1EffectiveDate
                        BEGIN
                            --> Move Price1 to Price2
                        	UPDATE AP_Products
                            SET Price2_Effective_Date = @Price1EffectiveDate,
                                Price2_Price1 = @Price1Price1,
                                Price2_Price2 = @Price1Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                
                            --> Put NEW prices into Price1
                        	UPDATE AP_Products
                            SET Price1_Effective_Date = @EffectiveDate,
                                Price1_Price1 = @Price1,
                                Price1_Price2 = @Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END

                    --> If Price1 = Price2 and both dates are probably NULL
                    ELSE
                        BEGIN
                            --> Put NEW prices into Price1
                        	UPDATE AP_Products
                            SET Price1_Effective_Date = @EffectiveDate,
                                Price1_Price1 = @Price1,
                                Price1_Price2 = @Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END

                    --> Replace Last Cost with the Cost in list
                    IF @ChkReplaceCost = 1
                        BEGIN
                        	UPDATE AP_Products
                            SET Last_Cost = @LastCost,
                            [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END
                END


        	FETCH NEXT FROM Product_Cursor 
        	INTO
                @ProductID,
                @Price1EffectiveDate,
                @Price1Price1,
                @Price1Price2,
            	@Price2EffectiveDate,
                @Price2Price1,
                @Price2Price2

        END
    	
	CLOSE Product_Cursor

	DEALLOCATE Product_Cursor

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Promotion
--Purpose       :UPDATE AP_Promotion Header
--Parameters    :
--Date          :2004/02/18
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AP_Update_Product_Promotion
	(
        @PromotionsID int,
        @Description varchar(50),
        @StartDate datetime,
        @EndDate datetime,
        @Active tinyint,
        @UserID int
	)

AS

SET NOCOUNT ON

    UPDATE AP_Promotions
    SET Description = @Description,
        Start_Date = @StartDate,
        End_Date = @EndDate,
    	User_ID = @UserID,
        Slu_AW_Active_ID = @Active
    WHERE AP_Promotions_ID = @PromotionsID



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Selling_Price_History
--Purpose       :select's a specific products Selling price history 
--Functionality :
--Parameters    : 
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Selling_Price_History]
    (
        @Product_ID int,
        @New_Price1_Effective_Date datetime,
        @New_Price1_Price1 money,
        @New_Price1_Price2 money,
        @New_Price2_Effective_Date datetime,
        @New_Price2_Price1 money,
        @New_Price2_Price2 money,
        @User_ID int,
        @Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Price1_Effective_Date datetime,	
    		@Prev_Price1_Price1 money,
    		@Prev_Price1_Price2 money,
    		@Prev_Price2_Effective_Date datetime,
    		@Prev_Price2_Price1 money,
    		@Prev_Price2_Price2 money,
    		@Stock_On_Hand Decimal(9,3)
    
    BEGIN
        BEGIN
			SELECT
                @Stock_On_Hand = On_Hand,
                @Prev_Price1_Effective_Date = Price1_Effective_Date,
                @Prev_Price1_Price1 = Price1_Price1,
                @Prev_Price1_Price2 = Price1_Price2,
                @Prev_Price2_Effective_Date = Price2_Effective_Date,
                @Prev_Price2_Price1 = Price2_Price1,
                @Prev_Price2_Price2 = Price2_Price2
			FROM AP_Products 
			WHERE AP_Products_ID = @Product_ID AND
                  AW_User_Companies_ID = @Company_ID
        END 
    
		BEGIN
            INSERT INTO AP_Product_Selling_Prices
                (		
                    AP_Products_ID ,
                    On_Hand ,
                    Prev_Price1_Effective_Date ,
                    Prev_Price1_Price1 ,
                    Prev_Price1_Price2 ,
                    Prev_Price2_Effective_Date ,
                    Prev_Price2_Price1 ,	
                    Prev_Price2_Price2 ,
                    New_Price1_Effective_Date ,
                    New_Price1_Price1 ,
                    New_Price1_Price2 ,
                    New_Price2_Effective_Date ,
                    New_Price2_Price1 ,	
                    New_Price2_Price2 ,
                    Date_Captured ,
                    [User_ID] , 
                    AW_User_Companies_ID
                ) 
			VALUES
                (
                    @Product_ID,
                    @Stock_On_Hand,
                    @Prev_Price1_Effective_Date,
                    @Prev_Price1_Price1,
                    @Prev_Price1_Price2,
                    @Prev_Price2_Effective_Date,
                    @Prev_Price2_Price1,
                    @Prev_Price2_Price2,
                    @New_Price1_Effective_Date,
                    @New_Price1_Price1,
                    @New_Price1_Price2,
                    @New_Price2_Effective_Date,
                    @New_Price2_Price1,
                    @New_Price2_Price2,
                    getdate(),
                    @User_ID,
                    @Company_ID
                )
		END
    
		BEGIN	
			UPDATE AP_Products 
			SET Price1_Effective_Date = @New_Price1_Effective_Date,
				Price1_Price1 = @New_Price1_Price1,
				Price1_Price2 = @New_Price1_Price2,
				Price2_Effective_Date = @New_Price2_Effective_Date,
				Price2_Price1 = @New_Price2_Price1,
				Price2_Price2 = @New_Price2_Price2,
				[User_ID] = @User_ID
			WHERE AP_Products_ID = @Product_ID AND
                  AW_User_Companies_ID = @Company_ID
		END
    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Profit_Protector
--Purpose       :
--Date          :2004/08/05
--Authors       :TB
--MODS          :
--              :09/05/08 - Replaced Maximum Discount% field functionality with
--              :           Minimum GP% functionality
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Profit_Protector]
	(
        @ProductID int,
        @EditPrice tinyint,
        @EditDisc tinyint,
        @MinGP decimal(5,2),
        @ApplyMin tinyint,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Slu_AW_YesNo_Edit_Price = @EditPrice,
                Slu_AW_YesNo_Edit_Discount = @EditDisc,
                Max_Discount_Perc = @MinGP,
                Slu_AW_YesNo_Max_Discount_Perc = @ApplyMin,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Std_Cost_Adjustments
--Purpose       :
--Date          :2006/06/05
--Authors       :TB
--MODS          :
--2004.3.3      :09/11/06 - Added new fields Standard_Disc1 (@StdDisc1) and
--              :           Standard_Disc2 (@StdDisc2)
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AP_Update_Std_Cost_Adjustments
	(
        @ProductID int,
        @StdCost money,
        @StdDisc1 money,
        @StdDisc2 money
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0



    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        )
        BEGIN
            UPDATE AP_Products
            SET Standard_Cost = @StdCost,
                Standard_Disc1 = @StdDisc1,
                Standard_Disc2 = @StdDisc2
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1
        END



RETURN @ReturnValue











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Stock_Levels
--Purpose       :
--Date          :2007/06/10
--Authors       :TB
--MODS          :
--2004.3.8      :24/05/08 - Added UPDATE Service_Level field as [@SL]
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AP_Update_Stock_Levels
	(
        @ProductID int,
        @SL decimal(9, 3),
        @MSL decimal(9, 3),
        @Min_Qty decimal(9, 3),
        @Max_Qty decimal(9, 3)
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0



    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        )
        BEGIN
            UPDATE AP_Products
            SET Service_Level = @SL,
                Min_Stock_Level = @MSL,
                Min_Order_Qty = @Min_Qty,
                Max_Order_Qty = @Max_Qty
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1
        END



RETURN @ReturnValue













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Stock_Take
--Purpose       :
--Date          :2009/02/19
--Authors       :TB
--MODS          :
--2004.4.4      :30/04/09 - Added @UserID input parameter to assign ID of editing user
--V6.2	RL	2015-12-01	:Added Product Bins
----V6.3	RL	2017-02-01	:Update On_Hand_Calc = @TotalCount and Variance_Calc = @Variance for post adjustments
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Stock_Take]
	(
        @StockTakeID int,
        @ProductID int,
        @BinID int,
        @Count1 decimal(9, 3),
        @Count2 decimal(9, 3),
        @Count3 decimal(9, 3),
        @TotalCount decimal(12, 3),
        @Variance decimal(12, 3),
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_Stock_Takes_ID
            FROM AP_Products_Stock_Takes
            WHERE AP_Products_Stock_Takes_ID = @StockTakeID AND
                  AP_Products_ID = @ProductID AND
                  Lup_AP_Product_Bins_ID = @BinID
        )
        BEGIN
            UPDATE AP_Products_Stock_Takes
            SET Count1 = @Count1,
                Count2 = @Count2,
                Count3 = @Count3,
                Total_Count = @TotalCount,
                Variance = @Variance,
                User_ID = @UserID,
                Variance_Calc = @Variance,
                On_Hand_Calc = @TotalCount
            WHERE AP_Products_Stock_Takes_ID = @StockTakeID AND
                  AP_Products_ID = @ProductID AND
                  Lup_AP_Product_Bins_ID = @BinID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--------------------------------------------------------------------------------
--Description   :sp_AP_Zero_Stock_Take_Count
--Purpose       :Assign Stock Take Count = 0
--Date          :2009/04/29
--Authors       :TB
--Mods          :
--------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AP_Zero_Stock_Take_Count
    (
    	@StockTakeProcedureID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @UserID int,
            @ReturnValue int


    SELECT @UserID = User_ID
    FROM AP_Stock_Take_Procedures
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID


    UPDATE AP_Products_Stock_Takes
    SET Count1 = 0,
        Count2 = 0,
        Count3 = 0,
        Total_Count = 0,
        Variance = On_Hand * -1,
        User_ID = @UserID
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
          AW_User_Companies_ID = @CompanyID


    SET @ReturnValue = 1




RETURN @ReturnValue


SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AP_Zero_Stock_Transfer_Item_Qty
--Purpose       :Delete a Stock Transfer item
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE              Procedure sp_AP_Zero_Stock_Transfer_Item_Qty
    (
        @TransferID int
    )

AS

SET NOCOUNT ON


	UPDATE AP_Stock_Transfer_Details
	SET Quantity = 0
	WHERE AP_Stock_Transfer_Details_ID = @TransferID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--!! PUT IN THE COMPANYID


-----------------------------------------------------------------------------
--Description   : sp_AS_1000
--Purpose       : Retrieves Sales for One Category from AS_Transactions
--              : for SalesAnalyst
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          : 26 MAY 2002
--Authors       : TB
--MODS          :
-----------------------------------------------------------------------------
--Returns a recordset of:
--    prior 24 WEEKS sales, aggregated by WEEK NUMBER 
--    prior 24 MONTH sales, aggregated by MONTH NUMBER
-----------------------------------------------------------------------------
--NB:    always use float for date conversions
-----------------------------------------------------------------------------

CREATE                            PROCEDURE sp_AS_1000
    (
    	@LupID int,
    	@DataChoice int,
    	@StartDate datetime,
    	@EndDate datetime,
        @Option varchar(20),
    	@StartWeekNo int OUTPUT,
    	@EndWeekNo int OUTPUT 
    )

AS

SET NOCOUNT ON

IF @Option = 'All Sales'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
            WHERE (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
            WHERE (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Type'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Types_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Types_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Group'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Groups_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Groups_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Department'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Departments_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Departments_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Supplier'    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Default_Supplier_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Default_Supplier_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Manufacturer'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Manufacturers_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Manufacturers_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Location'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Locations_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = d.AP_Products_ID
            WHERE p.Lup_AP_Product_Locations_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Sales Area'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c
                    ON c.AC_Customers_ID = h.AC_Customers_ID
            WHERE c.Lup_AC_Sales_Areas_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c
                    ON c.AC_Customers_ID = h.AC_Customers_ID
            WHERE c.Lup_AC_Sales_Areas_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

ELSE
IF @Option = 'Sales Person'
    IF @DataChoice = 0    --Weeks
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
    
            SELECT CONVERT(int, h.Transaction_Date) / 7 as WeekNo,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c
                    ON c.AC_Customers_ID = h.AC_Customers_ID
            WHERE c.Lup_AS_Reps_ID = @LupID AND
                 (CONVERT(int, h.Transaction_Date) / 7 >= @StartWeekNo AND    --must be >=
                  CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY CONVERT(int, h.Transaction_Date) / 7
            ORDER BY WeekNo DESC
        END
    
    ELSE    --Months
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
            
            SELECT dbo.fn_AS_Get_Month_Number(h.Transaction_Date) as DateString,
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) as PriceDiscount,
                   SUM(d.Discount_Amount) as Discount,
                   SUM(d.Quantity * d.Unit_Cost) as Cost,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income,
                   SUM(d.Quantity) as Quantity
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AC_Customers c
                    ON c.AC_Customers_ID = h.AC_Customers_ID
            WHERE c.Lup_AS_Reps_ID = @LupID AND
                 (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND    --must be >
                  dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Month_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   : sp_AS_1010
--Purpose       : Retrieves Category Lookup list based on Search Filter
--              : for SalesAnalyst
--Parameters    :
--Date          : 25 MAY 2002
--Authors       : TB
--Version       : 1.0.0
------------------------------------------------------------------------------

CREATE         PROCEDURE sp_AS_1010
    (
        @Option varchar(30) = '',
        @CompanyID int = 1
    )

AS

SET NOCOUNT ON

   IF @Option = 'All Sales'
      SELECT AW_User_Companies_ID as [ID], [Company_Name] AS [Sales]
      FROM AW_User_Companies
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Type'
      SELECT Lup_AP_Product_Types_ID as [ID], [Description] AS [Types]
      FROM Lup_AP_Product_Types
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Group'
      SELECT Lup_AP_Product_Groups_ID as [ID], [Description] AS [Groups]
      FROM Lup_AP_Product_Groups
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Supplier'
      SELECT AO_Suppliers_ID AS [ID], [Supplier_Name] AS [Suppliers]
      FROM AO_Suppliers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Department'
      SELECT Lup_AP_Product_Departments_ID as [ID], [Description] AS [Departments]
      FROM Lup_AP_Product_Departments
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Manufacturer'
      SELECT Lup_AP_Product_Manufacturers_ID as [ID], [Description] AS [Manufacturers]
      FROM Lup_AP_Product_Manufacturers
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Location'
      SELECT Lup_AP_Product_Locations_ID as [ID], [Description] AS [Locations]
      FROM Lup_AP_Product_Locations
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Sales Area'
      SELECT Lup_AC_Sales_Areas_ID as [ID], [Description] AS [Sales Area]
      FROM Lup_AC_Sales_Areas
      WHERE AW_User_Companies_ID = @CompanyID
   ELSE
   IF @Option = 'Sales Person'
      SELECT Lup_AS_Reps_ID as [ID], [Description] AS [Sales Person]
      FROM Lup_AS_Reps
      WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-----------------------------------------------------------------------------
--Description   : sp_AS_1020
--Purpose       : Retrieves selected Category Performance Chart Data
--              : for whole Category from AS_Transactions
--              :     for SalesAnalyst
--Parameters    :
--Date          : 27 MAY 2002
--Authors       : TB
--Version       : 1.0.0
-----------------------------------------------------------------------------

CREATE               PROCEDURE sp_AS_1020
    (
        @CompanyID int,
        @Option varchar(20),
    	@StartDate datetime,
    	@EndDate datetime
    )

AS

SET NOCOUNT ON

-->Product Types
    IF @Option = 'All Sales'
        BEGIN
            SELECT MAX(o.[Company_Name]) as [Company],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AW_User_Companies o
                    ON h.AW_User_Companies_ID = o.AW_User_Companies_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Company_Name]
            ORDER BY Income DESC
        END

-->Product Types
    IF @Option = 'Type'
        BEGIN
            SELECT MAX(o.[Description]) as [Type],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Types o
                    ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

-->Product Groups
    ELSE
    IF @Option = 'Group'
        BEGIN
            SELECT MAX(o.[Description]) as [Group],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Groups o
                    ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

-->Product Departments
    ELSE
    IF @Option = 'Department'
        BEGIN
            SELECT MAX(o.[Description]) as [Department],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Departments o
                    ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

-->Product Default Suppliers
    ELSE
    IF @Option = 'Supplier'
        BEGIN
            SELECT MAX(o.[Supplier_Name]) as [Supplier],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN AO_Suppliers o
                    ON p.Default_Supplier_ID = o.AO_Suppliers_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Supplier_Name]
            ORDER BY Income DESC
        END

-->Product Manufacturers
    ELSE
    IF @Option = 'Manufacturer'
        BEGIN
            SELECT MAX(o.[Description]) as [Manufacturer],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Manufacturers o
                    ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

-->Product Locations
    ELSE
    IF @Option = 'Location'
        BEGIN
            SELECT MAX(o.[Description]) as [Location],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Locations o
                    ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

-->Product Sales Areas
    ELSE
    IF @Option = 'Sales Area'
        BEGIN
            SELECT MAX(o.[Description]) as [Sales Area],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                INNER JOIN AC_Customers c
                    ON c.AC_Customers_ID = h.AC_Customers_ID
                LEFT JOIN Lup_AC_Sales_Areas o
                    ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

-->Product Sales Persons
    ELSE
    IF @Option = 'Sales Person'
        BEGIN
            SELECT MAX(o.[Description]) as [Sales Person],
                   SUM(d.Extended_Amount - d.Tax_Amount) as Sales,
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) as Income
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                INNER JOIN AC_Customers c
                    ON c.AC_Customers_ID = h.AC_Customers_ID
                LEFT JOIN Lup_AS_Reps o
                    ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY o.[Description]
            ORDER BY Income DESC
        END

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-----------------------------------------------------------------------------
--Description   : sp_AS_1030
--Purpose       : Retrieves Sales for One Selected DAY from AS_Transactions
--              : for SalesAnalyst
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    :
--Date          : 31 OCT 2002
--Authors       : TB
--Version       : 1.0.0
-----------------------------------------------------------------------------
--NB always use float for date conversions
--NB NB NB NB - IMPORTANT DATE TESTS below
-----------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_1030
    (
    	@Choice int,
        @CompanyID int,
    	@StartDate datetime,
    	@EndDate datetime,
    	@StartPeriodNo int OUTPUT,
    	@EndPeriodNo int OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @ToDay varchar(5)

    IF @Choice = 0    --Daily Sales
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Day_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Day_Number(@EndDate)
        
            SELECT dbo.fn_AS_Get_Day_Number(h.Transaction_Date) AS [DateString],
                   SUM(d.Extended_Amount - d.Tax_Amount) AS [Sales],
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) AS [PriceDiscount],
                   SUM(d.Discount_Amount) AS [Discount],
                   SUM(d.Quantity * d.Unit_Cost) AS [Cost],
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [Income],
                   SUM(d.Quantity) AS [Quantity]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate AND
                 (dbo.fn_AS_Get_Day_Number(h.Transaction_Date) >= @StartPeriodNo AND    --must be >
                  dbo.fn_AS_Get_Day_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Day_Number(h.Transaction_Date)
            ORDER BY DateString DESC
        END

    ELSE
    IF @Choice = 1    --Hourly Sales
        BEGIN
        --> Converts StartDate (to avoid rounding up after 12:00 AM) to int
        --      e.g. 2002/10/31 = 37558
            SET @ToDay = CONVERT(varchar(5), CONVERT(int, @StartDate))
        
            SET @StartPeriodNo = dbo.fn_AS_Get_Hour_Number(@ToDay, @StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Hour_Number(@ToDay, @EndDate)
            
            SELECT dbo.fn_AS_Get_Hour_Number(@ToDay, h.Transaction_Date) AS [DateString],
                   SUM(d.Extended_Amount - d.Tax_Amount) AS [Sales],
                   SUM((d.Unit_Price - d.Original_Price) * d.Quantity) AS [PriceDiscount],
                   SUM(d.Discount_Amount) AS [Discount],
                   SUM(d.Quantity * d.Unit_Cost) AS [Cost],
                   SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [Income],
                   SUM(d.Quantity) AS [Quantity]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  h.Transaction_Date >= @StartDate AND
                  h.Transaction_Date <= @EndDate AND
                 (dbo.fn_AS_Get_Hour_Number(@ToDay, h.Transaction_Date) >= @StartPeriodNo AND    --must be >
                  dbo.fn_AS_Get_Hour_Number(@ToDay, h.Transaction_Date) <= @EndPeriodNo) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY dbo.fn_AS_Get_Hour_Number(@ToDay, h.Transaction_Date)
            ORDER BY DateString DESC
        END

SET NOCOUNT OFF


-----------------------------------------------------------------------------
--NB NB NB NB - IMPORTANT DATE TESTS
-----------------------------------------------------------------------------
-- DECLARE @StartDate datetime,
--         @EndDate datetime
-- 
-- -- SET @StartDate = '2002-10-31 00:00:00.001'    --Don't go lower than 001
-- -- SET @EndDate = '2002-10-31 23:59:59.998'      --Don't go higher than 998
-- 
-- SET @StartDate = '2002-10-31 07:59:00.001'
-- SET @EndDate = '2002-10-31 21:59:59.998'
-- 
-- SELECT @StartDate AS [StartDate],
--         CONVERT(float, @StartDate) AS [StartFLOAT],
--         CONVERT(decimal(12,6), @StartDate) AS [StartDECI],
--         CONVERT(varchar(5), CONVERT(int, @StartDate)) AS [StartINT],
--         RTRIM(LTRIM(convert(varchar(2),DATEPART(Hour,@StartDate)))) AS [StartHOUR],
--        @EndDate AS [EndDate],
--         CONVERT(float, @EndDate) AS [EndFLOAT],
--         CONVERT(decimal(12,6), @EndDate) AS [EndDECI],
--         CONVERT(varchar(5), CONVERT(int, @EndDate)) AS [EndINT],
--         RTRIM(LTRIM(convert(varchar(2),DATEPART(Hour,@EndDate)))) AS [EndHOUR]
-----------------------------------------------------------------------------















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--sp_AS_1040 1, 0, '38179', 0, 'All Sales', 1

-----------------------------------------------------------------------------
--Description   :sp_AS_1040
--Purpose       :Retrieves selected Category Sales Transaction Header
--              :Component_Type Popup Shape Data
--              :for whole Category from AS_Transactions
--              :    for SalesAnalyst
--Parameters    :
--Date          :27 MAY 2002
--Authors       :TB
--Version       :1.0.0
--MODS          :01/10/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :12/08/04 - Added h.Amount AS [Total], h.Comment AS [Notes]
--              :           and removed h.User_ID for Sales Analyst
-----------------------------------------------------------------------------

CREATE              PROCEDURE  sp_AS_1040
   (
        @CompanyID int,
        @PeriodType tinyint,        --Typically 0=WEEKS, 1=MONTHS
        @PeriodString varchar(6),   --Typically WEEKNO or YEARMONTHNO (5297 or 200106)
        @Component_Type tinyint,    --0=SALES, 1=Price Discount, 2=Sales Discount, 3=Cost etc
        @Option varchar(20),        --'Type', 'Group', 'Department', etc.
        @OptionID int               --TypeID, GroupID, DepartmentID, etc.
   )

AS

SET NOCOUNT ON

    DECLARE
        @sql varchar(6000)

    SET @sql = ' SELECT ' +
                    ' h.AS_Transactions_ID as [ID], ' +
                    ' ISNULL(c.Surname, '''') ' + ' ' +
                    ' + ' + ' ISNULL(c.Firstnames, '''') ' +
                    ' + ' + ''' (''' + ' + ' +
                    ' CONVERT(VARCHAR(10), c.AC_Customers_ID) ' +
                    ' + ' + ''')''' + ' AS [Customer], ' +
                    ' h.Amount AS [Total], ' +
                    ' h.Transaction_Date AS [Date], ' +
                    ' ISNULL(csh.Surname, '''') ' + ' ' +
                    ' + ' + ' ISNULL('', '' + csh.FirstName, '''') AS [Cashier], ' +
                    ' h.Transaction_Number AS [No], ' +
                    ' tt.Type_Code AS [Type], ' +
                    ' h.Comment AS [Notes] ' +
                ' FROM AS_Transactions h ' +
                    ' INNER JOIN AS_Transaction_Details d ' +
                        ' ON h.AS_Transactions_ID = d.AS_Transactions_ID ' +
                    ' INNER JOIN AC_Customers c ' +
                    '     ON c.AC_Customers_ID = h.AC_Customers_ID ' +
                    ' INNER JOIN Sys_AW_Transaction_Types tt ' +
                        ' ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID ' +
                    ' INNER JOIN AW_Users csh ' +
                        ' ON h.Lup_AS_Cashiers_ID = csh.AW_Users_ID ' +

                    ' INNER JOIN AP_Products p ' +
                        ' ON d.AP_Products_ID = p.AP_Products_ID ' +
                    ' INNER JOIN AW_Users u ' +
                        ' ON h.User_ID = u.AW_Users_ID '

--WHERE
    SET @sql = @sql +
                ' WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
                    '    h.Sys_AW_Transaction_Types_ID = 4) AND '

--Additional WHERE
    IF @Component_Type = 0    -- Sales
        SET @sql = @sql +
                    '  d.Extended_Amount - d.Tax_Amount <> 0 AND '
    ELSE
    IF @Component_Type = 1    -- Price Discount
        SET @sql = @sql +
                    '  ((d.Original_Price - d.Unit_Price) * d.Quantity) <> 0 AND '
    ELSE
    IF @Component_Type = 2    -- Sales Discount
        SET @sql = @sql +
                    '  (d.Discount_Amount) <> 0 AND '
    ELSE
    IF @Component_Type = 3    -- Cost
        SET @sql = @sql +
                    '  (d.Quantity * d.Unit_Cost) <> 0 AND '
------------------

    IF @Option = 'Type'
        SET @sql = @sql +
                    ' p.Lup_AP_Product_Types_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Group'
        SET @sql = @sql +
                    ' p.Lup_AP_Product_Groups_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql + 
                    ' p.Lup_AP_Product_Departments_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql + 
                    ' p.Default_Supplier_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql + 
                    ' p.Lup_AP_Product_Manufacturers_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql + 
                    ' p.Lup_AP_Product_Locations_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql + 
                    ' c.Lup_AC_Sales_Areas_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql + 
                    ' c.Lup_AS_Reps_ID = ' + CONVERT(VARCHAR(10), @OptionID) + ' AND ' +
                    ' d.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @CompanyID) + ' AND '
------------------
--     IF @PeriodType = 0    --WEEKS
--         SET @sql = @sql +
--                     '  CONVERT(int, h.Transaction_Date) / 7 = ' + @PeriodString + ' '

    IF @PeriodType = 0    --WEEKS
        SET @sql = @sql +
                    '  CONVERT(int, h.Transaction_Date) = ' + @PeriodString + ' '

    ELSE
    IF @PeriodType = 1    --MONTHS
        SET @sql = @sql +
                    ' (MONTH(h.Transaction_Date) = ' + SUBSTRING(@PeriodString,5,2) + ' AND ' +
                    ' YEAR(h.Transaction_Date) = ' + SUBSTRING(@PeriodString,1,4) + ') '

    SET @sql = @sql +
        ' ORDER BY h.Transaction_Date DESC '

--> RUN the script
--  --------------
    EXEC (@sql)


SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   : sp_AS_1050
--Purpose       : Retrieves Sales Transaction Details in POPUP
--              : for Sales Analyst
--              : that make up the aggregated SALES COMPONENTS
--              : ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Parameters    : Uses SHAPE and is part of sp_AS_1040
--Date          : 24 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_1050
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID as [ID], 
           d.AS_Transactions_ID AS [FKID], 
           p.Description as [Description                        ], 
          (d.Extended_Amount - d.Tax_Amount) AS [    Sales],
         ((d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj],
          (d.Discount_Amount) AS [ Discount],
          (d.Quantity * d.Unit_Cost) AS [    Cost],
         ((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [  Income],
          (d.Quantity) AS [ Qty]
    FROM AS_Transaction_Details d
            LEFT JOIN AP_Products p
                ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












--ALTER  Random Sales Transaction Header Records
--In AS_Transactions
--29 JAN 2002 - Added Tills and Cashiers

CREATE           PROCEDURE sp_AS_1900
	(
        @CustomersID int ,
    	@TotalCost money ,
    	@Amount money ,
    	@TotalTaxAmount money ,
    	@TotalDiscountAmount money ,
    	@TotalAmount money ,
    	@PaymentAmount money ,
    	@TransactionNumber varchar(19) ,
    	@TransactionDate datetime ,
    	@TransactionTypesID tinyint ,
        @TillsID smallint ,
        @CashiersID smallint
    )

AS

SET NOCOUNT ON

    INSERT INTO [AS_Transactions]
        (
        	AC_Customers_ID,
        	Transaction_Number,
        	Total_Cost,
        	Amount,
        	Total_Tax_Amount,
        	Total_Discount_Amount,
        	Total_Amount,
        	Payment_Amount,
        	Transaction_Date,
        	Sys_AW_Transaction_Types_ID,
        	Lup_AW_Stores_ID,
        	Lup_AW_Workstations_ID,
        	Lup_AS_Tills_ID,
        	Lup_AS_Cashiers_ID,    --01/10/02 - now contains AW_Users_ID
        	Lup_AS_Reps_ID,
        	Date_Captured,
        	[User_ID],
        	AW_User_Companies_ID,
        	Slu_AW_Active_ID
        )
    VALUES
        (
        	@CustomersID,
        	@TransactionNumber,
        	@TotalCost,
        	@Amount,
        	@TotalTaxAmount,
        	@TotalDiscountAmount,
        	@TotalAmount,
        	@PaymentAmount,
        	@TransactionDate,
        	@TransactionTypesID,
        	1,
        	1,
        	@TillsID,
        	@CashiersID,
        	1,
        	@TransactionDate,
        	@CashiersID,
        	1,
        	1
        )

return scope_identity()

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--ALTER  Random Sales Transaction Detail Records
--In AS_Transaction_Details

CREATE       PROCEDURE sp_AS_1901

	@ASTransactionsID int,
	@ProductID int,
	@Qty decimal(9,3),
	@LastCost money,
    @UnitPrice money,
	@Price1Current money,
	@DiscountAmount money,
	@TaxAmount money,
	@Amount money,
	@TransactionDate datetime

AS

SET NOCOUNT ON

INSERT INTO AS_Transaction_Details
    (
    	AS_Transactions_ID,
    	AP_Products_ID,
    	Quantity,
    	Unit_Cost,
    	Unit_Price,
    	Original_Price,
    	Discount_Amount,
    	Tax_Amount,
    	Extended_Amount,
    	Commission_Amount,
    	AP_Promotion_Products_ID,
    	Date_Captured,
    	[User_ID],
    	AW_User_Companies_ID,
    	Slu_AW_Active_ID
    )
VALUES
    (
    	@ASTransactionsID,
    	@ProductID,
    	@Qty,
    	@LastCost,
    	@UnitPrice,
    	@Price1Current,
    	@DiscountAmount,
    	@TaxAmount,
    	@Amount,
    	1,	--Commission Amount
    	1,	--AP_Promotion_Products_ID
    	@TransactionDate,
    	1,	--User ID
    	1,	--Company ID
    	1	--Active
    )

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Get one Product Record
--for the AS_Transaction_Details record

CREATE  PROCEDURE sp_AS_1902

	@ProductID int,
	@Price1Current decimal(9,3) OUTPUT,
	@LastCost decimal(9,3) OUTPUT

AS

SET NOCOUNT ON

SELECT @Price1Current=isnull(Price1_Price1,100),
	@LastCost=isnull(Last_Cost,50)
FROM AP_Products 
WHERE AP_Products_ID = @ProductID


SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--Update the Account Balance of a Customer
--with the Total_Amount of each AS_Transaction record

CREATE   PROCEDURE sp_AS_1903

    @CustomerID int,
    @Transaction_Amount money

AS

SET NOCOUNT ON

    UPDATE AC_Customers
    SET Account_Balance = Account_Balance + @Transaction_Amount
    WHERE AC_Customers_ID = @CustomerID

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--Description   : sp_AS_1904
--Purpose       : Inserts POS Payment Transaction Details
--Functionality : Tables: AS_Transaction_Payments
--Parameters    : 
--Date          : 2002/01/29
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE      PROCEDURE sp_AS_1904
	(
		@Amount				money 		    = NULL,	
		@PayorName			varchar(50) 	= NULL,
		@CardExpiryDate		varchar(6) 	    = NULL,
		@CardNo				varchar(20) 	= NULL,
		@AuthorisationNo	varchar(20) 	= NULL,
		@MethodID			int 			= NULL,
		@InstitutionID		int 			= NULL,
		@UserID				int 			= NULL,
		@CompanyID			int 			= NULL,
		@PaymentDetailsID	int 			= NULL,    -- Not Used ???
		@PaymentID			int 			= NULL,
		@Date				DateTime        = NULL
	)

AS

SET NOCOUNT ON

	INSERT AS_Transaction_Payments
    	(	
    		AS_Transactions_ID,
    		Sys_AW_Payment_Methods_ID, 
    		Slu_AS_Card_Institutions_ID,
    		Payor_Name,
    		Card_Expiry_Date,
    		Card_Number,
    		Authorisation_Number,
    		Amount,
    		[User_ID],
    		AW_User_Companies_ID,
    		Date_Captured
    	)
	VALUES
    	(
    		@PaymentID,
    		@MethodID,
    		@InstitutionID,
    		@PayorName,
    		@CardExpiryDate,
    		@CardNo,
    		@AuthorisationNo,
    		@Amount,
    		@UserID,
    		@CompanyID,
    		@Date
    	)

RETURN scope_identity() --@@Identity

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AS_1905
--Purpose       : Inserts POS Payment Transaction Splits
--Functionality : Tables: AS_Transactions_Transactions
--Parameters    : 
--Date          : 2002/01/30
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE       PROCEDURE sp_AS_1905
	(
		@SourceTransactionID    int = NULL ,
		@PaymentID			    int ,
		@TotalAmount			money = 0
	)

AS

SET NOCOUNT ON

	INSERT AS_Transactions_Transactions 
        (
            Source_AS_Transactions_ID,
            Destination_AS_Transactions_ID,
            Amount
        )
	VALUES
		(
            @SourceTransactionID,    --AS_Transactions_ID (Invoice etc)
            @PaymentID,              --AS_Transactions_ID (Its Payment)
            ABS(@TotalAmount)
        )

RETURN scope_identity() --@@Identity

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_Add_Column_Enterprise_Customer_Sales
--Purpose       :ADD COLUMNS to AS_Enterprise_Customer_Sales table
--Date          :2007/03/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AS_Add_Column_Enterprise_Customer_Sales
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AS_Enterprise_Customer_Sales'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AS_Enterprise_Customer_Sales ADD ' + @ColumnName + ' money NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Add_Column_Enterprise_GP
--Purpose       :ADD COLUMNS to AS_Enterprise_GP table
--Date          :2009/09/04
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_AS_Add_Column_Enterprise_GP
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AS_Enterprise_GP'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AS_Enterprise_GP ADD ' + @ColumnName + ' money NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_Add_Column_Enterprise_Sales
--Purpose       :ADD COLUMNS to AS_Enterprise_Sales table
--Date          :2007/03/12
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AS_Add_Column_Enterprise_Sales
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AS_Enterprise_Sales'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AS_Enterprise_Sales ADD ' + @ColumnName + ' money NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Add_Column_Enterprise_Sales_All
--Purpose       :ADD COLUMNS to AS_Enterprise_Sales_All table
--Date          :2009/09/30
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AS_Add_Column_Enterprise_Sales_All
    (
        @ColumnName varchar(50)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(1000),
            @TableID int,
            @RetCode int


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @RetCode = 0


    SELECT @TableID = sysobjects.id
    FROM sysobjects
    WHERE sysobjects.name = 'AS_Enterprise_Sales_All'


    IF NOT EXISTS
        (
            SELECT syscolumns.id
            FROM syscolumns
            WHERE syscolumns.id = @TableID AND
                  syscolumns.name = @ColumnName
        )
        BEGIN
            SET @sql = ' ALTER TABLE AS_Enterprise_Sales_All ADD ' + @ColumnName + ' money NULL '

            EXEC (@sql)

            SET @RetCode = 1
        END



RETURN @RetCode










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Add_Product_To_Sales_Orders
--Purpose       :Check if @ProductID EXISTS in Sales Orders
--				:If EXISTS then UPDATE else ADD new Sales Orders
--Date          :07 JUN 2008
--Authors       :TB
--MODS          :
--V6.3	RL	2017/04/06	:Added option to automaticaly add backorder items to shopping list
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Add_Product_To_Sales_Orders]
    (
        @CustomerID int,
    	@ProductID int,
    	@Description varchar(50),
    	@ProductCode varchar(20),
    	@Quantity decimal(9, 3),
    	@BackOrder decimal(9, 3),
    	@OriginalPrice money,
    	@UnitPrice money,
    	@DiscountAmount money,
    	@Amount money,
    	@Shipping money,
        @Tax_Rate decimal(9, 3),
    	@TaxAmount money,
    	@ExtendedAmount money,
    	@UnitCost money,
        @PromoProductID int,
    	@PromoPrice money,
    	@DateCaptured datetime,
    	@AddToBO int,
    	@Customer_Reference varchar(15),
		@Lup_AP_Product_Bins_ID int,
       	@UserID int,
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ExistingID int,
			
            @Last_Qty decimal(9,3),
            @Last_Disc money,
            @Last_Shipping money,
            @Last_BOQty decimal(9,3),
            @New_Qty decimal(9,3),
            @New_BOQty decimal(9,3),
			@New_TotalQty decimal(9,3),
            @New_Disc money,
            @New_Shipping money,
            @SubTotal money,
            @Tax money,
            @Total money,

			@AO_Suppliers_ID		int,
			@RemoteID				int,
			@AO_Order_Candidates_ID int,
			@Notes					varchar(50),
			@Customer_Name			varchar(40)		

    SELECT @ExistingID = AS_Sales_Order_Details_ID,
            @Last_Qty = Quantity,
            @Last_BOQty = Back_Order,
            @Last_Disc = Discount_Amount,
            @Last_Shipping = Shipping_Cost
    FROM AS_Sales_Order_Details
    WHERE AP_Products_ID = @ProductID AND
    		AC_Customers_ID = @CustomerID AND
    		AW_User_Companies_ID = @CompanyID AND
    		Customer_Reference = @Customer_Reference AND
			Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID

    IF @ExistingID is NULL
    BEGIN
    	EXEC sp_AS_Insert_Sales_Order_Details
                                    @CustomerID,
                                    @ProductID,
                                    @Description,
                                    @ProductCode,
                                    @Quantity,
                                    @BackOrder,
                                    @OriginalPrice,
                                    @UnitPrice,
                                    @DiscountAmount,
                                    @Amount,
                                    @Shipping,
                                    @Tax_Rate,
                                    @TaxAmount,
                                    @ExtendedAmount,
                                    @UnitCost,
                                    @PromoProductID,
                                    @PromoPrice,
                                    @DateCaptured,
                                    @AddToBO,
                                    @Customer_Reference,
									@Lup_AP_Product_Bins_ID,
                                    @UserID,
                                    @CompanyID
	END
    ELSE
	BEGIN
		--> COMBINE the new sales order with existing
        SET @New_Qty = @Last_Qty + @Quantity
        SET @New_Disc = ROUND(@Last_Disc + @DiscountAmount, 2)
        SET @New_Shipping = ROUND(@Last_Shipping + @Shipping, 2)
        SET @New_BOQty = @Last_BOQty + @BackOrder
        SET @New_TotalQty = @New_Qty + @New_BOQty

        SET @SubTotal = ROUND((@UnitPrice * @New_TotalQty) - @New_Disc, 2)
        SET @Tax = ROUND((@SubTotal + @New_Shipping) * (@Tax_Rate / 100), 2)
        SET @Total = ROUND(@SubTotal + @Tax, 2)


    	UPDATE AS_Sales_Order_Details							
    	SET [Description] = @Description,
            Product_Code = @ProductCode,
            Quantity = @New_Qty,
            Back_Order = @New_BOQty,
            Original_Price = @OriginalPrice,
            Unit_Price = @UnitPrice,
            Discount_Amount = @New_Disc,
            Amount = @SubTotal,
            Shipping_Cost = @New_Shipping,
            Tax_Rate = @Tax_Rate,
            Tax_Amount = @Tax,
            Extended_Amount = @Total,
            Unit_Cost = @UnitCost,
            AP_Promotion_Products_ID = @PromoProductID,
            Promo_Price = @PromoPrice,
            Date_Captured = @DateCaptured,
            [User_ID] = @UserID,
            AW_User_Companies_ID = @CompanyID
    	WHERE AS_Sales_Order_Details_ID = @ExistingID   		
	END	

	--Add to purchase orders shopping list
	--@AddToBO = 6 is the VB6 integer value for yes
	IF @BackOrder <> 0 And @AddToBO = 6
	BEGIN
				
		SET @AO_Suppliers_ID = 1
				
		SELECT TOP 1 @AO_Suppliers_ID = s.AO_Suppliers_ID
		FROM AP_Products_Suppliers ps
			INNER JOIN AO_Suppliers s
				ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
		WHERE ps.AP_Products_ID = @ProductID
		AND ps.Slu_AW_Active_ID = 1
		AND s.Slu_AW_Active_ID = 1
		And GETDATE() Between ps.[Start_Date] And '2999-01-01'
				
		SET @RemoteID = 0
				
		SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
		FROM AW_Remote_Access
		WHERE AW_User_Companies_ID = @CompanyID
		AND Default_Connection = 1

		SELECT @Customer_Name = Surname
		FROM AC_Customers
		WHERE AC_Customers_ID = @CustomerID

		SET @Notes = 'Back Order - ' + @Customer_Name
				
		EXEC @AO_Order_Candidates_ID = sp_AO_Add_Product_To_Order_Candidates_RET @ProductID, @AO_Suppliers_ID, @BackOrder, @Notes, @UserID ,@UserID , @CompanyID, @RemoteID

	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   : sp_AS_Banking_Cash_Ups_Select
--Purpose       : Fetch Banking Cash-Ups data
--Functionality : Tables: AS_Cash_Ups
--Parameters    : 
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Banking_Cash_Ups_Select
	(
		@CompanyID int
	)
AS

	SELECT pm.Description as [Method],
           SUM(ISNULL(cu.Amount, 0)) as [Amount],
           pm.Sys_AW_Payment_Methods_ID as [MethodID],
           cu.AW_User_Companies_ID as [CompanyID]

	 FROM AS_Cash_Ups cu
		LEFT JOIN
            (
                SELECT Sys_AW_Payment_Methods_ID,
                       [Description]
                FROM Sys_AW_Payment_Methods 
                    UNION
                SELECT (-1),
                       'Surplus/Deficit'
            ) pm
            ON cu.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID
	WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1
	GROUP BY cu.AW_User_Companies_ID, pm.Sys_AW_Payment_Methods_ID, pm.[Description]








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   : sp_AS_Banking_Coinage_Select
--Purpose       : Fetch the Banking Coinage
--Functionality : Tables: AS_Cash_Ups
--Parameters    : 
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Banking_Coinage_Select
	(
		@CompanyID int
	)

AS

	SELECT c.Description,
           SUM(ISNULL(cu.Amount, 0)) as [Amount],
           cu.Sys_AW_Payment_Methods_ID as [MethodID]
	FROM AS_Cash_Ups cu
        INNER JOIN Slu_AS_Coinage c
            ON cu.Slu_AS_Coinage_ID = c.Slu_AS_Coinage_ID
	WHERE cu.AW_User_Companies_ID = @CompanyID AND
          cu.Slu_AW_Active_ID = 1
	GROUP BY cu.Sys_AW_Payment_Methods_ID, c.[Description]










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--Used in the banking
CREATE  PROCEDURE sp_AS_Banking_Payment_Methods_Select
	(
		@CompanyID int
	)
AS
	SELECT 
		Sys_AW_Payment_Methods_ID as ID, 
		Description , 
		@CompanyID as CompanyID  
	FROM Sys_AW_Payment_Methods
	WHERE Sys_AW_Payment_Methods_ID <> 1 AND 
			  Sys_AW_Payment_Methods_ID <> 7 AND 
			  Sys_AW_Payment_Methods_ID <> 10










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   : sp_AS_Banking_Payments_Select
--Purpose       : Fetch the Banking Coinage
--Functionality : Tables: vw_AS_Payments_Select
--Parameters    : 
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Banking_Payments_Select
    (
        @CompanyID int
    )

AS

	SELECT *
    FROM vw_AS_Payments_Select
	WHERE CompanyID = @CompanyID AND
          Banked IS NULL AND
          MethodID <> 2









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Banking_Post
--Purpose       :Inserts Normal Journal and GL Transactions in BANKING POST
--              :for ACTIVE Cash Ups except EFTPOS
--              :(NB: SURPLUS/DEFICIT is done in sp_AS_Cash_Up_Post)
--Tables        :AS_Cash_Ups
--Parameters    :
--Date          :2002/02/06
--Authors       :TB
--Version       :1.0.0
--MODS          :18/07/02 - Changed CASH-UP GLTranTypeID = 27 (was 23).
--              :            ID 23 is now 'Accounts Receivable - Interest'
--              :           NB NB NB: REQUIRES DB Schema change:
--              :            Add 2x NEW Sys_AB_Transaction_Types rows
--              :19/07/02 - Modified NARRATION to be more explanatory in GL
--              :26/09/02 - Modified Sign of @Amount to -@Amount to be
--              :            inserted into AB_Cash_Book_Transactions in
--              :            sp_AB_Insert_Cash_Book_Transactions where ALL
--              :            amounts are converted to a negative value (JW)
--              :21/10/02 - Added Payment Methods 7 & 8 and split 4 & 5
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_Banking_Post
	(
		@MethodID money,
		@Amount money,
		@Year int,
		@Month int,
		@BankAccountID int,
		@UserID int,
		@CompanyID int
	)
AS

SET NOCOUNT ON

	DECLARE @NextGLTranTypeID int,
            @CBHeaderID int,
            @JNLHeaderID int,
            @GLControlAccount int,
	        @Date DateTime,
            @Narration varchar(30),
            @Banks_GL_Account_ID int,
            @TempAmount money


	SET @Date = GetDate()


-- Sys_AW_Payment_Methods_ID
----------------------------
-- 1	<None>
-- 2	Cash
-- 3	Cheque
-- 4	Credit Card
-- 5	Debit Card
-- 6	EFTPOS
-- 7	Account
-- 8	RCS Auto
-- 9	Buy Association
-- 10	COD
-- 11	Voucher
-- 12	Foreign Currency
----------------------------

	IF @MethodID = 2
	    SET @Narration = 'Bank Deposit - Cash'
	ELSE
	IF @MethodID = 3
	    SET @Narration = 'Bank Deposit - Cheques'
	ELSE
	IF @MethodID = 4
	    SET @Narration = 'Bank Deposit - Credit Cards'
    ELSE
	IF @MethodID = 5
	    SET @Narration = 'Bank Deposit - Debit Cards'
	ELSE
	IF @MethodID = 6
	    SET @Narration = 'Bank Deposit - EFTPOS'
	ELSE
	IF @MethodID = 7
	    SET @Narration = 'Bank Deposit - Account'
	ELSE
	IF @MethodID = 8
	    SET @Narration = 'Bank Deposit - RCS Auto'
	ELSE
	IF @MethodID =  9 
	    SET @Narration = 'Bank Deposit - Buy Association'
	ELSE
	    SET @Narration = 'Bank Deposit - Other'

	BEGIN TRANSACTION

		IF @MethodID = -1    --Do NORMAL JOURNAL for Surplus/Deficit
			BEGIN

        		UPDATE AS_Cash_Ups
                SET Slu_AW_Active_ID = 2 
        		WHERE Sys_AW_Payment_Methods_ID = @MethodID AND 
                     (Slu_AW_Active_ID IS NULL OR
                      Slu_AW_Active_ID = 1) 

            --> NB Surplus = negative amount, Deficit = positive amount

			END
		ELSE        --Do CASHBOOK ENTRY for Normal Cashed Up values
    		BEGIN
    
    			EXEC @NextGLTranTypeID = sp_AB_Next_Transaction_Number
                                                    10,        --10 = CB Deposit
                                                    @CompanyID

            --> see 26/09/02 - Sign Convertion REQUIRED
                SET @TempAmount = @Amount * -1
    
    			EXEC @CBHeaderID = sp_AB_Insert_Cash_Book_Transactions
                                    @BankAccountID,
                                    10,                --10 = CB Deposit
                                    @Date,
                                    @Month,
                                    @Year,
                                    @NextGLTranTypeID,
                                    @Narration,
                                    @TempAmount,
                                    @UserID,
                                    @CompanyID,
                                    0            -- 0 Flag: Do Not insert a GL Transaction
    
            --> Get the AB_Accounts_ID for the select bank account
        		SELECT @Banks_GL_Account_ID = ISNULL(AB_Accounts_ID, 1)
        		FROM AW_Company_Banks 
        		WHERE AW_User_Companies_ID = @CompanyID AND
                      AW_Company_Banks_ID = @BankAccountID
    
            --> Do the Debit to Bank Control (@Amount is positive in AS_Cash_Ups)
            --> This sp also writes the GL Transaction for the Transaction and VAT
                EXEC sp_AB_Insert_Cash_Book_Transactions_Details
                        @CBHeaderID,
                        @Banks_GL_Account_ID,
                        3,
                        @Amount,
                        1,
                        NULL,
                        @Amount,
                        @Narration,
                        @Narration,
                        @UserID,
                        @CompanyID,
                        0            -- 0 Flag: Do Not insert a GL Transaction
    
            --> Create GL TRANSACTION for Select Bank Account (@Banks_GL_Account_ID)
                EXEC sp_AB_Insert_GL_Transactions
                       @Narration,
                       27,                    --27 = AR Cash-Up
                       @Banks_GL_Account_ID,  --@AB_Accounts_ID
                       @Date,                 --NEW
                       'Cash Up Banking',     --NEW
                       @Month,                --@AW_Months_ID
                       @Year,                 --@AW_Years_ID
                       @NextGLTranTypeID,     --@Transaction_Ref
                       @Amount,               --@Deposit Amount
                       @UserID,               --@User_ID
                       @CompanyID             --@Company_ID
    
    			SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 206    --Cash Control Account
    
    			SET @Amount = -@Amount    --Now Credit the Cash Control
    			
            --> Create GL TRANSACTION for Cash Control Account
                EXEC sp_AB_Insert_GL_Transactions
                       @Narration,
                       27,                    --27 = AR Cash-Up
                       @GLControlAccount,     --@AB_Accounts_ID
                       @Date,                 --NEW
                       '206 Cash Control',    --NEW
                       @Month,                --@AW_Months_ID
                       @Year,                 --@AW_Years_ID
                       @NextGLTranTypeID,     --@Transaction_Ref
                       @Amount,               --@Deposit Amount
                       @UserID,               --@User_ID
                       @CompanyID             --@Company_ID

        		UPDATE AS_Cash_Ups
                SET Slu_AW_Active_ID = 2 
        		WHERE Sys_AW_Payment_Methods_ID = @MethodID AND 
                     (Slu_AW_Active_ID IS NULL OR
                      Slu_AW_Active_ID = 1) 

    		END

	COMMIT TRANSACTION

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   : sp_AS_Banking_Select
--Purpose       : Fetch the used Payment Methods except EFTPOS from AS_Cash_Ups
--Functionality : Tables: AS_Cash_Ups
--Parameters    : 
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AS_Banking_Select
	(
		@CompanyID int
	)

AS

SET NOCOUNT ON

	SELECT Sys_AW_Payment_Methods_ID,
           SUM(ISNULL(Amount, 0)) as [Amount] 
	FROM AS_Cash_Ups 
	WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND 
		  Sys_AW_Payment_Methods_ID <> 6        --EFTPOS
	GROUP BY Sys_AW_Payment_Methods_ID

	    UNION

	SELECT Sys_AW_Payment_Methods_ID,
           ISNULL(Amount, 0) as [Amount] 
	FROM AS_Cash_Ups 
	WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND 
		  Sys_AW_Payment_Methods_ID = 6         --EFTPOS
		  

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS
--Purpose       :Get Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
--RL	V6_1	2015-02-17	:Use froam and to Day End dates sent through
--							:Added Inclusion and Exclusion Checks
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
AS

SET NOCOUNT ON

	Declare @CompanyNo			Int,
			@LastDayEnd			DateTime,
			@WhichName			Tinyint,
			@Loop_Ind			Int,
			@ptrval				binary(16),
			@OffSet				Int,
			
			@AS_Transactions_ID	Int,
			@Transaction_Number	Varchar(20),
			@Transaction_Date	Datetime,
			@Customer_Reference	Varchar(15), --Reg No
			@Comment			Varchar(20), --Make
			
			@Quantity			Decimal(9,3),
			@Extended_Amount	Decimal(18,3),
			@Product_Description	Varchar(50),
			@Product_Code		Varchar(20),
			
			@F_Surname			Varchar(50),
			@F_Initials			Varchar(10),
			@F_Title			Varchar(50),
			@F_ID_Number		Varchar(20),
			@F_PostalAddress1	Varchar(40),
			@F_PostalAddress2	Varchar(40),
			@F_PostalAddress3	Varchar(40),
			@F_PostalCode		Varchar(10),
			@F_HomeTelNo		Varchar(20),
			@F_WorkTelNo		Varchar(20),
			@F_MobileTelNo		Varchar(20),
			@F_Vehicle_Desc		Varchar(50),
			@F_Vehicle_Reg_No	Varchar(50),
			@F_Branch_Code		Varchar(20),
			@F_InvoiceNo		Varchar(20),
			@F_NoOfTyres		Varchar(20),
			@F_Price			Decimal(18,2),

			@C_Surname			Varchar(40),
			@C_Initials			Varchar(10),
			@C_Firstnames		Varchar(10),
			@C_Title			Varchar(50),
			@C_ID_Number		Varchar(20),
			@C_PostalAddress1	Varchar(40),
			@C_PostalAddress2	Varchar(40),
			@C_PostalAddress3	Varchar(40),
			@C_PostalCode		Varchar(10),
			@C_HomeTelNo		Varchar(20),
			@C_WorkTelNo		Varchar(20),
			@C_MobileTelNo		Varchar(20),

			@T_Surname			Varchar(50),
			@T_PostalAddress1	Varchar(40),
			@T_PostalAddress2	Varchar(40),
			@T_PostalAddress3	Varchar(40),
			@T_PostalCode		Varchar(10),
			
			@F_TyreData_1		Varchar(4000),
			@F_TyreData_2		Varchar(4000),
			@F_TyreData_3		Varchar(4000),
			@F_TyreData_4		Varchar(4000),
			@F_TyreData_5		Varchar(4000),
			@No_Days			Int,
			@Temp_No_Days		Varchar(20),
			@Details_Found		Int,
			@sql				Varchar(8000)
			
	DECLARE @Tbl_T Table
		(
			AS_Transactions_ID	Int,
			AC_CustomersID		Int,
			Transaction_Number	Varchar(20),
			Transaction_Date	Datetime,
			Customer_Reference	Varchar(15), --Make
			Comment				Varchar(20), --Reg No
		
			C_Surname			Varchar(40),
			C_Initials			Varchar(10),
			C_Firstnames		Varchar(50),
			C_Title				Varchar(50),						
			C_ID_Number			Varchar(20),
			C_PostalAddress1	Varchar(40),			
			C_PostalAddress2	Varchar(40),
			C_PostalAddress3	Varchar(40),
			C_PostalCode		Varchar(10),
			C_HomeTelNo			Varchar(20),
			C_WorkTelNo			Varchar(20),
			C_MobileTelNo		Varchar(20),			

			T_Surname			Varchar(50),
			T_PostalAddress1	Varchar(40),
			T_PostalAddress2	Varchar(40),
			T_PostalAddress3	Varchar(40),
			T_PostalCode		Varchar(10)
		)
		
	DECLARE @Tbl_F Table
		(
			F_TyreData_1 Text,
			F_TyreData_2 Varchar(1),
			F_TyreData_3 Varchar(1),
			F_TyreData_4 Varchar(1),
			F_TyreData_5 Varchar(1)
		)

	SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') From AW_User_Companies
                      	
	SELECT 
		TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM 
		Sys_AW_Options
	WHERE 
		Control_Index = 0 AND
		Control_Type = 'CheckBox' AND
		Control_Name = 'chkPOSPrintTradeName'
	
    SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
	
	--RL V6_1 Changed to use dates sent through				
	--If Exists	
	--(
	--	Select 1
	--	From AS_Day_Ends
	--)
	--Begin 
	--	Select @LastDayEnd = MAX(Day_End) From AS_Day_Ends
	--	Select @LastDayEnd = DateAdd(d,(@No_Days*-1),@LastDayEnd)
	--End
	--Else
	--Begin		
	--	Select @LastDayEnd = '1900-01-01'
	--End	

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	--Exec (@sql)

	
	--Exec (@sql)

	DECLARE Get_Data CURSOR
	FOR
	SELECT
		DISTINCT t.AS_Transactions_ID, t.Transaction_Number, t.Transaction_Date,
		LTRIM(RTRIM(ISNULL(s.Make,''))), LTRIM(RTRIM(ISNULL(s.Reg_No,''))),
		LTRIM(RTRIM(ISNULL(c.Surname,''))), LTRIM(RTRIM(ISNULL(c.Initials,''))), LTRIM(RTRIM(ISNULL(c.Firstnames,''))),
		LTRIM(RTRIM(ISNULL(x.[Description],''))), LTRIM(RTRIM(ISNULL(c.IDReg_Number,''))),
		LTRIM(RTRIM(ISNULL(c.Post_Box,''))), LTRIM(RTRIM(ISNULL(c.Post_Office,''))), LTRIM(RTRIM(ISNULL(c.City,''))) ,LTRIM(RTRIM(ISNULL(c.Post_Code,''))),
		LTRIM(RTRIM(ISNULL(c.Home_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Work_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Cell_No,''))),
		LTRIM(RTRIM(ISNULL(d.Customer_Name,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address1,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address2,''))),
		LTRIM(RTRIM(ISNULL(d.Inv_City,''))), LTRIM(RTRIM(ISNULL(d.Inv_Code,'')))
	FROM
		AS_Transactions t
    		LEFT OUTER JOIN AC_Customers c
    			ON t.AC_Customers_ID = c.AC_Customers_ID
    		LEFT OUTER JOIN AS_Transactions_Address a
    			ON t.AS_Transactions_ID = a.AS_Transactions_ID
    		LEFT OUTER JOIN AS_Transactions_Address_Detail d
    			ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
    		LEFT OUTER JOIN Slu_AW_Titles x
    			ON x.Slu_AW_Titles_ID = c.Slu_AW_Titles_ID
    		LEFT OUTER JOIN AC_Assets s
    			ON s.AS_Transactions_ID = t.AS_Transactions_ID
   	WHERE
    	(t.Sys_AW_Transaction_Types_ID = 3 OR
	   	 t.Sys_AW_Transaction_Types_ID = 4) AND
    	t.Slu_AW_Active_ID = 1 AND
    	ISNULL(t.Total_Amount,0) <> 0 AND
        t.Day_End >=  @StartDayEndDate AND 
        t.Day_End <= @EndDayEndDate AND
        t.AW_User_Companies_ID = @CompanyID
    	Order By t.Transaction_Date

	--Exec (@sql)
	--Select (@sql)

	OPEN Get_Data
	
	 FETCH NEXT FROM Get_Data INTO
		@AS_Transactions_ID, @Transaction_Number, @Transaction_Date, @Customer_Reference, @Comment,
		@C_Surname, @C_Initials, @C_Firstnames, @C_Title, @C_ID_Number,
		@C_PostalAddress1, @C_PostalAddress2, @C_PostalAddress3, @C_PostalCode,
		@C_HomeTelNo, @C_WorkTelNo, @C_MobileTelNo,
		@T_Surname, @T_PostalAddress1, @T_PostalAddress2, @T_PostalAddress3, @T_PostalCode
	
	 WHILE @@FETCH_STATUS = 0
	 BEGIN
--Select @AS_Transactions_ID, @StartDayEndDate, @No_Days
		SET @F_TyreData_1 = ''
		SET @F_TyreData_2 = ''
		SET @F_TyreData_3 = ''
		SET @F_TyreData_4 = ''
		SET @F_TyreData_5 = ''
		
		SET @F_Surname = ''
		SET @F_Initials = ''
		SET @F_Title = ''
		SET @F_ID_Number = ''
		SET @F_PostalAddress1 = ''
		SET @F_PostalAddress2 = ''
		SET @F_PostalAddress3 = ''
		SET @F_PostalCode = ''
		SET @F_HomeTelNo = ''
		SET @F_WorkTelNo = ''
		SET @F_MobileTelNo = ''
		SET @F_Vehicle_Desc = ''
		SET @F_Vehicle_Reg_No = ''
		SET @F_InvoiceNo = ''
		SET @F_NoOfTyres = '0'
				
		--SELECT
		--	@F_NoOfTyres = Convert(Int,SUM(ISNULL(d.Quantity,0)))
		--FROM
		--	AS_Transaction_Details d
		--		LEFT OUTER JOIN AP_Products p
		--			ON d.AP_Products_ID = p.AP_Products_ID
		--WHERE
		--	AS_Transactions_ID = @AS_Transactions_ID AND
		--	ISNULL(d.Extended_Amount,0) <> 0 AND
		--	d.Slu_AW_Active_ID = 1 AND
		--	p.Slu_AW_YesNo_Non_Stock_Item = 0							
		
		IF @T_Surname <> ''
		BEGIN
			IF @WhichName = 1
			BEGIN
				IF RTRIM(LTRIM(@C_Surname)) + ISNULL((', ' + @C_Initials),'') + ' / ' + IsNull(@C_Firstnames,'') = @T_Surname
				BEGIN
					SET @F_Surname = @C_Surname
					SET @F_Initials = @C_Initials
					SET @F_Title = @C_Title
				END
				ELSE
				BEGIN
					SET @F_Surname = @T_Surname
					SET @F_Initials = ''
					SET @F_Title = ''			
				END
			END
			ELSE
			BEGIN
				IF RTRIM(LTRIM(@C_Surname)) + ISNULL((', ' + @C_Initials),'') = @T_Surname
				BEGIN
					SET @F_Surname = @C_Surname
					SET @F_Initials = @C_Initials
					SET @F_Title = @C_Title
				END
				ELSE
				BEGIN
					SET @F_Surname = @T_Surname
					SET @F_Initials = ''
					SET @F_Title = ''			
				END
			END
			
			 IF (@T_PostalAddress1 <> '''' OR @T_PostalAddress2 <> '''' OR @T_PostalAddress3 <> '''' OR @T_PostalCode <> '''')
			 BEGIN
				SET @F_PostalAddress1 = @T_PostalAddress1
				SET @F_PostalAddress2 = @T_PostalAddress2
				SET @F_PostalAddress3 = @T_PostalAddress3
				SET @F_PostalCode = @T_PostalCode
			 END
			 ELSE
			 BEGIN
				SET @F_PostalAddress1 = @C_PostalAddress1
				SET @F_PostalAddress2 = @C_PostalAddress2
				SET @F_PostalAddress3 = @C_PostalAddress3
				SET @F_PostalCode = @C_PostalCode
			 END
		END
		ELSE
		BEGIN
			SET @F_Surname = @C_Surname
			SET @F_Initials = @C_Initials
			SET @F_Title = @C_Title
			SET @F_PostalAddress1 = @C_PostalAddress1
			SET @F_PostalAddress2 = @C_PostalAddress2
			SET @F_PostalAddress3 = @C_PostalAddress3
			SET @F_PostalCode = @C_PostalCode
		END
		
		SET @F_ID_Number = @C_ID_Number
		SET @F_HomeTelNo = @C_HomeTelNo
		SET @F_WorkTelNo = @C_WorkTelNo
		SET @F_MobileTelNo = @C_MobileTelNo
		SET @F_Vehicle_Desc = @Customer_Reference
		SET @F_Vehicle_Reg_No = @Comment
		SET @F_InvoiceNo = @Transaction_Number
				
		SELECT @F_TyreData_1 = '1' + ','+
								REPLACE(@F_Surname,',','~') + ','+
								REPLACE(@F_Initials,',','~') + ','+
								REPLACE(@F_Title,',','~') + ','+
								REPLACE(@F_ID_Number,',','~') + ','+
								REPLACE(@F_PostalAddress1,',','~') + ','+
								REPLACE(@F_PostalAddress2,',','~') + ','+
								REPLACE(@F_PostalAddress3,',','~') + ','+
								REPLACE(@F_PostalCode,',','~') + ','+
								REPLACE(@F_HomeTelNo,',','~') + ','+
								REPLACE(@F_WorkTelNo,',','~') + ','+
								REPLACE(@F_MobileTelNo,',','~') + ','+
								REPLACE(@F_Vehicle_Desc,',','~') + ','+
								REPLACE(@F_Vehicle_Reg_No,',','~') + ','+								
								REPLACE(@F_Branch_Code,',','~') + ','+
								REPLACE(@F_InvoiceNo,',','~') + ','+
								--REPLACE(@F_NoOfTyres,',','~') + ','
								'XXXXXXXXXXXXXXXXX' + ','

		SET @Details_Found = 0
		SET @F_NoOfTyres = '0'
		
	SET @sql = 'DECLARE Get_Detail CURSOR '
	SET @sql = @sql + ' FOR '
	SET @sql = @sql + ' SELECT '
	SET @sql = @sql + '		ISNULL(d.Quantity,0), ISNULL(d.Extended_Amount,0), '
	SET @sql = @sql + '		LTRIM(RTRIM(ISNULL(p.Description,''''))), '
	SET @sql = @sql + '		LTRIM(RTRIM(ISNULL(p.Product_Code,''''))) '
	SET @sql = @sql + ' FROM '
	SET @sql = @sql + '		AS_Transaction_Details d '
	SET @sql = @sql + '		INNER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '

    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '			ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
			
	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + '	d.AS_Transactions_ID = ' + CONVERT(varchar(30), @AS_Transactions_ID) + ' AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 '
			
	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
--Select @sql
	Exec (@sql)
				
	 	OPEN Get_Detail
		
		FETCH NEXT FROM Get_Detail INTO
			@Quantity, @Extended_Amount, @Product_Description, @Product_Code
			
		WHILE @@FETCH_STATUS = 0
		BEGIN
				
--Select 		@AS_Transactions_ID, @Quantity, @Extended_Amount, @Product_Description, @Product_Code

	
			SET @Details_Found = 1
			SET @F_Price = 0
			SET @F_Price = Convert(Decimal(18,2), (@Extended_Amount/ABS(@Quantity)))
			
			SET @Loop_Ind = 1
			
			IF @Quantity < 0
				SET @Quantity = @Quantity * -1
			
			SET @F_NoOfTyres = Convert(Varchar(10), ( Convert(Decimal(9,3),@F_NoOfTyres) + @Quantity ) )
			
			WHILE @Loop_Ind <= @Quantity
			BEGIN
				IF Len(@F_TyreData_1) < 3850
				BEGIN
					SET @F_TyreData_1 = @F_TyreData_1 +
										Convert(Varchar(10),@Transaction_Date,111) + ','+
										Convert(Varchar(20),@F_Price) + ','+
										REPLACE(@Product_Code,',','~') + ','+
										REPLACE(@Product_Description,',','~') + ',,'
				END
				ELSE
				IF (Len(@F_TyreData_1) >= 3850 AND Len(@F_TyreData_2)<3850)
				BEGIN
					SET @F_TyreData_2 = @F_TyreData_2 +
										Convert(Varchar(10),@Transaction_Date,111) + ','+
										Convert(Varchar(20),@F_Price) + ','+
										REPLACE(@Product_Code,',','~') + ','+
										REPLACE(@Product_Description,',','~') + ',,'
				END
				
				SET @Loop_Ind = @Loop_Ind+1
			END
		
			FETCH NEXT FROM Get_Detail INTO
				@Quantity, @Extended_Amount, @Product_Description, @Product_Code
		END
		CLOSE Get_Detail
		Deallocate Get_Detail

		IF NOT (Len(@F_TyreData_1) >= 3850 AND Len(@F_TyreData_2) >= 3850)
		BEGIN
			IF @Details_Found = 1
			BEGIN
				SET @F_TyreData_1 = REPLACE(@F_TyreData_1, 'XXXXXXXXXXXXXXXXX', @F_NoOfTyres)
			
				INSERT INTO @Tbl_F(F_TyreData_1) Values(@F_TyreData_1+@F_TyreData_2+@F_TyreData_3+@F_TyreData_4+@F_TyreData_5)
			END
		END
	
		FETCH NEXT FROM Get_Data INTO
			@AS_Transactions_ID, @Transaction_Number, @Transaction_Date, @Customer_Reference, @Comment,
			@C_Surname, @C_Initials, @C_Firstnames, @C_Title, @C_ID_Number,
			@C_PostalAddress1, @C_PostalAddress2, @C_PostalAddress3, @C_PostalCode,
			@C_HomeTelNo, @C_WorkTelNo, @C_MobileTelNo,
			@T_Surname, @T_PostalAddress1, @T_PostalAddress2, @T_PostalAddress3, @T_PostalCode 
	 END
	 CLOSE Get_Data
	 DEALLOCATE Get_Data

	 SELECT ISNULL(F_TyreData_1,'') AS [F1], ISNULL(F_TyreData_2,'') AS [F2],
			ISNULL(F_TyreData_3,'') AS [F3], ISNULL(F_TyreData_4,'') AS [F4],
			ISNULL(F_TyreData_5,'') AS [F5]
	 FROM @Tbl_F

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS_SEL
--Purpose       :Select Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	c.Surname AS [Customer Name] '	
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '		ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW
--Purpose       :Get Sales Submission Data For Rewards Program
--Parameters    :
--Date          :2014-10-15
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
AS

SET NOCOUNT ON

	DECLARE @LastDayEnd				DateTime,
			@Temp_No_Days			Varchar(20),	
			@No_Days				Int,
			@F_Branch_Code			Varchar(5),
			@Transaction_Type		Varchar(2),
			@Transaction_Number		Varchar(20),
			@Transaction_Date		Varchar(8),
			@Transaction_Time		Varchar(5),
			@Rep_ID					Varchar(5),
			@Rep_Name				Varchar(30),
			@Product_Code			Varchar(20),
			@Product_Description	Varchar(50),
			@Quantity				Varchar(20),
			@OLD_Transaction_Number	Varchar(20),
			@sql					Varchar(8000)
		
	DECLARE @Tbl_F Table
		(
			[Rec] Text
		)

	--SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') FROM AW_User_Companies
     
    SET @OLD_Transaction_Number = '' 
                      	
   SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
			
	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
	
	SET @sql = '        DECLARE Get_Data CURSOR FOR '
	SET @sql = @sql + '	SELECT '
	SET @sql = @sql + '		CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '		WHEN 3 THEN ''' + 'IN' +  ''' '
	SET @sql = @sql + '		WHEN 4 THEN ''' + 'CN' +  ''' '
	SET @sql = @sql + '		ELSE ''' + 'UN' +  ''' '
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(t.Transaction_Number,''''), '					--Transaction Number
	SET @sql = @sql + '		CONVERT(Varchar(10),t.Transaction_Date,112), '		--Transaction Date
	SET @sql = @sql + '		CONVERT(Varchar(5),t.Transaction_Date,108), '			--Transaction Time
	SET @sql = @sql + '		CONVERT(VARCHAR(20),IsNull(t.Lup_AS_Reps_ID,0)), '	--Transaction Rep ID
	SET @sql = @sql + '		CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '		WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '     
	SET @sql = @sql + '		ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(p.Product_Code,''''), '							--Product Code
	SET @sql = @sql + '		ISNULL(p.[Description],''''), '							--Product Description
	SET @sql = @sql + '		CONVERT(Varchar(20),ISNULL(d.Quantity,0)) '			--Quantity
	SET @sql = @sql + '		FROM ' 
	SET @sql = @sql + '		AS_Transactions t '
	SET @sql = @sql + '		INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '			ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN Lup_AS_Reps r '
	SET @sql = @sql + '			ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '			ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '			
	
	SET @sql = @sql + '	WHERE ' 
	SET @sql = @sql + '		(t.Sys_AW_Transaction_Types_ID = 3  OR '      -- Invoices
	SET @sql = @sql + '		 t.Sys_AW_Transaction_Types_ID = 4)  AND '    -- Refunds	
	SET @sql = @sql + '     t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   			
	SET @sql = @sql + '		t.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		t.Total_Amount <> 0 AND '
	SET @sql = @sql + '		p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'	
    SET @sql = @sql + '		t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '		t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '		

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
	SET @sql = @sql + '	ORDER BY t.Transaction_Date ' 	  	
--	Select @sql
	Exec (@sql)
	
	OPEN Get_Data
	
	FETCH NEXT FROM Get_Data INTO 
		@Transaction_Type,	@Transaction_Number, @Transaction_Date, @Transaction_Time,
		@Rep_ID, @Rep_Name, @Product_Code, @Product_Description, @Quantity

	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		SELECT @Rep_Name = Replace(@Rep_Name,',',' ')
		SELECT @Product_Code = Replace(@Product_Code,',',' ')
		SELECT @Product_Description = Replace(@Product_Description,',',' ')				
		
		IF @OLD_Transaction_Number != @Transaction_Number
		BEGIN
			--Insert Header Sales Records
			INSERT INTO @Tbl_F
			(
				[Rec]
			)
			VALUES
			(
				'H' + ',' +
				@Transaction_Number + ',' +
				@Transaction_Date + ',' +
				@Transaction_Time + ',' +
				@Transaction_Type + ',' +
				@Rep_ID + ' - ' + @Rep_Name + ','
			)
		END
		
		SET @OLD_Transaction_Number = @Transaction_Number		
		
		IF @OLD_Transaction_Number = @Transaction_Number
		BEGIN
			--Insert Header Sales Records
			INSERT INTO @Tbl_F
			(
				[Rec]
			)
			VALUES
			(
				'D' + ',' +
				@Transaction_Number + ',' +
				@Product_Code + ',' +
				@Quantity + ',' + 
				@Transaction_Type + ',' +
				@Transaction_Date + ',' +
				@Transaction_Time + ',' +				
				@Product_Description + ','
			)
		END			
				
		FETCH NEXT FROM Get_Data INTO 
			@Transaction_Type,	@Transaction_Number, @Transaction_Date, @Transaction_Time,
			@Rep_ID, @Rep_Name, @Product_Code, @Product_Description, @Quantity	
	END	
	CLOSE Get_Data
	Deallocate Get_Data

	SELECT [Rec] FROM @Tbl_F

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW_SEL
--Purpose       :Select Sales Submission Data For Rewards
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '	WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '   
	SET @sql = @sql + '	ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '	END '
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '		ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
	SET @sql = @sql + '	LEFT OUTER JOIN Lup_AS_Reps r '
	SET @sql = @sql + '		ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export	
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AS_Cash_Up
--Purpose       :SELECT Cashiers & Tills to be Cashed Up
--              :UPDATE AS_Transactions.Cashed_Up
--              :for ACTIVE Cash Ups except EFTPOS
--              :(NB: SURPLUS/DEFICIT is done in sp_AS_Cash_Up_Post)
--Tables        :AS_Cash_Ups
--Parameters    :
--Date          :2002/01/29
--Authors       :TB
--Version       :1.0.0
--MODS          :23/07/02 - ** Default to Cashier #1 for NULL cashiers - FIX POS **
--              :26/07/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :                released in RC4b
--              :03/08/02 - Created NEW Cash Up PICKLIST rs for Cashiers & Tills
--              :06/08/02 - For Cashiers/Tills list on 'Balance Cash Up' tab
--              :           Select ONLY Cashiers with PAYMENTS (TranType = 7)
--              :28/08/02 - Select ONLY Cashiers with PAYMENTS previously omitted
--              :           Sys_AW_Transaction_Types_ID = 7
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Cash_Up
	(
		@Choice int,
		@CompanyID int,
		@CashierID int = 0,
		@TillID int = 0,
		@Date DateTime = NULL
	)
AS

SET NOCOUNT ON

	DECLARE @GetDate DateTime

--> 0 - Get Cashiers TO BE CASHED UP DBC list
-->     (NB: Set Cashed_Up flag for ALL Cashiers with TRANSACTIONS)
	IF @Choice = 0
		SELECT  u.AW_Users_ID as [ID],
                ISNULL(u.Surname, '') + 
                ISNULL(', ' + u.FirstName, '') as [Description]
		FROM AW_Users u 
			INNER JOIN (SELECT DISTINCT Lup_AS_Cashiers_ID
                        FROM AS_Transactions 
						WHERE Cashed_Up IS NULL AND 
							  AW_User_Companies_ID = @CompanyID) t 
			    ON u.AW_Users_ID = t.Lup_AS_Cashiers_ID

--> 1 - Get Tills TO BE CASHED UP DBC list
-->     (NB: Set Cashed_Up flag for ALL Tills with TRANSACTIONS)
	ELSE
	IF @Choice = 1
		SELECT till.Lup_AS_Tills_ID as ID, till.Description 
		FROM Lup_AS_Tills till 
			INNER JOIN (SELECT DISTINCT Lup_AS_Tills_ID
                        FROM AS_Transactions 
					   	WHERE Cashed_Up IS NULL AND
						      AW_User_Companies_ID = @CompanyID) t 
			    ON till.Lup_AS_Tills_ID = t.Lup_AS_Tills_ID

--> 2 - Get Cashiers TO BE BALANCED DBC list
-->     (NB: Select ONLY Cashiers with PAYMENTS (Sys_AW_Transaction_Types_ID = 7))
	ELSE
	IF @Choice = 2
		SELECT  u.AW_Users_ID as [ID],
                ISNULL(u.Surname, '') +
                ISNULL(', ' + u.FirstName, '') as [Description]
		FROM AW_Users u 
			INNER JOIN (SELECT DISTINCT st.Lup_AS_Cashiers_ID
						FROM AS_Transactions st 
							LEFT JOIN AS_Cash_Ups cu
                                ON st.Lup_AS_Cashiers_ID = cu.Cashier_ID AND
                                   st.Cashed_Up = cu.Cashed_Up
						WHERE st.Cashed_Up IS NOT NULL AND
--28/08/02----------------------------------------------------------
                              st.Sys_AW_Transaction_Types_ID = 7 AND
--------------------------------------------------------------------
                              cu.Cashier_ID IS NULL) t
			ON u.AW_Users_ID = t.Lup_AS_Cashiers_ID


--> 3 - Get Tills TO BE BALANCED DBC list (ONLY Tills with PAYMENTS)
-->     (NB: Select ONLY Tills with PAYMENTS (Sys_AW_Transaction_Types_ID = 7))
	ELSE
	IF @Choice = 3
		SELECT till.Lup_AS_Tills_ID as [ID],
               till.[Description] as [Description]
    	FROM Lup_AS_Tills till
			INNER JOIN (SELECT DISTINCT st.Lup_AS_Tills_ID
						FROM AS_Transactions st 
							LEFT JOIN AS_Cash_Ups cu
                                ON st.Lup_AS_Tills_ID = cu.Lup_AS_Tills_ID AND
                                   st.Cashed_Up = cu.Cashed_Up
						WHERE st.Cashed_Up IS NOT NULL AND
                              st.Sys_AW_Transaction_Types_ID = 7 AND
                             (cu.Lup_AS_Tills_ID IS NOT NULL OR
                              cu.Lup_AS_Tills_ID <> 0)) t 
			    ON till.Lup_AS_Tills_ID = t.Lup_AS_Tills_ID

--> 4 - CashUp List
	ELSE
	IF @Choice = 4
		BEGIN
			IF @CashierID = 0 AND @TillID = 0
				SELECT DISTINCT Cashed_Up
				FROM AS_Transactions
				WHERE NOT Cashed_Up IS NULL AND
					  NOT Cashed_Up IN (SELECT Cashed_Up 
										FROM AS_Cash_Ups)
				ORDER BY Cashed_Up DESC
			ELSE
			IF @CashierID <> 0 AND @TillID = 0
				SELECT DISTINCT Cashed_Up
				FROM AS_Transactions
				WHERE NOT Cashed_Up IS NULL AND
					  Lup_AS_Cashiers_ID = @CashierID AND
					  NOT Cashed_Up IN (SELECT Cashed_Up 
										FROM AS_Cash_Ups 
										WHERE  Cashier_ID = @CashierID)
				ORDER BY Cashed_Up DESC
			ELSE
			IF @CashierID = 0 AND @TillID <> 0
				SELECT DISTINCT Cashed_Up
				FROM AS_Transactions
				WHERE NOT Cashed_Up IS NULL AND
					  Lup_AS_Tills_ID = @TillID AND
					  NOT Cashed_Up IN (SELECT Cashed_Up 
										FROM AS_Cash_Ups 
										WHERE Lup_AS_Tills_ID = @TillID)
				ORDER BY Cashed_Up DESC
            ELSE
			IF @CashierID <> 0 AND @TillID <> 0 
				SELECT DISTINCT Cashed_Up
				FROM AS_Transactions
				WHERE NOT Cashed_Up IS NULL AND
					  NOT Cashed_Up IN (SELECT Cashed_Up 
										FROM AS_Cash_Ups 
										WHERE Lup_AS_Tills_ID = @TillID AND
                                              Cashier_ID = @CashierID)
				ORDER BY Cashed_Up DESC

		END

--> 5 - Fetch the Payment Methods
	ELSE
	IF @Choice = 5
		SELECT Sys_AW_Payment_Methods_ID as [ID],
              [Description]
		FROM Sys_AW_Payment_Methods
		WHERE Sys_AW_Payment_Methods_ID <> 1 AND    -- <None>
              Sys_AW_Payment_Methods_ID <> 7 AND    -- Account
              Sys_AW_Payment_Methods_ID <> 10       -- COD    (S/B Voucher)
        -- Could use the Description to select rather than ID

--> 6 - DO CASH UP (Update AS_Transactions.Cashed_Up)
	ELSE
	IF @Choice = 6
		BEGIN
			SET @GetDate = GetDate()

			IF @CashierID = 0 AND @TillID = 0     --Cash Up ALL
				UPDATE AS_Transactions SET Cashed_Up = @GetDate
				WHERE Cashed_Up IS NULL
			ELSE
			IF @CashierID <> 0 AND @TillID = 0    --Cash Up by Cashier
				UPDATE AS_Transactions SET Cashed_Up = @GetDate
				WHERE Cashed_Up IS NULL AND
                      Lup_AS_Cashiers_ID = @CashierID
			ELSE
			IF @CashierID = 0 and @TillID <> 0    --Cash Up by Till
				UPDATE AS_Transactions SET Cashed_Up = @GetDate
				WHERE Cashed_Up IS NULL AND
                      Lup_AS_Tills_ID = @TillID
		END

--> 7 - GL Post (Update AS_Transactions)
	ELSE
	IF @Choice = 7
		BEGIN
			--This is where the GL <Post> happens
			Select 1


		END

--> 8 - Get the INVOICES Total of the selected Cashier
	ELSE
	IF @Choice = 8
		SELECT SUM(t.Total_Amount) as Amount
		FROM AS_Transactions t
		WHERE t.AW_User_Companies_ID = @CompanyID AND
			  DATEDIFF(n, t.Cashed_Up, @Date) = 0 AND 
   		      Sys_AW_Transaction_Types_ID = 3 AND        -- Invoices 
			  t.Lup_AS_Cashiers_ID = @CashierID

--> 9 - Get the INVOICES, REFUNDS & PAYMENTS (Net Movement) Total of the selected Cashier
	ELSE
	IF @Choice = 9
		SELECT SUM(t.Total_Amount) as [Amount]
		FROM AS_Transactions t
		WHERE t.AW_User_Companies_ID = @CompanyID AND
			  DATEDIFF(n, t.Cashed_Up, @Date) = 0 AND 
			 (Sys_AW_Transaction_Types_ID = 3 OR         -- Invoices 
			  Sys_AW_Transaction_Types_ID = 4 OR         -- Refunds
			  Sys_AW_Transaction_Types_ID = 7) AND       -- Payments
			  t.Lup_AS_Cashiers_ID = @CashierID

--> 10 - Get the Coinage denominations
	ELSE
	IF @Choice = 10
		SELECT Slu_AS_Coinage_ID as [ID],
               [Description] as [Unit]
        FROM Slu_AS_Coinage

--> 11 - Get the INVOICES Tax Total of the selected Cashier
	ELSE
	IF @Choice = 11
		SELECT SUM(t.Total_Tax_Amount) as [Tax]
		FROM AS_Transactions t
		WHERE t.AW_User_Companies_ID = @CompanyID AND
              DATEDIFF(n, t.Cashed_Up, @Date) = 0 AND 
			 (Sys_AW_Transaction_Types_ID = 3) AND       -- Tax on Invoices
			  t.Lup_AS_Cashiers_ID = @CashierID

--> 12 - Get the REFUNDS Total of the selected Cashier
	ELSE
	IF @Choice = 12
			SELECT SUM(t.Total_Amount) as [Amount]
		FROM AS_Transactions t
		WHERE t.AW_User_Companies_ID = @CompanyID AND
			  DATEDIFF(n, t.Cashed_Up, @Date) = 0 AND 
			 (Sys_AW_Transaction_Types_ID = 4) AND       -- Refunds
			  t.Lup_AS_Cashiers_ID = @CashierID

--> 13 - Get the REFUNDS Tax Total of the selected Cashier
	ELSE
	IF @Choice = 13
		SELECT SUM(t.Total_Tax_Amount) as [Tax]
		FROM AS_Transactions t
		WHERE t.AW_User_Companies_ID = @CompanyID AND
			  DATEDIFF(n, t.Cashed_Up, @Date) = 0 AND 
			 (Sys_AW_Transaction_Types_ID = 4) AND       -- Tax on Refunds
			  t.Lup_AS_Cashiers_ID = @CashierID

--> 14 - Get the PAYMENTS Total of the selected Cashier
	ELSE
	IF @Choice = 14
		SELECT SUM(t.Total_Amount) as [Amount]
		FROM AS_Transactions t
		WHERE t.AW_User_Companies_ID = @CompanyID AND
			  DATEDIFF(n, t.Cashed_Up, @Date) = 0 AND 
			 (Sys_AW_Transaction_Types_ID = 7) AND       -- Payments
			  t.Lup_AS_Cashiers_ID = @CashierID

--> 14 - PICKLIST rs (CASHIERS NOT YET CASHED UP)
	ELSE
	IF @Choice = 15
		SELECT DISTINCT t.Lup_AS_Cashiers_ID AS [ID],
                        ISNULL(u.Surname, '') + 
                        ISNULL(', ' + u.FirstName, '') AS [Cashier],
                        t.Cashed_Up AS [Cash Up Date]
			FROM AS_Transactions t
                INNER JOIN AW_Users u
			        ON u.AW_Users_ID = t.Lup_AS_Cashiers_ID
			WHERE NOT t.Cashed_Up IS NULL AND
--28/08/02----------------------------------------------------------
                  t.Sys_AW_Transaction_Types_ID = 7 AND
--------------------------------------------------------------------
				  NOT EXISTS (SELECT DISTINCT c.Cashier_ID, c.Cashed_Up 
                              FROM AS_Cash_Ups c 
                              WHERE c.Cashier_ID = t.Lup_AS_Cashiers_ID AND
                                    c.Cashed_Up = t.Cashed_Up)

--> 14 - PICKLIST rs (TILLS NOT YET CASHED UP)
	ELSE
	IF @Choice = 16
		SELECT DISTINCT t.Lup_AS_Tills_ID AS [ID],
                        ISNULL(till.[Description], '') AS [Till],
                        t.Cashed_Up AS [Cash Up Date]
			FROM AS_Transactions t
                INNER JOIN Lup_AS_Tills till
			        ON till.Lup_AS_Tills_ID = t.Lup_AS_Tills_ID
			WHERE NOT t.Cashed_Up IS NULL AND
--28/08/02----------------------------------------------------------
                  t.Sys_AW_Transaction_Types_ID = 7 AND
--------------------------------------------------------------------
				  NOT EXISTS (SELECT DISTINCT c.Lup_AS_Tills_ID, c.Cashed_Up 
                              FROM AS_Cash_Ups c 
                              WHERE c.Lup_AS_Tills_ID = t.Lup_AS_Tills_ID AND
                                    c.Cashed_Up = t.Cashed_Up)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





-------------------------------------------------------------------------------
--Description   :sp_AS_Cash_Up_Cashiers
--Purpose       :SELECT Cashiers to be Cashed Up
--Date          :2002/01/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Cash_Up_Cashiers
	(
		@Choice int,
		@CompanyID int,
		@CashierID int = 0,
		@Date DateTime = NULL
	)
AS

SET NOCOUNT ON

	DECLARE @GetDate DateTime

--> Get Cashiers to be Cashed Up
	IF @Choice = 1
        BEGIN
            SELECT MAX(t.Lup_AS_Cashiers_ID) AS [ID],
                   MAX(ISNULL(u.Surname, '') + ISNULL(', ' + u.FirstName, '')) as [Description],
                   SUM(t.Total_Amount) AS [Cash]
            FROM AS_Transactions t
                INNER JOIN AW_Users u
                    ON t.Lup_AS_Cashiers_ID = u.AW_Users_ID
            WHERE AW_User_Companies_ID = 1 AND
                  Cashed_Up IS NULL AND 
                  Sys_AW_Transaction_Types_ID = 7
            GROUP BY t.Lup_AS_Cashiers_ID
            HAVING SUM(t.Total_Amount) <> 0
        END

--> Cash-Up List
	ELSE
	IF @Choice = 2
		BEGIN
			IF @CashierID <> 0
				SELECT DISTINCT Cashed_Up
				FROM AS_Transactions
				WHERE Cashed_Up IS NOT NULL AND
					  Lup_AS_Cashiers_ID = @CashierID AND
					  Cashed_Up NOT IN (SELECT Cashed_Up 
										FROM AS_Cash_Ups 
										WHERE  Cashier_ID = @CashierID)
				ORDER BY Cashed_Up DESC
        END

--> Picklist rs (Cashiers not yet cashed up)
	ELSE
	IF @Choice = 3
        BEGIN
            SELECT MAX(t.Lup_AS_Cashiers_ID) AS [ID],
                   MAX(ISNULL(u.Surname, '') + ISNULL(', ' + u.FirstName, '')) as [Description],
                   MAX(t.Cashed_Up) AS [Cash Up Date],
                   SUM(t.Total_Amount) AS [Cash]
			FROM AS_Transactions t
                INNER JOIN AW_Users u
			        ON u.AW_Users_ID = t.Lup_AS_Cashiers_ID
			WHERE NOT t.Cashed_Up IS NULL AND
                  t.Sys_AW_Transaction_Types_ID = 7 AND
				  NOT EXISTS (SELECT DISTINCT c.Cashier_ID, c.Cashed_Up 
                              FROM AS_Cash_Ups c 
                              WHERE c.Cashier_ID = t.Lup_AS_Cashiers_ID AND
                                    c.Cashed_Up = t.Cashed_Up)
            GROUP BY t.Lup_AS_Cashiers_ID, t.Cashed_Up
            HAVING SUM(t.Total_Amount) <> 0
            ORDER BY t.Lup_AS_Cashiers_ID, t.Cashed_Up
        END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   : sp_AS_Cash_Up_Insert
--Purpose       : Inserts Cash Up Breakdown and Coinage Transaction Splits
--              : into sp_AS_Cash_Up. From 'Balance Cash Up' Tab
--Functionality : Tables: AS_Cash_Ups
--Date          : 2002/01/30
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE     PROCEDURE sp_AS_Cash_Up_Insert
    (
    	@CashierID int,
    	@TillID int,
    	@MethodID int,
    	@CoinageID int,
    	@Amount money,
    	@CashedUp smalldatetime,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	INSERT INTO AS_Cash_Ups
    	(	
    		Cashier_ID,
    		Lup_AS_Tills_ID,
    		Sys_AW_Payment_Methods_ID,
    		Slu_AS_Coinage_ID,
    		Amount,
    		Cashed_Up,
    		Slu_AW_Active_ID,
    		AW_User_Companies_ID
    	)
	VALUES
    	(
    		@CashierID,
    		@TillID,
    		@MethodID,
    		@CoinageID,
    		@Amount,
    		@CashedUp,
    		1,
    		@CompanyID
    	)

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_Cash_Up_Post
--Purpose       :Inserts  Normal Journal and GL Transactions
--              :    for Cash Up SURPLUS/DEFICIT from 'Balance Cash Up' Tab
--              :GL Transaction Ref no's:
--              :Sales: Cash Shortages & Overs = 99, Cash Control = 99
--Tables        :AB_Accounts, AB_Control_Accounts
--Date          :2002/02/06
--Authors       :TB
--MODS          :19/07/02 - Modified GL TranTypeID
--              :                from 23 (Accounts Receivable - Interest)
--              :                to 27 (Cash-Up)
--              :02/08/02 - Changed POS to insert UserID rather than CashierID
--              :                & modified GL Narration to reflect UserName
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           input parameters
--2004.4.0      :31/07/07 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Cash_Up_Post
    (
        @SurplusDeficit money,
        @CashierID int,
        @TillID int,
        @Month int,
        @Year int,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @GLAccountID int,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
	        @Date DateTime,
            @Cashier varchar(30),
            @Till varchar(30),
            @NettInvoice money,
            @NettRefund money,
            @Overage varchar(10),
            @CashierName varchar(30)

    --Per Cashier/Till - Total Surplus/Deficit
    IF @SurplusDeficit <> 0

    	SET @Date = GetDate()

--         SELECT @Cashier = [Description]
--         FROM Lup_AS_Cashiers
--         WHERE Lup_AS_Cashiers_ID = @CashierID

    --> Changed POS to insert UserID rather than CashierID
		SELECT @Cashier = ISNULL(Surname, '') + ISNULL(', ' + FirstName, '')
		FROM AW_Users
        WHERE AW_Users_ID = @CashierID
    
        SELECT @Till = ISNULL([Description], '')
        FROM Lup_AS_Tills
        WHERE Lup_AS_Tills_ID = @TillID

        IF @SurplusDeficit > 0
            SET @Overage = 'Deficit '
        ELSE
            SET @Overage = 'Surplus '

        IF @CashierID <> 0
            SET @CashierName = LEFT(ISNULL(@Cashier, ''), 30)
        ELSE
            SET @CashierName = LEFT(ISNULL(@Till, ''), 30)

        SET @Narration = 'Cash Up ' + @Overage + @CashierName

        BEGIN
            SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
        	BEGIN TRANSACTION
    
                BEGIN

                --> Create NORMAL JOURNAL header for the Cash Surplus/Deficit
     				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                             15,
                                             @CompanyID
    
    				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @Date,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
    				
    				SELECT @GLAccountID = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 202    --Cash Shortages/Overs
    				
                    --NB Surplus = negative amount, Deficit = positive amount
                    
                --> Create JOURNAL DETAIL for Cash Shortages/Overs
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAccountID,
                            @SurplusDeficit,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            0

                --> Create GL TRANSACTION for Cash Shortages/Overs
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            27,
                            @GLAccountID,
                            @Date,
                            '202 Cash Shortages',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @SurplusDeficit,
                            @UserID,
                            @CompanyID

    				SELECT @GLAccountID = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 206    --Cash Control Account
    
    				SET @SurplusDeficit = -@SurplusDeficit
    
                --> Create JOURNAL DETAIL for Cash Control Account  
    				EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAccountID,
                            @SurplusDeficit,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            0

                --> Create GL TRANSACTION for Cash Control Account  
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            27,
                            @GLAccountID,
                            @Date,
                            '206 Cash Control',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @SurplusDeficit,
                            @UserID,
                            @CompanyID

    			END

        	COMMIT TRANSACTION
        
        END

SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE PROCEDURE sp_AS_Cash_Up_Select
	(
		@StartDate DateTime,	
		@EndDate DateTime,
		@CashierID int,
		@TillID int,
		@RepID int
	)
AS
	DECLARE @Criteria varchar(4000)
	SET @Criteria = ''

	Print @StartDate
	Print @EndDate

	IF NOT @StartDate IS NULL
		SET @Criteria = ' DateDiff(d, ' + '''' + convert(varchar(20), @StartDate,111) + '''' + ' , tCashedUp) >= 0 '
	
	IF NOT @EndDate IS NULL
		BEGIN
			IF NOT @Criteria = '' 
				SET @Criteria = @Criteria + ' AND ' + ' Datediff(d,' + '''' + convert(varchar(20),@EndDate,111) + '''' +  ' , tCashedUp) <= 0 '
			ELSE
				 SET @Criteria =  ' Datediff(d,' + '''' + convert(varchar(20),@EndDate,111) + '''' +  ' , tCashedUp) <= 0 '
		END

	IF NOT (@CashierID IS NULL OR @CashierID = 0)
		BEGIN
			IF NOT @Criteria = '' 
				SET @Criteria = @Criteria + ' AND tCashierID = ' + convert(varchar(10),@CashierID) 
			ELSE
				SET @Criteria = ' tCashierID = ' + convert(varchar(10),@CashierID) 
		END

	IF NOT (@TillID IS NULL OR @TillID = 0)
		BEGIN
			IF NOT @Criteria = '' 
				SET @Criteria = @Criteria + ' AND tTillID = ' + convert(varchar(10),@TillID) 
			ELSE
				SET @Criteria = ' tTillID = ' + convert(varchar(10),@TillID) 
		END

	IF NOT (@RepID IS NULL OR @RepID = 0)
		BEGIN
			IF NOT @Criteria = '' 
				SET @Criteria = @Criteria + ' AND tRepID = ' + convert(varchar(10),@RepID) 
			ELSE
				SET @Criteria = ' tRepID = ' + convert(varchar(10),@RepID) 
		END




	IF NOT @Criteria = ''
		SET @Criteria = ' WHERE ' + @Criteria

	PRINT @Criteria

	EXEC ('SELECT * FROM vw_RPT_AS_Transactions_Transaction_Details  ' + @Criteria)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AS_Cashup_Up_Lookups_Select
--Purpose       :Cash-Up Report lookups 
--Date          :2003/11/22
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Cashup_Up_Lookups_Select
	(
		@CompanyID int, 
		@Choice smallint
	)

AS
	IF @Choice = 0 --Cashier
-- 		SELECT UserID as ID, FullName as Description 
-- 		FROM vw_AS_Users_Roles
-- 		WHERE CompanyID = @CompanyID AND
-- 			RoleID = 4
-- 		UNION
-- 		SELECT 0, '<All>'

		SELECT AW_Users_ID as [ID],
               ISNULL(Surname, '') + ISNULL(', ' + FirstName, '') AS [Description] 
		FROM AW_Users
		WHERE AW_Users_ID > 0 AND
              IsCashier = 1
		UNION
		SELECT 0, '<All>'

	ELSE
	IF @Choice = 1 --Till
		SELECT Lup_AS_Tills_ID as ID, Description 
		FROM Lup_AS_Tills 
		WHERE AW_User_Companies_ID = @CompanyID
		UNION
		SELECT 0, '<All>'
	ELSE
	IF @Choice = 2	--Rep
		SELECT Lup_AS_Reps_ID as ID, Description 
		FROM Lup_AS_Reps 
		WHERE AW_User_Companies_ID = @CompanyID
		UNION
		SELECT 0, '<All>'






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_Daily_GRV_VMI
--Purpose       :GY LOYALTY GRV RECEIPTS data file – GRV for last ROLLING month
--Date          :2005/05/19
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Daily_GRV_VMI
    (
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @IgnoreNonStock tinyint,
        @IgnoreNegativeStock tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @FranchiseNo varchar(20)


-- SET @DayEndFromDate = '2005/04/15 06:47:00 AM'
-- SET @DayEndToDate = '2005/04/15 06:47:00 AM'
-- SET @IgnoreNonStock = 1
-- SET @IgnoreNegativeStock = 1
-- SET @CompanyID = 1


    SELECT @FranchiseNo = RTRIM(LTRIM(ISNULL(Network_Identity_Number, '')))
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    SELECT
        '' AS [TT Key],
        ISNULL(h.Delivery_Note_Number, '') AS [Invoice No],
        ISNULL(h.AO_Suppliers_ID, 0) AS [Supplier ID],
        LEFT(ISNULL(m.Old_Code, ''), 3) AS [Brand],
        REPLACE(CONVERT(CHAR(10), h.Date_Received, 121), '-', '') AS [Date],
        REPLACE(CONVERT(CHAR(10), h.Date_Received, 108), '-', '') AS [Time],
        @FranchiseNo AS [Branch No],
        ISNULL(p.Product_Code, '') AS [Product Code],
        CONVERT(int, ISNULL(d.Qty, 0)) AS [Qty],
        LEFT(ISNULL(p.Manufacturer_Code, ''), 10) AS [Manuf. Code]

    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 AO_Suppliers s
             ON s.AO_Suppliers_ID = h.AO_Suppliers_ID
         LEFT JOIN Lup_AP_Product_Manufacturers m
             ON m.Lup_AP_Product_Manufacturers_ID = p.Lup_AP_Product_Manufacturers_ID
    
    WHERE d.AW_User_Companies_ID = @CompanyID AND
          h.Date_Received >= DATEADD(m, -1, @DayEndToDate) AND
          h.Sys_AW_Transaction_Types_ID = 19
    ORDER BY h.Date_Received, [Product Code]

        











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AS_Daily_Sales_Loyalty
--Purpose       :GY LOYALTY SALES data file – DAILY SALES at end of business
--Functionality :Uses TABLE datatype
--Date          :2005/05/19
--Authors       :TB
--MODS:         :
--2004.3.4      :16/02/07 - Append Daily Stock to Daily Sales Loyalty export - K.S.
--2004.3.7      :19/07/07 - Added Product Description (new spec) field as [Description]
--              :19/07/07 - Added CASE to insert Product Code if Manuf Code IS empty
--              :18/07/07 - Reworked using TABLE DATATYPE to seperate Sales and Stock
--              :           and MERGE Sales with Stock NOT IN Sales - K Slabbert
--2004.3.8      :22/03/08 - Append STOCK ON HAND if ONE DayEnd is selected - K Slabbert
--2004.4.0      :19/07/08 - Append STOCK ON HAND if ONE or RANGE of Day-Ends is selected
--              :           and the ending Day-End date in the selection is the LATEST Day-End
--              :           K Slabbert - 18 JUL 2008
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AS_Daily_Sales_Loyalty
    (
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @IgnoreNonStock tinyint,
        @IgnoreNegativeStock tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @FranchiseNo varchar(20),
            @sql varchar(8000),
            @Today varchar(10),
            @FromDate varchar(10),
            @ToDate varchar(10),
            @LastDayEndDate datetime


-- SET @DayEndFromDate = '2007/06/11 17:06:00'
-- SET @DayEndToDate = '2007/06/11 17:06:00'
-- SET @IgnoreNonStock = 1
-- SET @IgnoreNegativeStock = 1
-- SET @CompanyID = 1


    SELECT TOP 1 @LastDayEndDate = Day_End
    FROM AS_Day_Ends
    ORDER BY Day_End DESC


    SELECT @FromDate = LEFT(REPLACE(CONVERT(varchar(30), @DayEndFromDate, 121), '-', ''), 8)
    SELECT @ToDate = LEFT(REPLACE(CONVERT(varchar(30), @DayEndToDate, 121), '-', ''), 8)
    SELECT @Today = LEFT(REPLACE(CONVERT(varchar(30), getdate(), 121), '-', ''), 8)


    SELECT @FranchiseNo = RTRIM(LTRIM(ISNULL(Network_Identity_Number, '')))
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


	SET @sql = ' DECLARE @Sales table '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     [Branch No] varchar(20), '
    SET @sql = @sql + '     [Date] varchar(10), '
    SET @sql = @sql + '     [Product Code] varchar(20), '
    SET @sql = @sql + '     [Manuf. Code] varchar(20), '
    SET @sql = @sql + '     [Brand] varchar(3), '
    SET @sql = @sql + '     [Qty] int, '
    SET @sql = @sql + '     [On Hand] int, '
    SET @sql = @sql + '     [Dealer List] int, '
    SET @sql = @sql + '     [Avg. Selling] int, '
    SET @sql = @sql + '     [Cost] int, '
    SET @sql = @sql + '     [Description] varchar(50) '
    SET @sql = @sql + ' ) '



	SET @sql = @sql + ' DECLARE @Stock table '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     [Branch No] varchar(20), '
    SET @sql = @sql + '     [Date] varchar(10), '
    SET @sql = @sql + '     [Product Code] varchar(20), '
    SET @sql = @sql + '     [Manuf. Code] varchar(20), '
    SET @sql = @sql + '     [Brand] varchar(3), '
    SET @sql = @sql + '     [Qty] int, '
    SET @sql = @sql + '     [On Hand] int, '
    SET @sql = @sql + '     [Dealer List] int, '
    SET @sql = @sql + '     [Avg. Selling] int, '
    SET @sql = @sql + '     [Cost] int, '
    SET @sql = @sql + '     [Description] varchar(50) '
    SET @sql = @sql + ' ) '


    --------------------------------------------------------------------------------------------
    SET @sql = @sql + ' INSERT INTO @Sales '


    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + ' MAX(''' + CONVERT(varchar(20), @FranchiseNo) + '''), '
    SET @sql = @sql + ' MAX(REPLACE(CONVERT(CHAR(10), h.Transaction_Date, 121), ''-'', '''')), '
    SET @sql = @sql + ' LEFT(ISNULL(p.Product_Code, ''''), 10), '

    SET @sql = @sql + ' MAX(CASE WHEN ISNULL(p.Manufacturer_Code, '''') = '''' '
    SET @sql = @sql + '     THEN LEFT(ISNULL(p.Product_Code, ''''), 10) '
    SET @sql = @sql + '     ELSE LEFT(ISNULL(p.Manufacturer_Code, ''''), 10) '
    SET @sql = @sql + '     END), '

    SET @sql = @sql + ' MAX(LEFT(ISNULL(m.Old_Code, ''''), 3)), '
    SET @sql = @sql + ' CONVERT(int, SUM(d.Quantity), 0), '
    SET @sql = @sql + ' MAX(CONVERT(int, ISNULL(p.On_Hand, 0))), '
    SET @sql = @sql + ' MAX(CONVERT(int, ISNULL(d.Original_Price, 0))), '
    SET @sql = @sql + ' CASE WHEN CONVERT(int, SUM(d.Quantity)) <> 0 ' +
                      ' THEN CONVERT(int, SUM(d.Unit_Price * d.Quantity)) / CONVERT(int, SUM(d.Quantity)) ' +
                      ' ELSE 0 ' +
                      ' END, '
    SET @sql = @sql + ' MAX(CONVERT(int, ISNULL(p.Last_Cost, 0))), '
    SET @sql = @sql + ' MAX(ISNULL(p.Description, '''')) '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + ' INNER JOIN AS_Transactions h '
    SET @sql = @sql + '     ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + ' INNER JOIN AP_Products p '
    SET @sql = @sql + '     ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '     ON m.Lup_AP_Product_Manufacturers_ID = p.Lup_AP_Product_Manufacturers_ID '

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '  (h.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' AND '
    SET @sql = @sql + '   h.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ') AND '
    SET @sql = @sql + '  (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   h.Sys_AW_Transaction_Types_ID = 4) '


    IF @IgnoreNonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END

    IF @IgnoreNegativeStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.On_Hand >= 0 '
        END


    SET @sql = @sql + ' GROUP BY p.Product_Code '
    --------------------------------------------------------------------------------------------


    --------------------------------------------------------------------------------------------
    SET @sql = @sql + ' INSERT INTO @Stock '


    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + ' ''' + CONVERT(varchar(20), @FranchiseNo) + ''' AS [Branch No], '
    SET @sql = @sql + ' ''' + CONVERT(CHAR(10), @Today) + ''' AS [Date], '
    SET @sql = @sql + ' LEFT(ISNULL(p.Product_Code, ''''), 10) AS [Product Code], '

    SET @sql = @sql + ' CASE WHEN ISNULL(p.Manufacturer_Code, '''') = '''' '
    SET @sql = @sql + '      THEN LEFT(ISNULL(p.Product_Code, ''''), 10) '
    SET @sql = @sql + '      ELSE LEFT(ISNULL(p.Manufacturer_Code, ''''), 10) '
    SET @sql = @sql + '      END AS [Manuf. Code], '

    SET @sql = @sql + ' LEFT(ISNULL(m.Old_Code, ''''), 3) AS [Brand], '
    SET @sql = @sql + ' 0 AS [Qty], '
    SET @sql = @sql + ' CONVERT(int, ISNULL(p.On_Hand, 0)) AS [On Hand], '
    SET @sql = @sql + ' 0 AS [Dealer List], '
    SET @sql = @sql + ' 0 AS [Avg. Selling], '
    SET @sql = @sql + ' CONVERT(int, ISNULL(p.Last_Cost, 0)) AS [Cost], '
    SET @sql = @sql + ' ISNULL(p.Description, '''') AS [Description] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '     ON m.Lup_AP_Product_Manufacturers_ID = p.Lup_AP_Product_Manufacturers_ID '

    SET @sql = @sql + ' WHERE p.On_Hand <> 0 '


    IF @IgnoreNonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END

    IF @IgnoreNegativeStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.On_Hand >= 0 '
        END
    --------------------------------------------------------------------------------------------


    ---------------------------------------------
    SET @sql = @sql + ' SELECT * '
    SET @sql = @sql + ' FROM @Sales '
    ---------------------------------------------


    -------------------------------------------------------------------------------
    -- NEW 2004.3.8
    -- Append STOCK ON HAND if ONE DayEnd range is select and @DayEndToDate = TODAY
    -- K Slabbert - 19 MAR 2008
    -------------------------------------------------------------------------------
--    IF @FromDate = @ToDate

    -------------------------------------------------------------------------------
    -- NEW 2004.4.0
    -- Append STOCK ON HAND if ONE or RANGE of Day-Ends is selected
    --     and the ending Day-End date in the selection is the LATEST Day-End
    -- K Slabbert - 18 JUL 2008
    -------------------------------------------------------------------------------
    IF @DayEndToDate = @LastDayEndDate
        BEGIN
            SET @sql = @sql + ' UNION ALL '

            SET @sql = @sql + ' SELECT * '
            SET @sql = @sql + ' FROM @Stock '
            SET @sql = @sql + ' WHERE [Product Code] NOT IN ( SELECT [Product Code] FROM @Sales ) '
        END
    ---------------------------------------------


    SET @sql = @sql + ' ORDER BY [Date], [Product Code] '



    EXEC (@sql)
    ---------------------------------------------












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Daily_Stock_VMI
--Purpose       :GY LOYALTY SALES data file – DAILY SALES at end of business
--Date          :2005/05/19
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Daily_Stock_VMI
    (
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @IgnoreNonStock tinyint,
        @IgnoreNegativeStock tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @FranchiseNo varchar(20),
            @FranchiseName varchar(50),
            @sql varchar(8000)


-- SET @DayEndFromDate = '2005/04/15 06:47:00 AM'
-- SET @DayEndToDate = '2005/04/15 06:47:00 AM'
-- SET @IgnoreNonStock = 1
-- SET @IgnoreNegativeStock = 1
-- SET @CompanyID = 1


    SELECT @FranchiseNo = RTRIM(LTRIM(ISNULL(Network_Identity_Number, ''))),
           @FranchiseName = RTRIM(LTRIM(ISNULL(Company_Name, '')))
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    SET @sql = ' SELECT '

    SET @sql = @sql + '     MAX(''' + CONVERT(varchar(20), @FranchiseNo) + ''') AS [Branch No], '
    SET @sql = @sql + '     MAX(''' + CONVERT(varchar(20), @FranchiseName) + ''') AS [Branch Name], '
    SET @sql = @sql + '     ISNULL(p.Product_Code, '''') AS [Product Code], '
    SET @sql = @sql + '     MAX(ISNULL(p.Description, '''')) AS [Product Name], '
    SET @sql = @sql + '     MAX(LEFT(ISNULL(m.Old_Code, ''''), 3)) AS [Brand], '
    SET @sql = @sql + '     MAX(REPLACE(CONVERT(CHAR(10), h.Transaction_Date, 121), ''-'', '''')) AS [Date], '
    SET @sql = @sql + '     MAX(CONVERT(int, ISNULL(p.On_Hand, 0))) AS [On Hand], '
    SET @sql = @sql + '     0 AS [SIT Non-Supplier], '
    SET @sql = @sql + '     0 AS [SIT Inter-Branch], '
    SET @sql = @sql + '     0 AS [SIT Inter-Company], '
    SET @sql = @sql + '     MAX(LEFT(ISNULL(p.Manufacturer_Code, ''''), 10)) AS [Manuf. Code] '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON m.Lup_AP_Product_Manufacturers_ID = p.Lup_AP_Product_Manufacturers_ID '

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '      (p.On_Hand <> 0 OR '
    SET @sql = @sql + '       dbo.fn_AP_Product_Has_Movement_Period(d.AP_PRoducts_ID, ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ', 6) = 1 ) '


    IF @IgnoreNonStock = 1
        BEGIN
            SET @sql = @sql + '     AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END

--     IF @IgnoreNegativeStock = 1
--         BEGIN
--             SET @sql = @sql + '     AND p.On_Hand >= 0 '
--         END
--     ELSE
--         BEGIN
--             SET @sql = @sql + '     AND p.On_Hand <> 0 '
--         END


    SET @sql = @sql + '     GROUP BY p.Product_Code '
    SET @sql = @sql + '     ORDER BY [Date], [Product Code] '


    EXEC (@sql)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Day_End
--Purpose       :Daily Sales Day-End procedure
--              :Inserts GL Journal and GL Transactions to GL CONTROL ACCOUNTS:
--              :1. DEBTORS, SALES, & VAT CONTROL
--              :2. RECEIPTS to DEBTORS & CASH CONTROL
--              :3. INTEREST JOURNALS to DEBTORS & INTEREST RECEIVED - Removed 31/05/04
--              :4. SETTLEMENT DISCOUNT to DEBTORS & SETTLEMENT DISCOUNT ALLOWED
--              :    for the following AS_Transaction_Types:
--              :        3=Invoice, 4=Refund, 7=Receipt,
--              :        15=Interest Journal, 18=Settlement Discount
--              :
--              :Ignores 5=Customer Journals. This is updated in Customer Journals
--              :-------------------------------------------------------
--              :GL Transaction Ref no's: !! REDUNDANT 15/10/03 !!
--              :Sales:            Debtors = 90, Sales = 91, VAT = 92
--              :Cost Of Sales:    Cost Of Sales = 82, Inventory = 83
--              :Receipts:         Debtors = 93, Cash = 94
--              :Interest:         Debtors = 95, Interest Received = 96 - Removed 31/05/04
--              :Settlement:       Debtors = 97, Discount Allowed = 98
--              :-------------------------------------------------------
--Date          :2002/02/06
--Authors       :TB
--MODS          :07/07/02 - Inserted VAT on Settlement Discount transaction
--              :07/07/02 - Changed Sys_AB_Transaction_Types_ID for each TranType
--              :19/07/02 - Added RECEIPTS TranTypes 21 (Back Office Receipt) and
--              :           22 (EFT Receipt) and split RECEIPTS updates to GL
--              :28/09/02 - Removed @Date parameter passed in from UI and replaced
--              :           it with @DayEndDate (SERVER date) to eliminate DE's
--              :           on different computers with varying Realtime Clock
--              :21/12/02 - Modified @GLControlAccount def from smallint to int
--              :04/09/03 - Added to Post Day-End COST OF SALES to Inventory/C.O.S.
--              :           if chkGRVtoInventoryCOS parameter is vbChecked
--              :15/10/03 - Replaced ALL GL Transaction Ref no's number and apply
--              :           @NextGLTranID reference number to ALL GL Transactions
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :31/05/04 - Removed Customer Interest updated here in Day-End.
--              :           Customer Interest update was removed and put back into 
--              :           sp_AC_Customer_Journals_Insert_Update on 28/07/02 !!
--2004.2.4      :04/06/05 - Added filter @CompanyID in ALL WHERE clauses !!!!!!
--              :05/06/05 - Added fetch PICKLIST from NEW AS_Day_Ends table
--              :05/06/05 - Added INSERT NEW AS_Day_Ends table
--2004.2.7      :28/03/06 - Replaced GL TranType 24 (Accounts Receivable - Settlement)
--              :           with GL TranType 22 (Accounts Receivable - Journal)
--              :           for Settlement Discount portion of Day-End procedure
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.6      :08/08/09 - Added UPDATE DAY-END FLAG in NEW AS_Till_Payouts table
--2004.5.3      :09/08/11 - Added Day-End CUTOFF DATE using Transaction_Date and DELETE DAY-END
--2004.5.5      :10/11/11 - Added Set @RetVal = 1 in DO DAY-END when Day-End completed succesfully
--2004.5.7 RGL  :2012-10-22 - Split Levy product transactions to Sales and COS GL 
--                            accounts as setup on Products
--2004.6.2 RGL  :2015-07-02 - Added Consignment GL entries
--2004.6.2 RGL  :2015-08-07 - Added Call to sp_AS_Day_End_Summary. Writes to Day End Summary tables
--2004.6.2 RGL  :2015-08-07 - Changed @DayEndDate from DateTime to SmallDateTime
--2016.6.2 RGL	:2016-08-04	:Changed Settlement discount from 22 to 24 ABTranType - AP Settlement
--							 So that it shows in its own section on TAX report
-------------------------------------------------------------------------------
---- ToDo: ADD NEW CURSOR GROUP BY AP_Products.GL_COS_ID  (Cost-of-Sales GL Account)
--2004.2.5      :23/10/05 - Added to each Product Sales and C.O.S. GL Accounts using
--              :           System Options chkUseProductSalesGL and chkUseProductCOSGL
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_Day_End]
	(
		@Choice int,
		@CompanyID int,
		@Month tinyint,
		@Year int,
        @UserID int,
        @CutOffDate datetime
	)
AS
SET NOCOUNT ON

	DECLARE --@DayEndDate SmallDateTime, --DateTime, V6.2 Changed to match AS_Day_Ends and AS_Transactions Day_End field !!!Check
			@DayEndDate DateTime,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @DayEndCheck DateTime,
            @RetVal int,
            @SumAmount money,
            @SumTax money,
            @SumTotalAmount money,
            @SumTotalCost money,
            @GLControlAccount int,
            @SalesAmount money,
            @TaxAmount money,
            @Count int,
            @POSCount int,
            @BOFCount int,
            @EFTCount int,
            @InsertGLTran bit,
            @Settlement_Disc_Allowed_GL_ID int,
            @Settlement_Ex_VAT money,
            @Settlement_VAT money,
            @POSReceipts money,
            @BOFReceipts money,
            @EFTReceipts money,
            @TaxRate decimal(5,2),
            @GRInventoryCOS varchar(10),
            @PostGLSales varchar(10),
            @PostGLCOS varchar(10),

			@Levy_SumTax money,
			@Levy_SumTotalAmount money,
			@Levy_SumTotalCost money,
			@Levy_Count int,
			@NONLevy_SumTax money,
			@NONLevy_SumTotalAmount money,
			@NONLevy_SumTotalCost money,
			@NONLevy_Count int,
			@Levy_GRInventoryCOS_ID int,
            @Levy_PostGLSales_ID int,
            @Levy_PostGLCOS_ID int,
            @Levy_AP_Products_ID int,
            
			@SumConsignmentTax money,
            @SumConsignmentTotalAmount money,
            @SumConsignmentTotalCost money

	SET @DayEndDate = @CutOffDate    -- NEW 2004.5.3
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0            --0 = Do Not insert a GL Transaction in JNL Details
    SET @Count = 0
	SET @RetVal = 0
	SET @Levy_Count = 0
	SET @NONLevy_Count =0
	
	IF @Choice = 0    --Select list of PREVIOUS DAY-ENDS (PICKLIST)
	BEGIN
		SELECT AS_Day_Ends_ID AS [ID],
               Day_End,
               AB_Transaction_Ref AS [GL Tran Ref],
               AB_Transaction_Date AS [GLTranDate]
        FROM AS_Day_Ends
        WHERE AW_User_Companies_ID = @companyID
        ORDER BY Day_End DESC
	END

	ELSE
	IF @Choice = 1    --Do a NEW DAY-END
	BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		BEGIN TRANSACTION

    --> SALES--------------------------------------------------------------

            SET @SumTax = 0
            SET @SumTotalAmount = 0
            SET @SumTotalCost = 0
            SET @Count = 0
            SET @Levy_SumTax = 0
            SET @Levy_SumTotalAmount = 0
            SET @Levy_SumTotalCost = 0
            SET @Levy_Count = 0
            SET @NONLevy_SumTax = 0
            SET @NONLevy_SumTotalAmount = 0
            SET @NONLevy_SumTotalCost = 0
            SET @NONLevy_Count = 0

        --> Get SALES
			SELECT @SumTax = ISNULL(SUM(Total_Tax_Amount), 0),
                   @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                   @SumTotalCost = ISNULL(SUM(Total_Cost), 0),
                   @Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions
            WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  Day_End IS NULL
              AND Transaction_Date <= @CutOffDate

            SET @SumTax = ROUND(@SumTax, 2)
            SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)
            SET @SumTotalCost = ROUND(@SumTotalCost, 2)

        --> Get LEVY SALES
			SELECT @Levy_Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions t
			Inner Join AS_Transaction_Details d On
				t.AS_Transactions_ID = d.AS_Transactions_ID
			Inner Join AP_Products p On
			  	d.AP_Products_ID = p.AP_Products_ID
            WHERE t.AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  t.Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  t.Day_End IS NULL AND
				  t.Transaction_Date <= @CutOffDate AND
				  p.Slu_AW_YesNo_Levy_Item = 1


        --> Get NON LEVY SALES
--			IF @Levy_Count < 0
--			BEGIN
				SELECT 
					@NONLevy_SumTax = ISNULL(SUM(Tax_Amount), 0),
					@NONLevy_SumTotalAmount = ISNULL(SUM(Extended_Amount), 0),
					@NONLevy_SumTotalCost = Cast( SUM( ISNULL(d.Unit_Cost,0) * ISNULL(d.Quantity,0) ) As Money),
					@NONLevy_Count = ISNULL(COUNT(*), 0)
				FROM AS_Transactions t
				Inner Join AS_Transaction_Details d On
					t.AS_Transactions_ID = d.AS_Transactions_ID
				Inner Join AP_Products p On
			  		d.AP_Products_ID = p.AP_Products_ID
				WHERE t.AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
					 (t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
					  t.Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
					  t.Day_End IS NULL AND
					  t.Transaction_Date <= @CutOffDate AND
					  p.Slu_AW_YesNo_Levy_Item = 0

				SET @NONLevy_SumTax = ROUND(@NONLevy_SumTax, 2)
				SET @NONLevy_SumTotalAmount = ROUND(@NONLevy_SumTotalAmount, 2)
				SET @NONLevy_SumTotalCost = ROUND(@NONLevy_SumTotalCost, 2)
--			END

            IF @Count > 0 --If SALES transactions exist
            BEGIN

            --> Get 'Post GL SALES in Day-End to each Product's Sales GL Account' parameter
                SELECT @PostGLSales = RTRIM(LTRIM(Control_Value))
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkUseProductSalesGL' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID
				
				--If Levy transactions exist, then assign the NON Levy totals
				--to the normal variables and process as normaly
				IF @Levy_Count > 0
				BEGIN
					SET @SumTax = @NONLevy_SumTax
					SET @SumTotalAmount = @NONLevy_SumTotalAmount
					SET @SumTotalCost = @NONLevy_SumTotalCost             
				END				
				
				SET @Narration = 'Day End - Sales'

			--> Create NORMAL JOURNAL header for the Sales Journal
				IF @NextGLTranID = 0
				BEGIN

 					EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
							22,
							@CompanyID
    
					EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
							@DayEndDate,
							@NextGLTranID,
							@Narration,
							@Month,
							@Year,
							@UserID,
							@CompanyID

				END

			--> Update DEBTORS CONTROL
				SELECT @GLControlAccount = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 101    --Debtors Control

			--> Create JOURNAL DETAIL for Debtors Control
				EXEC sp_AB_Insert_Journal_Detail
						@JNLHeaderID,
						@GLControlAccount,
						@SumTotalAmount,
						@Narration,
						@UserID,
						@CompanyID,
						@InsertGLTran

			--> Create GL TRANSACTION for Debtors Control
				EXEC sp_AB_Insert_GL_Transactions
						@Narration,
						22,
						@GLControlAccount,
						@DayEndDate,
						'101 Debtors',
						@Month,
						@Year,
						@NextGLTranID,
						@SumTotalAmount,
						@UserID,
						@CompanyID

			--> Reverse signs to balance double entry
				SET @SalesAmount = (@SumTotalAmount - @SumTax) * -1
				SET @TaxAmount = @SumTax * -1

			--> Update SALES CONTROL
				SELECT @GLControlAccount = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 102    --Sales Control

			--> Create JOURNAL DETAIL for Sales Control
				EXEC sp_AB_Insert_Journal_Detail
						@JNLHeaderID,
						@GLControlAccount,
						@SalesAmount,
						@Narration,
						@UserID,
						@CompanyID,
						@InsertGLTran

			--> Create GL TRANSACTION for Sales Control
				EXEC sp_AB_Insert_GL_Transactions
						@Narration,
						22,
						@GLControlAccount,
						@DayEndDate,
						'102 Sales',
						@Month,
						@Year,
						@NextGLTranID,
						@SalesAmount,
						@UserID,
						@CompanyID

			--> UPDATE GL - VAT Control
				SELECT @GLControlAccount = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 401    --VAT Control

				SET @Narration = 'Day End - VAT on Sales'

			--> Create JOURNAL DETAIL for VAT Control
				EXEC sp_AB_Insert_Journal_Detail
						@JNLHeaderID,
						@GLControlAccount,
						@TaxAmount,
						@Narration,
						@UserID,
						@CompanyID,
						@InsertGLTran

			--> Create GL TRANSACTION for VAT Control
				EXEC sp_AB_Insert_GL_Transactions
						@Narration,
						22,
						@GLControlAccount,
						@DayEndDate,
						'401 VAT on Sales',
						@Month,
						@Year,
						@NextGLTranID,
						@TaxAmount,
						@UserID,
						@CompanyID

				SET @Count = 0

--> COST OF SALES -----------------------------------------------------

			--> Get parameter 'Post GL COST-OF-SALES in Day-End to each Product's Cost-of-Sales GL Account'
				SELECT @PostGLCOS = RTRIM(LTRIM(Control_Value))
				FROM Sys_AW_Options
				WHERE Control_Type = 'CheckBox' AND
					  Control_Name = 'chkUseProductCOSGL' AND
					  Control_Index = 0 AND
					  AW_User_Companies_ID = @CompanyID


			--> Get parameter 'Post directly to Inventory and Cost-of-Sales accounts  (Continous Inventory method)
				SELECT @GRInventoryCOS = RTRIM(LTRIM(Control_Value))
				FROM Sys_AW_Options
				WHERE Control_Type = 'CheckBox' AND
					  Control_Name = 'chkGRVtoInventoryCOS' AND
					  Control_Index = 0 AND
					  AW_User_Companies_ID = @CompanyID

				IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
				BEGIN

--------------------------------------------------------------------------------------------
-- ToDo: ADD NEW CURSOR GROUP BY AP_Products.GL_COS_ID  (Cost-of-Sales GL Account)
--------------------------------------------------------------------------------------------

					SET @Narration = 'Day End - Cost Of Sales'
    
				--> Create NORMAL JOURNAL header for Cost Of Sales
					IF @NextGLTranID = 0
					BEGIN

     					EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
								22,
								@CompanyID
        
    					EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
								@DayEndDate,
								@NextGLTranID,
								@Narration,
								@Month,
								@Year,
								@UserID,
								@CompanyID

					END
    
				--> Update COST OF SALES CONTROL
					SELECT @GLControlAccount = AB_Accounts_ID
					FROM AB_Control_Accounts
					WHERE Control_Number = 106    --Cost Of Sales Control

				--> Create JOURNAL DETAIL for Cost Of Sales Control
					EXEC sp_AB_Insert_Journal_Detail
							@JNLHeaderID,
							@GLControlAccount,
							@SumTotalCost,
							@Narration,
							@UserID,
							@CompanyID,
							@InsertGLTran
    
				--> Create GL TRANSACTION for Cost Of Sales Control
					EXEC sp_AB_Insert_GL_Transactions
							@Narration,
							22,
							@GLControlAccount,
							@DayEndDate,
							'106 Cost of Sales',
							@Month,
							@Year,
							@NextGLTranID,
							@SumTotalCost,
							@UserID,
							@CompanyID

				--> Reverse signs to balance double entry
					SET @SumTotalCost = @SumTotalCost * -1
    
				--> Update INVENTORY CONTROL
					SELECT @GLControlAccount = AB_Accounts_ID
					FROM AB_Control_Accounts
					WHERE Control_Number = 601    --Inventory Control

				--> Create JOURNAL DETAIL for Inventory Control
					EXEC sp_AB_Insert_Journal_Detail
							@JNLHeaderID,
							@GLControlAccount,
							@SumTotalCost,
							@Narration,
							@UserID,
							@CompanyID,
							@InsertGLTran
    
				--> Create GL TRANSACTION for Inventory Control
					EXEC sp_AB_Insert_GL_Transactions                                        
							@Narration,
							22,
							@GLControlAccount,
							@DayEndDate,
							'601 Inventory',
							@Month,
							@Year,
							@NextGLTranID,
							@SumTotalCost,
							@UserID,
							@CompanyID

				END    --IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
					
--####################################################################################						
					IF @Levy_Count > 0 --If NO LEVY SALES transactions exist
					BEGIN
						DECLARE Get_Data CURSOR
						FOR
						SELECT 
							p.AP_Products_ID,
				--			p.Description,
				--			p.Product_Code,
							p.GL_Purchases_ID,
							p.GL_Sales_ID,
							p.GL_COS_ID,
							ISNULL(SUM(d.Tax_Amount), 0),
							ISNULL(SUM(d.Extended_Amount), 0),
							Cast( SUM( ISNULL(d.Unit_Cost,0) * ISNULL(d.Quantity,0) ) As Money)
						FROM AS_Transactions t
						Inner Join AS_Transaction_Details d On
							t.AS_Transactions_ID = d.AS_Transactions_ID
						Inner Join AP_Products p On
			  				d.AP_Products_ID = p.AP_Products_ID
						WHERE t.AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
							 (t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
							  t.Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
							  t.Day_End IS NULL AND
							  t.Transaction_Date <= @CutOffDate AND
							  p.Slu_AW_YesNo_Levy_Item = 1                              
						GROUP BY 
							p.AP_Products_ID, 			
							p.GL_Purchases_ID,
							p.GL_Sales_ID,
							p.GL_COS_ID

                        OPEN Get_Data
						FETCH NEXT FROM Get_Data 
        				INTO
        					@Levy_AP_Products_ID,
        					@Levy_GRInventoryCOS_ID,
							@Levy_PostGLSales_ID,
							@Levy_PostGLCOS_ID,
							@Levy_SumTax,
							@Levy_SumTotalAmount,
							@Levy_SumTotalCost    
                    	
        				WHILE (@@FETCH_STATUS = 0)
        				BEGIN                        
                            Set @SumTax = ROUND(@Levy_SumTax, 2)
                            Set @SumTotalAmount = ROUND(@Levy_SumTotalAmount, 2)
							Set @SumTotalCost = ROUND(@Levy_SumTotalCost, 2)
						   
							SET @Narration = 'Day End - Sales Levy'

						--> Create NORMAL JOURNAL header for the Sales Journal
							IF @NextGLTranID = 0
							BEGIN

         						EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
										22,
										@CompanyID
	            
        						EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
										@DayEndDate,
										@NextGLTranID,
										@Narration,
										@Month,
										@Year,
										@UserID,
										@CompanyID

							END

						--> Update DEBTORS CONTROL
    						SELECT @GLControlAccount = AB_Accounts_ID
							FROM AB_Control_Accounts
							WHERE Control_Number = 101    --Debtors Control

						--> Create JOURNAL DETAIL for Debtors Control
							EXEC sp_AB_Insert_Journal_Detail
									@JNLHeaderID,
									@GLControlAccount,
									@Levy_SumTotalAmount,
									@Narration,
									@UserID,
									@CompanyID,
									@InsertGLTran

						--> Create GL TRANSACTION for Debtors Control
							EXEC sp_AB_Insert_GL_Transactions
									@Narration,
									22,
									@GLControlAccount,
									@DayEndDate,
									'101 Debtors Levy',
									@Month,
									@Year,
									@NextGLTranID,
									@Levy_SumTotalAmount,
									@UserID,
									@CompanyID

						--> Reverse signs to balance double entry
    						SET @SalesAmount = (@Levy_SumTotalAmount - @Levy_SumTax) * -1
							SET @TaxAmount = @Levy_SumTax * -1
	    
						--> Update SALES CONTROL
							--SELECT @GLControlAccount = AB_Accounts_ID
							--FROM AB_Control_Accounts
							--WHERE Control_Number = 102    --Sales Control
						--> Use product GL account	
                            Set @GLControlAccount = @Levy_PostGLSales_ID  

						--> Create JOURNAL DETAIL for Sales Control
							EXEC sp_AB_Insert_Journal_Detail
									@JNLHeaderID,
									@GLControlAccount,
									@SalesAmount,
									@Narration,
									@UserID,
									@CompanyID,
									@InsertGLTran
	    
						--> Create GL TRANSACTION for Sales Control
							EXEC sp_AB_Insert_GL_Transactions
									@Narration,
									22,
									@GLControlAccount,
									@DayEndDate,
									'102 Sales Levy',
									@Month,
									@Year,
									@NextGLTranID,
									@SalesAmount,
									@UserID,
									@CompanyID

						--> UPDATE GL - VAT Control
							SELECT @GLControlAccount = AB_Accounts_ID
							FROM AB_Control_Accounts
							WHERE Control_Number = 401    --VAT Control

							SET @Narration = 'Day End - VAT on Sales Levy'

						--> Create JOURNAL DETAIL for VAT Control
							EXEC sp_AB_Insert_Journal_Detail
									@JNLHeaderID,
									@GLControlAccount,
									@TaxAmount,
									@Narration,
									@UserID,
									@CompanyID,
									@InsertGLTran

						--> Create GL TRANSACTION for VAT Control
							EXEC sp_AB_Insert_GL_Transactions
									@Narration,
									22,
									@GLControlAccount,
									@DayEndDate,
									'401 VAT on Sales Levy',
									@Month,
									@Year,
									@NextGLTranID,
									@TaxAmount,
									@UserID,
									@CompanyID

							SET @Count = 0

			--> COST OF SALES -----------------------------------------------------

						--> Get parameter 'Post GL COST-OF-SALES in Day-End to each Product's Cost-of-Sales GL Account'
							SELECT @PostGLCOS = RTRIM(LTRIM(Control_Value))
							FROM Sys_AW_Options
							WHERE Control_Type = 'CheckBox' AND
								  Control_Name = 'chkUseProductCOSGL' AND
								  Control_Index = 0 AND
								  AW_User_Companies_ID = @CompanyID


						--> Get parameter 'Post directly to Inventory and Cost-of-Sales accounts  (Continous Inventory method)
							SELECT @GRInventoryCOS = RTRIM(LTRIM(Control_Value))
							FROM Sys_AW_Options
							WHERE Control_Type = 'CheckBox' AND
								  Control_Name = 'chkGRVtoInventoryCOS' AND
								  Control_Index = 0 AND
								  AW_User_Companies_ID = @CompanyID

							IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
							BEGIN

	--------------------------------------------------------------------------------------------
	-- ToDo: ADD NEW CURSOR GROUP BY AP_Products.GL_COS_ID  (Cost-of-Sales GL Account)
	--------------------------------------------------------------------------------------------

								SET @Narration = 'Day End - Cost Of Sales Levy'
	            
							--> Create NORMAL JOURNAL header for Cost Of Sales
								IF @NextGLTranID = 0
								BEGIN

             						EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
											22,
											@CompanyID
	                
            						EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
											@DayEndDate,
											@NextGLTranID,
											@Narration,
											@Month,
											@Year,
											@UserID,
											@CompanyID

								END
	            
							--> Update COST OF SALES CONTROL
        						--SELECT @GLControlAccount = AB_Accounts_ID
								--FROM AB_Control_Accounts
								--WHERE Control_Number = 106    --Cost Of Sales Control
							--> Use product GL account	
                            Set @GLControlAccount = @Levy_PostGLCOS_ID  

							--> Create JOURNAL DETAIL for Cost Of Sales Control
								EXEC sp_AB_Insert_Journal_Detail
										@JNLHeaderID,
										@GLControlAccount,
										@SumTotalCost,
										@Narration,
										@UserID,
										@CompanyID,
										@InsertGLTran
	            
							--> Create GL TRANSACTION for Cost Of Sales Control
								EXEC sp_AB_Insert_GL_Transactions
										@Narration,
										22,
										@GLControlAccount,
										@DayEndDate,
										'106 Cost of Sales Levy',
										@Month,
										@Year,
										@NextGLTranID,
										@SumTotalCost,
										@UserID,
										@CompanyID

							--> Reverse signs to balance double entry
								SET @SumTotalCost = @SumTotalCost * -1
	            
							--> Update INVENTORY CONTROL
								--SELECT @GLControlAccount = AB_Accounts_ID
								--FROM AB_Control_Accounts
								--WHERE Control_Number = 601    --Inventory Control
							--> Use product GL account	
                            Set @GLControlAccount = @Levy_GRInventoryCOS_ID  

							--> Create JOURNAL DETAIL for Inventory Control
								EXEC sp_AB_Insert_Journal_Detail
										@JNLHeaderID,
										@GLControlAccount,
										@SumTotalCost,
										@Narration,
										@UserID,
										@CompanyID,
										@InsertGLTran
	            
							--> Create GL TRANSACTION for Inventory Control
								EXEC sp_AB_Insert_GL_Transactions                                        
										@Narration,
										22,
										@GLControlAccount,
										@DayEndDate,
										'601 Inventory Levy',
										@Month,
										@Year,
										@NextGLTranID,
										@SumTotalCost,
										@UserID,
										@CompanyID

	    
							END    --IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
						FETCH NEXT FROM Get_Data 
        				INTO
        					@Levy_AP_Products_ID,
        					@Levy_GRInventoryCOS_ID,
							@Levy_PostGLSales_ID,
							@Levy_PostGLCOS_ID,
							@Levy_SumTax,
							@Levy_SumTotalAmount,
							@Levy_SumTotalCost    
												
        				END    	
    					CLOSE Get_Data
    					DEALLOCATE Get_Data
						
					END	--If LEVY SALES transactions exist		
--####################################################################################						
																			
                END    --IF @Count > 0    --If SALES transactions exist


    --> RECEIPTS-----------------------------------------------------------

            SET @SumTotalAmount = 0
            SET @Count = 0

            SET @POSReceipts = 0
            SET @BOFReceipts = 0
            SET @EFTReceipts = 0
            SET @POSCount = 0
            SET @BOFCount = 0
            SET @EFTCount = 0

        --> Get POS RECEIPTS (for the CASH CONTROL)
			SELECT @POSReceipts = ISNULL(SUM(Total_Amount), 0),
                   @POSCount = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 7          --POS Receipts
              AND Transaction_Date <= @CutOffDate

            SET @POSReceipts = ROUND(@POSReceipts, 2)


        --> Get BOF RECEIPTS (for the CASH CONTROL)
			SELECT @BOFReceipts = ISNULL(SUM(Total_Amount), 0),
                   @BOFCount = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 21         --BACK OFFICE Receipts
              AND Transaction_Date <= @CutOffDate

            SET @BOFReceipts = ROUND(@BOFReceipts, 2)


        --> Get EFT RECEIPTS (for the CASH CONTROL)
			SELECT @EFTReceipts = ISNULL(SUM(Total_Amount), 0),
                   @EFTCount = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 22         --EFT Receipts
              AND Transaction_Date <= @CutOffDate

            SET @EFTReceipts = ROUND(@EFTReceipts, 2)


            SET @SumTotalAmount = @POSReceipts + @BOFReceipts + @EFTReceipts
            SET @Count = @POSCount + @BOFCount + @EFTCount


            IF @Count > 0
            --> Update DEBTORS CONTROL ------------------------------
                BEGIN

                    SET @Narration = 'Day End - Receipts'

                --> Create NORMAL JOURNAL header for the Sales Journal
                    IF @NextGLTranID = 0
                        BEGIN

             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    22,
                                    @CompanyID
            
            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @DayEndDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID

                        END

                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 101    --DEBTORS CONTROL

                --> Create JOURNAL DETAIL for Debtors Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @SumTotalAmount,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                --> Create GL TRANSACTION for DEBTORS CONTROL
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            22,
                            @GLControlAccount,
                            @DayEndDate,
                            '101 Total Receipts',
                            @Month,
                            @Year,                                @NextGLTranID,
                            @SumTotalAmount,
                            @UserID,
                            @CompanyID


                    IF @POSCount > 0
                    --> Update CASH CONTROL ---------------------------------
                        BEGIN
                            SELECT @GLControlAccount = AB_Accounts_ID
                            FROM AB_Control_Accounts
                            WHERE Control_Number = 206    --CASH CONTROL
    
                            SET @POSReceipts = -(@POSReceipts)

                            SET @Narration = 'Day End - POS Receipts'

                        --> Create JOURNAL DETAIL for CASH CONTROL
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @POSReceipts,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran
    
                        --> Create GL TRANSACTION for Cash Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLControlAccount,
                                    @DayEndDate,
                                    '206 POS Receipts',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,                                        @POSReceipts,
                                    @UserID,
                                    @CompanyID

                        END

                    SET @Count = @BOFCount + @EFTCount
                    SET @SumTotalAmount = 0

                    IF @Count > 0
                    --> Update TRADE DEBTORS PAYMENT CLEARING ---------------
                        BEGIN
                            SELECT @GLControlAccount = AB_Accounts_ID
                            FROM AB_Control_Accounts
                            WHERE Control_Number = 105    --TRADE DEBTORS PAYMENT CLEARING

                            SET @SumTotalAmount = @BOFReceipts + @EFTReceipts
                            SET @SumTotalAmount = -(@SumTotalAmount)

                            SET @Narration = 'Day End - OTHER Receipts'

                        --> Create JOURNAL DETAIL for DEBTORS PAYMENT CLEARING
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @SumTotalAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran
    
                        --> Create GL TRANSACTION for DEBTORS PAYMENT CLEARING
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLControlAccount,
                                    @DayEndDate,
                                    '105 Other Receipts',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @SumTotalAmount,
                                    @UserID,
                                    @CompanyID

                        END

                END


    --> INTEREST - IS UPDATED IN CUSTOMERS INTEREST JOURNALS --------------


    --> SETTLEMENT DISCOUNT------------------------------------------------

            SET @SumTotalAmount = 0
            SET @Count = 0

        --> Get SETTLEMENT DISCOUNT total - NB: THIS IS A NEGATIVE NUMBER
			SELECT @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                   @Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 18         --Settlement Disc
              AND Transaction_Date <= @CutOffDate

            SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)


            IF @Count > 0
            --> Update DEBTORS CONTROL
                BEGIN

                --> (NEW 06 JUL 2002) VAT ON SETTLEMENT DISCOUNT --------
                    --Get the Current Tax Rate
                    SELECT @TaxRate = ISNULL(Tax_Rate, 0)
                    FROM Sys_AW_Tax_Codes
                    WHERE Tax_Code = 'S'    --Standard (Current) rate (e.g. 14%)
                    
                    SET @Settlement_VAT = ROUND((@SumTotalAmount * (@TaxRate / (100 + @TaxRate))) ,2)
                    SET @Settlement_Ex_VAT = (@SumTotalAmount - @Settlement_VAT) 
                    
                    --Make both amounts Debits
                    SET @Settlement_VAT = (@Settlement_VAT * -1)
                    SET @Settlement_Ex_VAT = (@Settlement_Ex_VAT * -1)
                    
                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 103    --SETTLEMENT DISCOUNT ALLOWED

                --> Create NORMAL JOURNAL header for the Sales Journal
                    IF @NextGLTranID = 0
                        BEGIN

             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    24,
                                    @CompanyID
            
            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @DayEndDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID

                        END

                    SET @Narration = 'Day End - Settlement Disc Ex VAT'

                --> Create JOURNAL DETAIL for Settlement Discount Allowed
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @Settlement_Ex_VAT,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran
                
                --> Create GL TRANSACTION: DEBIT Settlement Discount Allowed
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            24,
                            @GLControlAccount,
                            @DayEndDate,
                            '103 Settlement Disc',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Settlement_Ex_VAT,
                            @UserID,
                            @CompanyID

                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 401    --VAT Control

                    SET @Narration = 'Day End - Settlement Disc VAT'

                --> Create JOURNAL DETAIL for VAT on Settlement Discount
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @Settlement_VAT,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran
                
                --> Create GL TRANSACTION: DEBIT VAT Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            24,
                            @GLControlAccount,
                            @DayEndDate,
                            '401 Settlement VAT',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Settlement_VAT,
                            @UserID,
                            @CompanyID

                --> (END NEW 06 JUL 2002) VAT ON SETTLEMENT DISCOUNT ----

                    SET @Narration = 'Day End - Settlement Discount'

                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 101    --Debtors Control

                --> Create JOURNAL DETAIL for Debtors Control (a Credit)
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @SumTotalAmount,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                --> Create GL TRANSACTION: CREDIT Debtors Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            24,
                            @GLControlAccount,
                            @DayEndDate,
                            '101 Settlement Disc',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @SumTotalAmount,
                            @UserID,
                            @CompanyID

                    SET @Count = 0

                END

 --   --> Consignment------------------------------------------------

	--		SELECT @SumConsignmentTax = ISNULL(SUM(Total_Tax_Amount), 0),
 --                  @SumConsignmentTotalAmount = ISNULL(SUM(Total_Amount), 0),
 --                  @SumConsignmentTotalCost = ISNULL(SUM(Total_Cost), 0),
 --                  @Count = ISNULL(COUNT(*), 0)
	--		FROM AS_Transactions
 --           WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
 --                (Sys_AW_Transaction_Types_ID = 33  OR      -- Consignment Note
 --                 Sys_AW_Transaction_Types_ID = 34  OR      -- Consignment Sold
 --                 Sys_AW_Transaction_Types_ID = 35) AND     -- Consignment Returned
 --                 Day_End IS NULL
 --             AND Transaction_Date <= @CutOffDate

 --           SET @SumConsignmentTax = ROUND(@SumConsignmentTax, 2)
 --           SET @SumConsignmentTotalAmount = ROUND(@SumConsignmentTotalAmount, 2)
 --           SET @SumConsignmentTotalCost = ROUND(@SumConsignmentTotalCost, 2)        
        
	--		--> Reverse signs to balance double entry
	--		SET @SumConsignmentTotalCost = @SumConsignmentTotalCost * -1
	--		SET @SumConsignmentTax = @SumConsignmentTax * -1

 --           IF @Count > 0
 --           --> Update DEBTORS CONTROL
 --           BEGIN

	--			--Consignment Debtor
	--			SET @Narration = 'Day End - Consignment Sales'
	--			SET @GLControlAccount = 0
				
	--			--Consignment Trade Debtors
	--			SELECT @GLControlAccount = AB_Accounts_ID
	--			FROM AB_Control_Accounts
	--			WHERE Control_Number = 703

 --				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
	--					22,
	--					@CompanyID
    
	--			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
	--					@DayEndDate,
	--					@NextGLTranID,
	--					@Narration,
	--					@Month,
	--					@Year,
	--					@UserID,
	--					@CompanyID				

	--		--> Create JOURNAL DETAIL for Consignment Trade Debtors
	--			EXEC sp_AB_Insert_Journal_Detail
	--					@JNLHeaderID,
	--					@GLControlAccount,
	--					@SumConsignmentTotalAmount,
	--					@Narration,
	--					@UserID,
	--					@CompanyID,
	--					@InsertGLTran

	--		--> Create GL TRANSACTION for Consignment Trade Debtors
	--			EXEC sp_AB_Insert_GL_Transactions
	--					@Narration,
	--					22,
	--					@GLControlAccount,
	--					@DayEndDate,
	--					'703 Consignment Debtors',
	--					@Month,
	--					@Year,
	--					@NextGLTranID,
	--					@SumConsignmentTotalAmount,
	--					@UserID,
	--					@CompanyID

	--			SET @Narration = 'Day End - Consignment Inentory'
	--			SET @GLControlAccount = 0
    		    
 --   		    -- Consignment Inventory
 --   			SELECT @GLControlAccount = AB_Accounts_ID
 --               FROM AB_Control_Accounts
 --               WHERE Control_Number = 701                
    		
 --				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
	--					22,
	--					@CompanyID    	
							
	--			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
	--					@DayEndDate,
	--					@NextGLTranID,
	--					@Narration,
	--					@Month,
	--					@Year,
	--					@UserID,
	--					@CompanyID				

	--		--> Create JOURNAL DETAIL for Consignment Trade Debtors
	--			EXEC sp_AB_Insert_Journal_Detail
	--					@JNLHeaderID,
	--					@GLControlAccount,
	--					@SumConsignmentTotalCost,
	--					@Narration,
	--					@UserID,
	--					@CompanyID,
	--					@InsertGLTran
    		
	--			--> INSERT Consignment Inventory GL entry
	--			EXEC sp_AB_Insert_GL_Transactions
	--					@Narration,
	--					22,
	--					@GLControlAccount,
	--					@DayEndDate,
	--					'701 Consignment Inentory',
	--					@Month,
	--					@Year,
	--					@NextGLTranID,
	--					@SumConsignmentTotalCost,
	--					@UserID,
	--					@CompanyID

	--			SET @Narration = 'Day End - Consignment VAT'
	--			SET @GLControlAccount = 0

 --   		    -- Consignment VAT
 --   			SELECT @GLControlAccount = AB_Accounts_ID
 --               FROM AB_Control_Accounts
 --               WHERE Control_Number = 704                
    		
 --				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
	--					22,
	--					@CompanyID    	
							
	--			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
	--					@DayEndDate,
	--					@NextGLTranID,
	--					@Narration,
	--					@Month,
	--					@Year,
	--					@UserID,
	--					@CompanyID				

	--		--> Create JOURNAL DETAIL for Consignment Inventory
	--			EXEC sp_AB_Insert_Journal_Detail
	--					@JNLHeaderID,
	--					@GLControlAccount,
	--					@SumConsignmentTax,
	--					@Narration,
	--					@UserID,
	--					@CompanyID,
	--					@InsertGLTran
    		
	--			--> INSERT Consignment VAT GL entry
	--			EXEC sp_AB_Insert_GL_Transactions
	--					@Narration,
	--					22,
	--					@GLControlAccount,
	--					@DayEndDate,
	--					'704 Consignment VAT',
	--					@Month,
	--					@Year,
	--					@NextGLTranID,
	--					@SumConsignmentTax,
	--					@UserID,
	--					@CompanyID

	--		END -- Consignment
			
	----> Consignment------------------------------------------------

-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG
-------------------------------------------------------------------------
			UPDATE AS_Transactions
            SET Day_End = @DayEndDate
            WHERE Day_End IS NULL AND
                  AW_User_Companies_ID = @CompanyID
              AND Transaction_Date <= @CutOffDate

-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG in AS_Till_Payouts
-------------------------------------------------------------------------
			UPDATE AS_Till_Payouts
            SET Day_End = @DayEndDate
            WHERE Day_End IS NULL AND
                  AW_User_Companies_ID = @CompanyID
              AND Payout_Date <= @CutOffDate

-------------------------------------------------------------------------
--> INSERT INTO AS_Day_Ends TABLE
-------------------------------------------------------------------------
            INSERT AS_Day_Ends
                (
                    Day_End,
                	AB_Transaction_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    AB_Transaction_Ref,
                    Date_Captured,
                    User_ID,
                    AW_User_Companies_ID
                )
            VALUES
                (
                    @DayEndDate,
                    --@CutOffDate, --@DayEndDate, V6.2 @DayEndDate changed to ShortDateTime Check!!!!!!!!!!!!!!!!
                    @DayEndDate,
                    @Month,
                    @Year,
                    @NextGLTranID,
                    @DayEndDate,
                    @UserID,
                    @CompanyID
                )
-------------------------------------------------------------------------
			--Populates Day End summary tables

			EXEC sp_AS_Day_End_Summary @DayEndDate, @CompanyID

		COMMIT TRANSACTION

        SET @RetVal = 1
	END

    ELSE
	IF @Choice = 2    --Reverse a Day-End
		BEGIN
			BEGIN TRANSACTION
			
    			UPDATE AS_Transactions
                SET Day_End = NULL
                WHERE AW_User_Companies_ID = @CompanyID
                  --AND Day_End = @DayEndDate
					AND Day_End = @CutOffDate                  

    			--UPDATE AS_Day_Ends
       --         SET Slu_AW_Active_ID = 5
       --         WHERE AW_User_Companies_ID = @CompanyID
       --           AND Day_End = @DayEndDate

			COMMIT TRANSACTION
		END

    ELSE
	IF @Choice = 3    --(Not Used)
		BEGIN
			SELECT *
            FROM vw_RPT_AS_Transactions_Transaction_Details
            WHERE DATEDIFF(d, @DayEndDate, tDayEnd) = 0 AND
                  tCompanyID = @CompanyID
		END

    ELSE
	IF @Choice = 4 -- Check if any Day-Ends have been done this minute/day
		BEGIN
			SELECT TOP 1 @DayEndCheck = Day_End
            FROM AS_Transactions
            WHERE DATEDIFF(n, @DayEndDate, Day_End) = 0 AND           --n = minute
                  AW_User_Companies_ID = @CompanyID                   --Added 04/06/05
			
            IF @DayEndCheck IS NULL 
				BEGIN 
					SELECT TOP 1 @DayEndCheck = Day_End
                    FROM AS_Transactions
                    WHERE DATEDIFF(d, @DayEndDate, Day_End) = 0 AND   --d = day
                          AW_User_Companies_ID = @CompanyID           --Added 04/06/05
					
                    IF NOT @DayEndCheck IS NULL 
						SET @RetVal = 1    -- A Day-End was done during this day
				END
			ELSE
				SET @RetVal = 2            -- A Day-End was done during this minute
		END

RETURN @RetVal
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Day_End_Sales_Split_Types
--Purpose       :Day-End procedure with Sales SPLIT by PRODUCT TYPE
--              :Inserts GL Journal and GL Transactions to GL CONTROL ACCOUNTS:
--              :1. DEBTORS, SALES, & VAT CONTROL
--              :2. RECEIPTS to DEBTORS & CASH CONTROL
--              :3. INTEREST JOURNALS to DEBTORS & INTEREST RECEIVED - Removed 31/05/04
--              :4. SETTLEMENT DISCOUNT to DEBTORS & SETTLEMENT DISCOUNT ALLOWED
--              :    for the following AS_Transaction_Types:
--              :        3=Invoice, 4=Refund, 7=Receipt,
--              :        15=Interest Journal, 18=Settlement Discount
--              :
--              :Ignores 5=Customer Journals. This is updated in Customer Journals
--              :-------------------------------------------------------
--              :GL Transaction Ref no's: !! REDUNDANT 15/10/03 !!
--              :Sales:            Debtors = 90, Sales = 91, VAT = 92
--              :Cost Of Sales:    Cost Of Sales = 82, Inventory = 83
--              :Receipts:         Debtors = 93, Cash = 94
--              :Interest:         Debtors = 95, Interest Received = 96 - Removed 31/05/04
--              :Settlement:       Debtors = 97, Discount Allowed = 98
--              :-------------------------------------------------------
--Calls         :sp_AB_Next_Transaction_Number
--              :sp_AB_Insert_Journal_Header
--              :sp_AB_Insert_Journal_Detail
--              :sp_AB_Insert_GL_Transactions
--              :sp_AB_Insert_System_GL_Account
--Date          :2006/10/03
--Authors       :TB
--MODS          :
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.3      :12/02/09 - Added new split COST-OF-SALES and INVENTORY by TYPE - RM
--2004.4.6      :08/08/09 - Added UPDATE DAY-END FLAG in NEW AS_Till_Payouts table
--2004.5.3      :09/08/11 - Added Day-End CUTOFF DATE using Transaction_Date and DELETE DAY-END
--              :23/08/11 - Modified @Choice = 5 (Check if Sales Split product totals balance to Sales totals)
--              :           to SET @RetVal = Difference, and removed ZERO splits total return value setting
--2004.5.5      :31/10/11 - Changed Day_End = @CutOffDate to Transaction_Date <= @CutOffDate in @Choice = 5 !!!
--              :           Previously this would have found NO TRANSACTIONS because Day_End WOULD HAVE BEEN NULL !!!
--              :31/10/11 - Fixed SELECT CLAUSE of Sales_Cursor and added Transaction_Date <= @CutOffDate
--              :           to SELECT DAILY SALES TOTALS by TYPE. When a Day End is deleted we only want
--              :           to fetch ALL Day_End IS NULL transactions UP TO THE CUTOFF DATE
--              :10/11/11 - Added Set @RetVal = 1 in DO DAY-END when Day-End completed succesfully
--2004.5.6      :06/12/11 - Changed DECLARE @RetValValue money to @RetValValue float to prevent ROUNDING the result
--              :           and set it to 23061949 if transaction count = 0 (because it ONLY returns INTEGERS)
--2004.6.2 RL   :2015-08-07 - Added Call to sp_AS_Day_End_Summary. Writes to Day End Summary tables
--2004.6.2 RL   :2015-08-07 - Changed @DayEndDate from DateTime to SmallDateTime
--2016.6.2 RL	:2016-08-04	Changed Settlement discount from 22 to 24 ABTranType - AP Settlement
--							So that it shows in its own section on TAX report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Day_End_Sales_Split_Types]
	(
		@Choice int,
		@CompanyID int,
		@Month tinyint,
		@Year int,
        @UserID int,
        @CutOffDate datetime
	)
AS

SET NOCOUNT ON

	DECLARE @DayEndDate SmallDateTime, --DateTime,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @DayEndCheck DateTime,
            @RetVal int,
            @RetValValue float,
            @SumAmount money,
            @SumTax money,
            @SumTotalAmount money,
            @SumTotalCost money,
            @GLControlAccount int,
            @CostAmount money,
            @SalesAmount money,
            @TaxAmount money,
            @Count int,
            @PAYCount int,
            @POSCount int,
            @BOFCount int,
            @EFTCount int,
            @InsertGLTran bit,
            @Settlement_Disc_Allowed_GL_ID int,
            @Settlement_Ex_VAT money,
            @Settlement_VAT money,
            @POSReceipts money,
            @BOFReceipts money,
            @EFTReceipts money,
            @TaxRate decimal(5,2),
            @SplitGLAccount varchar(50),
            @COSGLDescription varchar(50),
            @SalesGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @SplitSales money,
            @GLSalesID int,
            @GLCOSID int,
            @GLInventoryID int


	SET @DayEndDate = @CutOffDate    -- NEW 2004.5.3
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
    SET @Count = 0
	SET @RetVal = 0


	IF @Choice = 0    --Select list of PREVIOUS DAY-ENDS (PICKLIST)
		BEGIN
			SELECT AS_Day_Ends_ID AS [ID],
                   Day_End,
                   AB_Transaction_Ref AS [GL Tran Ref],
                   AB_Transaction_Date AS [GLTranDate]
            FROM AS_Day_Ends
            WHERE AW_User_Companies_ID = @companyID
            ORDER BY Day_End DESC
		END

	ELSE
	IF @Choice = 1    --Do a NEW DAY-END
		BEGIN
            SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

			BEGIN TRANSACTION

        --> SALES--------------------------------------------------------------

                SET @SumTax = 0
                SET @SumTotalAmount = 0
                SET @SumTotalCost = 0
                SET @Count = 0

            --> Get SALES
				SELECT @SumTax = ISNULL(SUM(Total_Tax_Amount), 0),
                       @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                       @SumTotalCost = ISNULL(SUM(Total_Cost), 0),
                       @Count = ISNULL(COUNT(*), 0)
				FROM AS_Transactions
                WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                     (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                      Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                      Day_End IS NULL AND
                      Transaction_Date <= @CutOffDate


                SET @SumTax = ROUND(@SumTax, 2)
                SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)
                SET @SumTotalCost = ROUND(@SumTotalCost, 2)


                ---------------------------------------------------------------------
                --> If SALES transactions exist
                ---------------------------------------------------------------------
                IF @Count > 0
                    BEGIN

                        SET @Narration = 'Day End - Debtors Sales'

                    --> Create NORMAL JOURNAL header for the Sales Journal
                        IF @NextGLTranID = 0
                            BEGIN
                 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                        22,
                                        @CompanyID
                
                				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @DayEndDate,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
                            END

                    --> Update DEBTORS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 101    --Debtors Control
    
                    --> Create JOURNAL DETAIL for Debtors Control
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @SumTotalAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION for Debtors Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                22,
                                @GLControlAccount,
                                @DayEndDate,
                                '101 Debtors Sales',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @SumTotalAmount,
                                @UserID,
                                @CompanyID


                        SET @Narration = 'Day End - Sales'

                        ---------------------------------------------------------------------
                        --> Post Product Sales in Day-End to a Sales GL Account by Product Type
                        ---------------------------------------------------------------------
                        DECLARE Sales_Cursor CURSOR FOR
                            (
                                SELECT t.[Description],
                                       SUM(d.Extended_Amount - d.Tax_Amount),
                                       SUM(d.Unit_Cost * d.Quantity)
                                FROM AS_Transaction_Details d
                                    INNER JOIN AS_Transactions h
                                        ON h.AS_Transactions_ID = d.AS_Transactions_ID
                                    INNER JOIN AP_Products p
                                        ON d.AP_Products_ID = p.AP_Products_ID
                                    LEFT JOIN Lup_AP_Product_Types t
                                        ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID
                                WHERE d.AW_User_Companies_ID = @CompanyID AND
                                     (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                                      h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                                      h.Day_End IS NULL AND
                                      Transaction_Date <= @CutOffDate
                                GROUP BY t.[Description]
                            )

                    	OPEN Sales_Cursor

                    	FETCH NEXT FROM Sales_Cursor 
                    	INTO
                            @SplitGLAccount,
                            @SalesAmount,
                            @CostAmount

                    	WHILE @@FETCH_STATUS = 0
                    	BEGIN

                            SET @SalesAmount = ROUND(@SalesAmount, 2)
                            SET @CostAmount = ROUND(@CostAmount, 2)
                            SET @GLSalesID = 0

                            SET @SalesGLDescription = LEFT('SALES - ' + @SplitGLAccount, 50)
                            SET @COSGLDescription = LEFT('C.O.S. - ' + @SplitGLAccount, 50)
                            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @SplitGLAccount, 50)


                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL SALES AccountID
                            ---------------------------------------------------------------------
                            SET @GLSalesID = 0

                            SELECT TOP 1 @GLSalesID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @SalesGLDescription AND
                                  Sys_AB_Account_Categories_ID = 13 AND        --REVENUE
                                  Slu_AW_Active_ID = 1

                            IF @GLSalesID = 0
                                BEGIN
                     				EXEC @GLSalesID = sp_AB_Insert_System_GL_Account
                                                            @SalesGLDescription,
                                                            13,
                                                            @UserID,
                                                            @CompanyID
                                END


                            --> Reverse signs SALES amount to balance double entry
            	            SET @SalesAmount = (@SalesAmount * -1)


                            --> Create JOURNAL DETAIL for Sales Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLSalesID,
                                    @SalesAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for SPLIT SALES Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLSalesID,
                                    @DayEndDate,
                                    '102 Sales',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @SalesAmount,
                                    @UserID,
                                    @CompanyID


                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL C.O.S. AccountID
                            ---------------------------------------------------------------------
                            SET @GLCOSID = 0

                            SELECT TOP 1 @GLCOSID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @COSGLDescription AND
                                  Sys_AB_Account_Categories_ID = 14 AND        --COST OF SALES
                                  Slu_AW_Active_ID = 1

                            IF @GLCOSID = 0
                                BEGIN
                     				EXEC @GLCOSID = sp_AB_Insert_System_GL_Account
                                                            @COSGLDescription,
                                                            14,
                                                            @UserID,
                                                            @CompanyID
                                END

                            --> Create JOURNAL DETAIL for C.O.S. Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLCOSID,
                                    @CostAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for SPLIT C.O.S. Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLCOSID,
                                    @DayEndDate,
                                    '106 Cost of Sales',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @CostAmount,
                                    @UserID,
                                    @CompanyID


                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0

                            SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @InventoryGLDescription AND
                                  Sys_AB_Account_Categories_ID = 7 AND        --INVENTORIES
                                  Slu_AW_Active_ID = 1

                            IF @GLInventoryID  = 0
                                BEGIN
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END


                            --> Reverse signs INVENTORY amount to balance double entry
            	            SET @CostAmount = (@CostAmount * -1)


                            --> Create JOURNAL DETAIL for INVENTORY Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @CostAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for SPLIT INVENTORY Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLInventoryID,
                                    @DayEndDate,
                                    '601 Inventory',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @CostAmount,
                                    @UserID,
                                    @CompanyID


                        	FETCH NEXT FROM Sales_Cursor 
                        	INTO
                                @SplitGLAccount,
                                @SalesAmount,
                                @CostAmount

                    	END

                    	CLOSE Sales_Cursor

                    	DEALLOCATE Sales_Cursor
                        ---------------------------------------------------------------------


                    --> Reverse signs to balance double entry
                        SET @TaxAmount = (@SumTax * -1)


                    --> UPDATE GL - VAT Control
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 401    --VAT Control

                        SET @Narration = 'Day End - VAT on Sales'

                    --> Create JOURNAL DETAIL for VAT Control
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @TaxAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION for VAT Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                22,
                                @GLControlAccount,
                                @DayEndDate,
                                '401 VAT on Sales',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @TaxAmount,
                                @UserID,
                                @CompanyID
    
--                        SET @Count = 0

                    END    --IF @Count > 0    --If SALES transactions exist


        --> COST OF SALES - IS UPDATED IN STOCK RECEIPTS GRV ------------------


        --> RECEIPTS-----------------------------------------------------------

                SET @SumTotalAmount = 0
                SET @PAYCount = 0
                SET @Count = 0

                SET @POSReceipts = 0
                SET @BOFReceipts = 0
                SET @EFTReceipts = 0
                SET @POSCount = 0
                SET @BOFCount = 0
                SET @EFTCount = 0


            --> Get POS RECEIPTS (for the CASH CONTROL)
				SELECT @POSReceipts = ISNULL(SUM(Total_Amount), 0),
                       @POSCount = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 7 AND      --POS Receipts
                      Transaction_Date <= @CutOffDate

                SET @POSReceipts = ROUND(@POSReceipts, 2)


            --> Get BOF RECEIPTS (for the CASH CONTROL)
				SELECT @BOFReceipts = ISNULL(SUM(Total_Amount), 0),
                       @BOFCount = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 21 AND     --BACK OFFICE Receipts
                      Transaction_Date <= @CutOffDate

                SET @BOFReceipts = ROUND(@BOFReceipts, 2)


            --> Get EFT RECEIPTS (for the CASH CONTROL)
				SELECT @EFTReceipts = ISNULL(SUM(Total_Amount), 0),
                       @EFTCount = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 22 and     --EFT Receipts
                      Transaction_Date <= @CutOffDate

                SET @EFTReceipts = ROUND(@EFTReceipts, 2)


                SET @SumTotalAmount = @POSReceipts + @BOFReceipts + @EFTReceipts
                SET @PAYCount = @POSCount + @BOFCount + @EFTCount


                ---------------------------------------------------------------------
                --> If PAYMENT transactions exist
                ---------------------------------------------------------------------
                IF @PAYCount > 0
                    BEGIN

                        ---------------------------------------------------------------------
                        --> Update DEBTORS CONTROL - TOTAL RECEIPTS
                        ---------------------------------------------------------------------
                        SET @Narration = 'Day End - Total Receipts'

                    --> Create NORMAL JOURNAL header for the Sales Journal
                        IF @NextGLTranID = 0
                            BEGIN
                 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                        22,
                                        @CompanyID
                
                				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @DayEndDate,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
                            END

                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 101    --DEBTORS CONTROL
    
                    --> Create JOURNAL DETAIL for Debtors Control
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @SumTotalAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION for DEBTORS CONTROL
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                22,
                                @GLControlAccount,
                                @DayEndDate,
                                '101 Total Receipts',
                                @Month,
                                @Year,                                @NextGLTranID,
                                @SumTotalAmount,
                                @UserID,
                                @CompanyID


                        ---------------------------------------------------------------------
                        --> Update CASH CONTROL - POS RECEIPTS
                        ---------------------------------------------------------------------
                        IF @POSCount > 0
                            BEGIN
                                SELECT @GLControlAccount = AB_Accounts_ID
                                FROM AB_Control_Accounts
                                WHERE Control_Number = 206    --CASH CONTROL
        
                                SET @POSReceipts = (@POSReceipts * -1)

                                SET @Narration = 'Day End - POS Receipts'
        
                            --> Create JOURNAL DETAIL for CASH CONTROL
                                EXEC sp_AB_Insert_Journal_Detail
                                        @JNLHeaderID,
                                        @GLControlAccount,
                                        @POSReceipts,
                                        @Narration,
                                        @UserID,
                                        @CompanyID,
                                        @InsertGLTran
        
                            --> Create GL TRANSACTION for Cash Control
                                EXEC sp_AB_Insert_GL_Transactions
                                        @Narration,
                                        22,
                                        @GLControlAccount,
                                        @DayEndDate,
                                        '206 POS Receipts',
                                        @Month,
                                        @Year,
                                        @NextGLTranID,                                        @POSReceipts,
                                        @UserID,
                                        @CompanyID
        
                            END

                        SET @Count = @BOFCount + @EFTCount
                        SET @SumTotalAmount = 0

                        ---------------------------------------------------------------------
                        --> Update TRADE DEBTORS PAYMENT CLEARING - OTHER Receipts
                        ---------------------------------------------------------------------
                        IF @Count > 0
                            BEGIN
                                SELECT @GLControlAccount = AB_Accounts_ID
                                FROM AB_Control_Accounts
                                WHERE Control_Number = 105    --TRADE DEBTORS PAYMENT CLEARING

                                SET @SumTotalAmount = @BOFReceipts + @EFTReceipts
                                SET @SumTotalAmount = (@SumTotalAmount * -1)

                                SET @Narration = 'Day End - OTHER Receipts'
        
                            --> Create JOURNAL DETAIL for DEBTORS PAYMENT CLEARING
                                EXEC sp_AB_Insert_Journal_Detail
                                        @JNLHeaderID,
                                        @GLControlAccount,
                                        @SumTotalAmount,
                                        @Narration,
                                        @UserID,
                                        @CompanyID,
                                        @InsertGLTran
        
                            --> Create GL TRANSACTION for DEBTORS PAYMENT CLEARING
                                EXEC sp_AB_Insert_GL_Transactions
                                        @Narration,
                                        22,
                                        @GLControlAccount,
                                        @DayEndDate,
                                        '105 Other Receipts',
                                        @Month,
                                        @Year,
                                        @NextGLTranID,
                                        @SumTotalAmount,
                                        @UserID,
                                        @CompanyID
        
                            END

                    END        --> If PAYMENT transactions exist


        --> INTEREST - IS UPDATED IN CUSTOMERS INTEREST JOURNALS --------------


        --> SETTLEMENT DISCOUNT------------------------------------------------

                SET @SumTotalAmount = 0
                SET @Count = 0

            --> Get SETTLEMENT DISCOUNT total - NB: THIS IS A NEGATIVE NUMBER
				SELECT @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                       @Count = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 18 AND     --Settlement Disc
                      Transaction_Date <= @CutOffDate

                SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)


                ---------------------------------------------------------------------
                --> If SETTLEMENT DISCOUNT transactions exist
                ---------------------------------------------------------------------
                IF @Count > 0
                    BEGIN

                    --> VAT ON SETTLEMENT DISCOUNT --------
                        --Get the Current Tax Rate
                        SELECT @TaxRate = ISNULL(Tax_Rate, 0)
                        FROM Sys_AW_Tax_Codes
                        WHERE Tax_Code = 'S'    --Standard (Current) rate (e.g. 14%)
                        
                        SET @Settlement_VAT = ROUND((@SumTotalAmount * (@TaxRate / (100 + @TaxRate))) ,2)
                        SET @Settlement_Ex_VAT = (@SumTotalAmount - @Settlement_VAT) 
                        
                        --Make both amounts Debits
                        SET @Settlement_VAT = (@Settlement_VAT * -1)
                        SET @Settlement_Ex_VAT = (@Settlement_Ex_VAT * -1)
                        
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 103    --SETTLEMENT DISCOUNT ALLOWED

                    --> Create NORMAL JOURNAL header for the Sales Journal
                        IF @NextGLTranID = 0
                            BEGIN
                 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                        24,
                                        @CompanyID
                
                				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @DayEndDate,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
                            END

                        SET @Narration = 'Day End - Settlement Disc Ex VAT'
                    
                    --> Create JOURNAL DETAIL for Settlement Discount Allowed
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @Settlement_Ex_VAT,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
                    
                    --> Create GL TRANSACTION: DEBIT Settlement Discount Allowed
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                24,
                                @GLControlAccount,
                                @DayEndDate,
                                '103 Settlement Disc',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @Settlement_Ex_VAT,
                                @UserID,
                                @CompanyID

                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 401    --VAT Control

                        SET @Narration = 'Day End - Settlement Disc VAT'

                    --> Create JOURNAL DETAIL for VAT on Settlement Discount
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @Settlement_VAT,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
                    
                    --> Create GL TRANSACTION: DEBIT VAT Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                24,
                                @GLControlAccount,
                                @DayEndDate,
                                '401 Settlement VAT',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @Settlement_VAT,
                                @UserID,
                                @CompanyID

                    --> VAT ON SETTLEMENT DISCOUNT

                        SET @Narration = 'Day End - Settlement Discount'

                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 101    --Debtors Control

                    --> Create JOURNAL DETAIL for Debtors Control (a Credit)
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @SumTotalAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION: CREDIT Debtors Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                24,
                                @GLControlAccount,
                                @DayEndDate,
                                '101 Settlement Disc',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @SumTotalAmount,
                                @UserID,
                                @CompanyID

                        SET @Count = 0

                    END


-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG
-------------------------------------------------------------------------
				UPDATE AS_Transactions
                SET Day_End = @DayEndDate
                WHERE AW_User_Companies_ID = @CompanyID AND
                      Day_End IS NULL AND
                      Transaction_Date <= @CutOffDate

-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG in AS_Till_Payouts
-------------------------------------------------------------------------
				UPDATE AS_Till_Payouts
                SET Day_End = @DayEndDate
                WHERE AW_User_Companies_ID = @CompanyID AND
                      Day_End IS NULL AND
                      Payout_Date <= @CutOffDate

-------------------------------------------------------------------------
--> INSERT INTO AS_Day_Ends TABLE
-------------------------------------------------------------------------
                INSERT AS_Day_Ends
                    (
                        Day_End,
                    	AB_Transaction_Date,
                        Slu_AW_Months_ID,
                        Slu_AW_Years_ID,
                        AB_Transaction_Ref,
                        Date_Captured,
                        User_ID,
                        AW_User_Companies_ID
                    )
                VALUES
                    (
                        @DayEndDate,
                        @DayEndDate,
                        @Month,
                        @Year,
                        @NextGLTranID,
                        @DayEndDate,
                        @UserID,
                        @CompanyID
                    )
-------------------------------------------------------------------------
			--Populates Day End summary tables
			EXEC sp_AS_Day_End_Summary @DayEndDate, @CompanyID

			COMMIT TRANSACTION

            SET @RetVal = 1
		END

    ELSE
	IF @Choice = 2    --Reverse a Day-End
		BEGIN
			BEGIN TRANSACTION
    			UPDATE AS_Transactions
                SET Day_End = NULL
                WHERE AW_User_Companies_ID = @CompanyID AND
                      Day_End = @DayEndDate

    			UPDATE AS_Day_Ends
                SET Slu_AW_Active_ID = 5
                WHERE AW_User_Companies_ID = @CompanyID
                  AND Day_End = @DayEndDate

			COMMIT TRANSACTION
		END

    ELSE
	IF @Choice = 3    --(Not Used)
		BEGIN
			SELECT *
            FROM vw_RPT_AS_Transactions_Transaction_Details
            WHERE DATEDIFF(d, @DayEndDate, tDayEnd) = 0 AND
                  tCompanyID = @CompanyID
		END

    ELSE
	IF @Choice = 4 -- Check if any Day-Ends have been done this minute/day
		BEGIN
			SELECT TOP 1 @DayEndCheck = Day_End
            FROM AS_Transactions
            WHERE DATEDIFF(n, @DayEndDate, Day_End) = 0 AND           --n = minute
                  AW_User_Companies_ID = @CompanyID                   --Added 04/06/05
			
            IF @DayEndCheck IS NULL 
				BEGIN 
					SELECT TOP 1 @DayEndCheck = Day_End
                    FROM AS_Transactions
                    WHERE DATEDIFF(d, @DayEndDate, Day_End) = 0 AND   --d = day
                          AW_User_Companies_ID = @CompanyID           --Added 04/06/05
					
                    IF NOT @DayEndCheck IS NULL 
						SET @RetVal = 1    -- A Day-End was done during this day
				END
			ELSE
				SET @RetVal = 2            -- A Day-End was done during this minute
		END

    ELSE
	IF @Choice = 5     -- Check if Sales Split Day-End totals balance to Sales totals
		BEGIN

            SET @RetVal = 0
            SET @RetValValue = 0
            SET @Count = 0

        --> Get SALES
			SELECT @Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions
            WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  Day_End IS NULL AND
                  Transaction_Date <= @CutOffDate


            IF @Count = 0
                BEGIN
                    --SET @RetValValue = 0.9999
                    SET @RetValValue = 23061949

                    RETURN @RetValValue
                END


    		SELECT @SumTax = ISNULL(SUM(Total_Tax_Amount), 0),
                   @SumTotalAmount = ISNULL(SUM(Total_Amount), 0)
    		FROM AS_Transactions
            WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  Day_End IS NULL AND
                  Transaction_Date <= @CutOffDate


            SET @SumTax = ROUND(@SumTax, 2)
            SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)


            SELECT @SplitSales = ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0)
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Types t
                    ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                  h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                  h.Day_End IS NULL AND
                  h.Transaction_Date <= @CutOffDate

            SET @SplitSales = ROUND(@SplitSales, 2)
            SET @RetValValue = (@SumTotalAmount - @SumTax) - @SplitSales


            RETURN @RetValValue
        END

RETURN @RetVal

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE [dbo].[sp_AS_Day_End_Summary]
    (
		@Day_End	SmallDateTime,
		@CompanyID	Int
    )

AS

SET NOCOUNT ON

	DECLARE	@ValuationMethod smallint,
			@ZeroCostOverride smallint,
			@CurrentInvValuation money,
			@AS_Day_Ends_ID int,
			--@Day_End smallint,
			--Daily Sales
			@Day_ExcIntCompCost money,
			@Day_ExcIntCompSale money,
			@Day_ExcIntCompStdGP money,
			@Day_ExcIntCompActGP money,
			@Day_ExcIntCompGP money,
			
			@Day_IncIntCompCost money,
			@Day_IncIntCompSale money,
			@Day_IncIntCompStdGP money,
			@Day_IncIntCompActGP money,
			@Day_IncIntCompGP money,

			--Monthly Sales
			@Month_ExcIntCompCost money,
			@Month_ExcIntCompSale money,
			@Month_ExcIntCompStdGP money,
			@Month_ExcIntCompActGP money,
			@Month_ExcIntCompGP money,
			
			@Month_IncIntCompCost money,
			@Month_IncIntCompSale money,
			@Month_IncIntCompStdGP money,
			@Month_IncIntCompActGP money,
			@Month_IncIntCompGP money,
			
            @LastPeriodProcedureDate datetime,
            @LastPeriodProcedureMonthID tinyint,
            @LastPeriodProcedureYearID int

    --> Get Primary Costing method
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID

    --> Get Secondary Costing method (Zero Primary Cost override)
    SELECT @ZeroCostOverride = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optZeroCostOverride' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID
    
--> Get the date of the LAST CUSTOMER MONTH-END done
	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date,
                 @LastPeriodProcedureMonthID = [Month],
                 @LastPeriodProcedureYearID = [Year]
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
	ORDER BY Month_End_Date DESC
    
    SELECT @AS_Day_Ends_ID = AS_Day_Ends_ID
    FROM AS_Day_Ends
    WHERE DAY_END = @Day_End
    
	BEGIN--Current Inventory Valuation
		IF @ValuationMethod = 0
		BEGIN
			IF @ZeroCostOverride = 0
			BEGIN
				SELECT @CurrentInvValuation =SUM(	
													CASE WHEN ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
			ELSE
			IF @ZeroCostOverride = 1
			BEGIN
				SELECT @CurrentInvValuation = SUM(	
													CASE WHEN ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
			ELSE
			IF @ZeroCostOverride = 2
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
		END
		ELSE
		IF @ValuationMethod = 1
		BEGIN
			IF @ZeroCostOverride = 0
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
			ELSE
			IF @ZeroCostOverride = 1
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
			ELSE
			IF @ZeroCostOverride = 2
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
		END
		ELSE
		IF @ValuationMethod = 2
		BEGIN
			IF @ZeroCostOverride = 0
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Average_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
			ELSE
			IF @ZeroCostOverride = 1
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Last_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
			ELSE
			IF @ZeroCostOverride = 2
			BEGIN
				SELECT @CurrentInvValuation = SUM(
													CASE WHEN ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2) = 0
													THEN ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													ELSE ROUND(ISNULL(Standard_Cost, 0) * ( ISNULL(On_Hand, 0) - dbo.fn_AP_Get_Consignment_Stock_Qty(AP_Products_ID) ) ,2)
													END
												)
        		FROM AP_Products
				WHERE AW_User_Companies_ID = @CompanyID AND
					  On_Hand <> 0
			END
		END
	END--Current Inventory Valuation

	--DECLARE GetData CURSOR
	--FOR
	--SELECT TOP 7 AS_Day_Ends_ID, Day_End
	--FROM AS_Day_Ends
	--WHERE Slu_AW_Active_ID = 1
	--ORDER BY AS_Day_Ends_ID DESC
	
	--OPEN GetData
	--FETCH NEXT FROM GetData INTO @AS_Day_Ends_ID, @Day_End
	--WHILE @@FETCH_STATUS = 0
	--BEGIN

	--	IF NOT EXISTS
	--	(
	--		SELECT 1
	--		FROM AS_Day_End_Summary
	--		WHERE AS_Day_Ends_ID = @AS_Day_Ends_ID 
	--	)

		
	BEGIN--Daily Sales 
		--Exclude Inter-Company Customers
		SELECT
			@Day_ExcIntCompSale = ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0), --AS [NetSales],
			@Day_ExcIntCompCost = ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0), --AS [Cost],
			@Day_ExcIntCompGP = ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0), --AS [GP],
			@Day_ExcIntCompStdGP = CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
				 ELSE 0.00
				 END, --AS [StdGP%],
			@Day_ExcIntCompActGP = CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
				 ELSE 0.00
				 END --AS [ActGP%]
		FROM AS_Transaction_Details d
			INNER JOIN AS_Transactions h
				ON h.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON h.AC_Customers_ID = c.AC_Customers_ID
		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
			   h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
			   h.Day_End = @Day_End AND
			   h.AW_User_Companies_ID = @CompanyID AND
			   c.Sys_AC_Account_Types_ID <> 3
           
		--Include Inter-Company Customers
		SELECT
			@Day_IncIntCompSale = ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0), --AS [NetSales],
			@Day_IncIntCompCost = ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0), --AS [Cost],
			@Day_IncIntCompGP = ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0), --AS [GP],
			@Day_IncIntCompStdGP = CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
				 ELSE 0.00
				 END, --AS [StdGP%],
			@Day_IncIntCompActGP = CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
				 ELSE 0.00
				 END --AS [ActGP%]
		FROM AS_Transaction_Details d
			INNER JOIN AS_Transactions h
				ON h.AS_Transactions_ID = d.AS_Transactions_ID
		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
			   h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
			   h.Day_End = @Day_End AND
			   h.AW_User_Companies_ID = @CompanyID
	END--Daily Sales 

	
	BEGIN--Month Sales 
		--Exclude Inter-Company Customers
		SELECT
			@Month_ExcIntCompSale = ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0), --AS [NetSales],
			@Month_ExcIntCompCost = ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0), --AS [Cost],
			@Month_ExcIntCompGP = ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0), --AS [GP],
			@Month_ExcIntCompStdGP = CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
				 ELSE 0.00
				 END, --AS [StdGP%],
			@Month_ExcIntCompActGP = CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
				 ELSE 0.00
				 END --AS [ActGP%]
		FROM AS_Transaction_Details d
			INNER JOIN AS_Transactions h
				ON h.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON h.AC_Customers_ID = c.AC_Customers_ID
		WHERE h.Date_Captured > @LastPeriodProcedureDate AND
			 (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
			  h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
			  h.AW_User_Companies_ID = @CompanyID AND
			  c.Sys_AC_Account_Types_ID <> 3
			  

		--Include Inter-Company Customers
		SELECT
			@Month_IncIntCompSale = ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0), --AS [NetSales],
			@Month_IncIntCompCost = ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0), --AS [Cost],
			@Month_IncIntCompGP = ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0), --AS [GP],
			@Month_IncIntCompStdGP = CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
				 ELSE 0.00
				 END, --AS [StdGP%],
			@Month_IncIntCompActGP = CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
				 THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
				 ELSE 0.00
				 END --AS [ActGP%]
		FROM AS_Transaction_Details d
			INNER JOIN AS_Transactions h
				ON h.AS_Transactions_ID = d.AS_Transactions_ID
		WHERE h.Date_Captured > @LastPeriodProcedureDate AND
			 (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
			  h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
			  h.AW_User_Companies_ID = @CompanyID
	END--Month Sales 

	BEGIN--Sales By Cashier Report Level 1
		INSERT INTO AS_Day_End_Summary_Cashier
		(
			[AS_Day_Ends_ID],
			[Day_End],
			[CashierID],
			[Cashier],
			[Qty],
			[NetSales],
			[Cost],
			[Total],
			[GP],
			[ActGPer],
			[StdGPPer],

			Changes_Sent,
			[Date_Captured],
			[AW_User_Companies_ID]		
		)
		SELECT
			@AS_Day_Ends_ID,
			@Day_End,  
			h.[User_ID] AS [CashierID],  
			ISNULL(u.FirstName, '') + ' ' +  ISNULL(u.Surname, '') AS [Cashier],  
			CONVERT(money, SUM(ISNULL(d.Quantity,0))) AS [Qty],  

			CONVERT(money, SUM(ISNULL(d.Extended_Amount,0) - ISNULL(d.Tax_Amount,0))) AS [NetSales],  

			CONVERT(money, SUM(ISNULL(d.Unit_Cost,0) * ISNULL(d.Quantity,0))) AS [Cost],  
			CONVERT(money, SUM(ISNULL(d.Extended_Amount,0))) AS [Total],  
			CONVERT(money, SUM((ISNULL(d.Extended_Amount,0) - ISNULL(d.Tax_Amount,0)) - (ISNULL(d.Quantity,0) * ISNULL(d.Unit_Cost,0)))) AS [GP],  
			
			 CASE WHEN SUM( dbo.fn_AS_Calc_Act_Sales_Value( ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0)) ) <> 0       
			 THEN CONVERT(money,(  SUM(dbo.fn_AS_Calc_Act_GP( ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0), ISNULL(d.Quantity,0), ISNULL(d.Unit_Cost,0)) )
						/ SUM( dbo.fn_AS_Calc_Act_Sales_Value( ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0))) * 100)) 
			 ELSE 0.00       
			 END AS [Act GP%],  

			 CASE WHEN SUM( dbo.fn_AS_Calc_Std_Sales_Value( ISNULL(d.Original_Price,0), ISNULL(d.Quantity,0)) ) <> 0       
			 THEN CONVERT(money,( SUM(dbo.fn_AS_Calc_Std_GP( ISNULL(d.Original_Price,0), ISNULL(d.Unit_Cost,0), ISNULL(d.Quantity,0))) 
						/ SUM( dbo.fn_AS_Calc_Std_Sales_Value( ISNULL(d.Original_Price,0), ISNULL(d.Quantity,0))) * 100))       
			 ELSE 0.00       
			 END AS [Std GP%],
			 0,
			 GetDate(),
			 @CompanyID
		FROM AS_Transaction_Details d       
			INNER JOIN AS_Transactions h           
				ON h.AS_Transactions_ID = d.AS_Transactions_ID       
			LEFT JOIN AW_Users u           
				ON h.User_ID = u.AW_Users_ID       
		WHERE d.AW_User_Companies_ID = @CompanyID 
			AND (h.Day_End >= @Day_End AND h.Day_End <= @Day_End) 
			AND (h.Sys_AW_Transaction_Types_ID = 3 OR h.Sys_AW_Transaction_Types_ID = 4) 
		GROUP BY h.[User_ID], ISNULL(u.FirstName, '') + ' ' +  ISNULL(u.Surname, '')      
	END--Sales By Cashier Report Level 1
     
    INSERT INTO AS_Day_End_Summary
    (
		AS_Day_Ends_ID,
		Day_End,
		StockValuation,
		Day_ExcIntCompCost,
		Day_ExcIntCompSale,
		Day_ExcIntCompStdGP,
		Day_ExcIntCompActGP,
		Day_ExcIntCompGP,
			
		Day_IncIntCompCost,
		Day_IncIntCompSale,
		Day_IncIntCompStdGP,
		Day_IncIntCompActGP,
		Day_IncIntCompGP,
			
		Month_ExcIntCompCost,
		Month_ExcIntCompSale,
		Month_ExcIntCompStdGP,
		Month_ExcIntCompActGP,
		Month_ExcIntCompGP,
			
		Month_IncIntCompCost,
		Month_IncIntCompSale,
		Month_IncIntCompStdGP,
		Month_IncIntCompActGP,
		Month_IncIntCompGP,
			
        LastPeriodProcedureDate,
        LastPeriodProcedureMonthID,
        LastPeriodProcedureYearID,

		Changes_Sent,
		Date_Captured,
		AW_User_Companies_ID
    )
    VALUES
    (
		@AS_Day_Ends_ID,
		@Day_End,
		@CurrentInvValuation,
		@Day_ExcIntCompCost,
		@Day_ExcIntCompSale,
		@Day_ExcIntCompStdGP,
		@Day_ExcIntCompActGP,
		@Day_ExcIntCompGP,
			
		@Day_IncIntCompCost,
		@Day_IncIntCompSale,
		@Day_IncIntCompStdGP,
		@Day_IncIntCompActGP,
		@Day_IncIntCompGP,
			
		@Month_ExcIntCompCost,
		@Month_ExcIntCompSale,
		@Month_ExcIntCompStdGP,
		@Month_ExcIntCompActGP,
		@Month_ExcIntCompGP,
			
		@Month_IncIntCompCost,
		@Month_IncIntCompSale,
		@Month_IncIntCompStdGP,
		@Month_IncIntCompActGP,
		@Month_IncIntCompGP,
			
        @LastPeriodProcedureDate,
        @LastPeriodProcedureMonthID,
        @LastPeriodProcedureYearID,

		0,
		GetDate(),
		@CompanyID    
    )
     
                   
	--	END
	--	FETCH NEXT FROM GetData INTO @AS_Day_Ends_ID, @Day_End
	--END
	--CLOSE GetData
	--DEALLOCATE GetData	

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE Procedure [dbo].[sp_AS_Day_End_Summary_Cashier_SEL]
AS

	SELECT	
		'1' + '|' + 
		left('DayEnd' + REPLICATE(' ',19), 19) + '|' +
		--left('Qty' + REPLICATE(' ',10), 10) + '|' +
		--left('NetSales' + REPLICATE(' ',20), 20) + '|' +
		--left('Cost' + REPLICATE(' ',20), 20) + '|' +
		--left('Total' + REPLICATE(' ',20), 20) + '|' +		
		left('GP'+ REPLICATE(' ',20), 20) + '|' +
		left('ActGPer'+ REPLICATE(' ',20), 20) + '|' +
		--left('StdGPPer'+ REPLICATE(' ',20), 20) + '|' +
		left('Cashier' + REPLICATE(' ',100), 100)		
	UNION
	SELECT
		'2' + '|' +  
		left(Convert(Varchar(20),s.Day_End,120) + REPLICATE(' ',19), 19) + '|' +		
		
		--left(Convert(Varchar(10),Qty) + REPLICATE(' ',10), 10) + '|' +		
		--left(Convert(Varchar(20),NetSales) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Cost) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Total) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),GP) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),ActGPer) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),StdGPPer) + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(Cashier,'') + REPLICATE(' ',100), 100)
	FROM AS_Day_End_Summary_Cashier s
		INNER JOIN AS_Day_Ends d
			ON s.AS_Day_Ends_ID = d.AS_Day_Ends_ID
	WHERE Changes_Sent = 0
	AND d.Slu_AW_Active_ID = 1		
	UNION
	SELECT
		'3' + '|' +  
		left(Convert(Varchar(20),s.Day_End,120) + REPLICATE(' ',19), 19) + '|' +		
		
		--left(Convert(Varchar(10),Qty) + REPLICATE(' ',10), 10) + '|' +		
		--left(Convert(Varchar(20),NetSales) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Cost) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Total) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),SUM(GP)) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),CASE WHEN SUM(NetSales) <> 0
				 THEN CONVERT(Decimal(18,2), (SUM(NetSales) - Sum(Cost)) / SUM(NetSales) * 100)
				 ELSE 0.00
				 END) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),StdGPPer) + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL('','') + REPLICATE(' ',100), 100)
	FROM AS_Day_End_Summary_Cashier s
		INNER JOIN AS_Day_Ends d
			ON s.AS_Day_Ends_ID = d.AS_Day_Ends_ID
	WHERE Changes_Sent = 0
	AND d.Slu_AW_Active_ID = 1
	Group BY s.Day_End		



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE Procedure [dbo].[sp_AS_Day_End_Summary_SEL]
AS

	SELECT	
		'1' + '|' + 
		left('DayEnd' + REPLICATE(' ',19), 19) + '|' +
		left('StockValuation' + REPLICATE(' ',20), 20) + '|' +
		--left('DayExcIntCompCost' + REPLICATE(' ',20), 20) + '|' +
		--left('DayExcIntCompSale' + REPLICATE(' ',20), 20) + '|' +
		--left('DayExcIntCompStdGP' + REPLICATE(' ',20), 20) + '|' +
		--left('DayExcIntCompActGP' + REPLICATE(' ',20), 20) + '|' +
		--left('DayExcIntCompGP' + REPLICATE(' ',20), 20) + '|' +	
			
		--left('DayIncIntCompCost'+ REPLICATE(' ',20), 20) + '|' +
		--left('DayIncIntCompSale'+ REPLICATE(' ',20), 20) + '|' +
		--left('DayIncIntCompStdGP'+ REPLICATE(' ',20), 20) + '|' +
		left('DayIncIntCompActGP'+ REPLICATE(' ',20), 20) + '|' +
		left('DayIncIntCompGP'+ REPLICATE(' ',20), 20) + '|' +
		
		--left('MonthExcIntCompCost'+ REPLICATE(' ',20), 20) + '|' +
		--left('MonthExcIntCompSale'+ REPLICATE(' ',20), 20) + '|' +
		--left('MonthExcIntCompStdGP'+ REPLICATE(' ',20), 20) + '|' +
		--left('MonthExcIntCompActGP'+ REPLICATE(' ',20), 20) + '|' +
		--left('MonthExcIntCompGP'+ REPLICATE(' ',20), 20) + '|' +
		
		--left('MonthIncIntCompCost'+ REPLICATE(' ',20), 20) + '|' +
		--left('MonthIncIntCompSale'+ REPLICATE(' ',20), 20) + '|' +
		--left('MonthIncIntCompStdGP'+ REPLICATE(' ',20), 20) + '|' +
		left('MonthIncIntCompActGP'+ REPLICATE(' ',20), 20) + '|' +
		left('MonthIncIntCompGP'+ REPLICATE(' ',20), 20) + '|' +										
		
		left('LastMonthEndDate'+ REPLICATE(' ',19), 19)
	UNION
	SELECT
		'2' + '|' +  
		left(Convert(Varchar(20),s.Day_End,120) + REPLICATE(' ',19), 19) + '|' +		
		left(Convert(Varchar(20),StockValuation) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_ExcIntCompCost) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_ExcIntCompSale) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_ExcIntCompStdGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_ExcIntCompActGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_ExcIntCompGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_IncIntCompCost) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_IncIntCompSale) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Day_IncIntCompStdGP) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),Day_IncIntCompActGP) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),Day_IncIntCompGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_ExcIntCompCost) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_ExcIntCompSale) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_ExcIntCompStdGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_ExcIntCompActGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_ExcIntCompGP) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_IncIntCompCost) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_IncIntCompSale) + REPLICATE(' ',20), 20) + '|' +		
		--left(Convert(Varchar(20),Month_IncIntCompStdGP) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),Month_IncIntCompActGP) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),Month_IncIntCompGP) + REPLICATE(' ',20), 20) + '|' +		
		left(Convert(Varchar(20),LastPeriodProcedureDate,120) + REPLICATE(' ',19), 19)
	FROM AS_Day_End_Summary s
		INNER JOIN AS_Day_Ends d
			ON s.AS_Day_Ends_ID = d.AS_Day_Ends_ID
	WHERE Changes_Sent = 0
	AND d.Slu_AW_Active_ID = 1		
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Delete_Day_End
--Purpose       :DELETE Day-End procedure
--Date          :2011/08/09
--Authors       :TB
--MODS          :
--2004.5.5      :31/10/11 - Fixed Journal_Narration from 'Day End - Sales' to be
--              :           'Day End - Debtors Sales' as it is written in AB_Journals !!!
--              :31/10/11 - Replaced the REVERSAL of the Journal and GL Transactions code
--              :           with DELETE of the Journal and GL Transactions and UPDATING
--              :           the GL Account Balance with the REVERSAL AMOUNT
--              :           This is preferable to reversing a potentially OUT-OF-BALANCE
--              :           GL Transaction and Journal that puts the GL back in balance
--              :03/11/11 - Modified to delete AS_Day-Ends and reset Day-End flag even if
--              :           Day-End journal not found - to enable delete EMPTY Day-Ends
--2004.5.9 RL   :2013-05-06 Added extra Journal_Narrations to find day ends
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Delete_Day_End]
	(
		@DayEndID int,
        @DayEndDate datetime,
		@GLTranRef int,
        @GLTranDate datetime,
        @UserID int,
        @CompanyID int
	)
AS

SET NOCOUNT ON

    DECLARE @JournalID int,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @GLAccountID int,
            @Amount money,
            @Notes varchar(50),
    		@Month tinyint,
    		@Year int,
            @InsertGLTran bit,
            @RetCode int

    SET @RetCode = 0
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0            --0 = Do Not insert a GL Transaction in JNL Details
    SET @JournalID = 0


    SELECT TOP 1 @Month = Slu_AW_Months_ID,
                 @Year = Slu_AW_Years_ID
    FROM AB_GL_Transactions
    WHERE AB_Transaction_Ref = @GLTranRef AND
          Sys_AB_Transaction_Types_ID = 22 AND
          Description = 'Day End - Sales'


    --> STRIP milliseconds using CONVERT(CHAR(19)
    SELECT @JournalID = AB_Journals_ID
    FROM AB_Journals
    WHERE CONVERT(CHAR(19), Journal_Date) = CONVERT(CHAR(19), @GLTranDate) AND
          Journal_Reference = CONVERT(varchar(30), @GLTranRef) AND
	--> Ver 5.9, RL, Added extra Journal_Narrations to find day ends
          Journal_Narration IN ('Day End - Debtors Sales',
                                'Day End - Sales',
                                'Day End - Receipts',
                                'Day End - POS Receipts',
                                'Day End - Total Receipts',
                                'Day End - Settlement Discount',
                                'Day End - Interest Journals',
                                'Day End - OTHER Receipts',
                                'Day End - Consignment Sales',
                                'Day End - Consignment Inentory',
                                'Day End - Consignment VAT')


    IF @JournalID > 0
        BEGIN
        	DECLARE DELETE_DAYEND CURSOR FOR
                (
                    SELECT AB_Accounts_ID,
                           Amount,
                           Notes
                    FROM AB_Journal_Details
                    WHERE AB_Journals_ID = @JournalID
                )

        	OPEN DELETE_DAYEND

            	FETCH NEXT FROM DELETE_DAYEND 
            	INTO
                    @GLAccountID,
                    @Amount,
                    @Notes

            	WHILE @@FETCH_STATUS = 0
            	BEGIN
                    -- NEW CODE - 2004.5.5
                    SET @Amount = @Amount * -1


                    UPDATE AB_Accounts
                    SET AB_Account_Balance = AB_Account_Balance + @Amount
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          AB_Accounts_ID = @GLAccountID 


                    DELETE
                    FROM AB_GL_Transactions
                    WHERE Sys_AB_Transaction_Types_ID = 22 AND
                          AB_Accounts_ID = @GLAccountID AND
                          AB_Transaction_Date = @GLTranDate AND
                          AB_Transaction_Ref = @GLTranRef


                	FETCH NEXT FROM DELETE_DAYEND 
                	INTO
                        @GLAccountID,
                        @Amount,
                        @Notes
                END

        	CLOSE DELETE_DAYEND
        
        	DEALLOCATE DELETE_DAYEND


            --> DELETE the Journal Details - NEW 2004.5.5
            DELETE
            FROM AB_Journal_Details
            WHERE AB_Journals_ID = @JournalID


            --> DELETE the Journal Header - NEW 2004.5.5
            DELETE
            FROM AB_Journals
            WHERE AB_Journals_ID = @JournalID
        END


        --> RESET the Day-End flag
        UPDATE AS_Transactions
        SET Day_End = NULL
        WHERE Day_End = @DayEndDate

        --> RESET the Day-End flag
        UPDATE AS_Till_Payouts
        SET Day_End = NULL
        WHERE Day_End = @DayEndDate

        --> DELETE the Day-End
        DELETE
        FROM AS_Day_Ends
        WHERE AS_Day_Ends_ID = @DayEndID


        SET @RetCode = 1


RETURN @RetCode
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AS_Delete_Sales_Order_Item
--Purpose       :Delete a Sales Order item from AS_Sales_Order_Details
--Date          :08 JUN 2008
--Authors       :TB
--MODS          :
--RL	V6.3	:2017-02-09 - Remove 
---------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Delete_Sales_Order_Item]
    (
        @OrderID				int,
		@AP_Products_ID		    int,
		@Back_Order				decimal(18,3)
    )
AS

SET NOCOUNT ON

	IF @AP_Products_ID <> 0
	BEGIN
		DECLARE @AO_Order_Candidates_ID int,
				@Order_Qty				decimal(9,3)

		SET @AO_Order_Candidates_ID = 0
		SET @Order_Qty = 0
	
		SELECT	@Order_Qty = Qty,
				@AO_Order_Candidates_ID = AO_Order_Candidates_ID
		FROM AO_Order_Candidates
		WHERE AP_Products_ID = @AP_Products_ID
		AND Slu_AW_Active_ID = 1

		--If the sales order raised a Order Candidate we need to remove the qty ordered
		IF @AO_Order_Candidates_ID <> 0
		BEGIN
			--If the Order candidate still exists
			IF @Order_Qty <> 0
			BEGIN
			
				--If Order canidate has the same or less quantity as the back order we can remove the order candidate
				IF (( @Order_Qty = @Back_Order) or (@Order_Qty < @Back_Order) )
				BEGIN
			
					DELETE FROM AO_Order_Candidates WHERE AO_Order_Candidates_ID = @AO_Order_Candidates_ID
			
				END
				ELSE
				BEGIN
					UPDATE AO_Order_Candidates 
					SET Qty = Qty - @Back_Order
					WHERE AO_Order_Candidates_ID = @AO_Order_Candidates_ID
				END
			
			END
		END
	END

	DELETE 
	FROM AS_Sales_Order_Details
	WHERE AS_Sales_Order_Details_ID = @OrderID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








---------------------------------------------------------------------------------
--Description   :sp_AS_Delete_Sales_Order_Product
--Purpose       :Delete a Sales Order Product from AS_Transaction_Details
--Date          :18 JUN 2008
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE             Procedure sp_AS_Delete_Sales_Order_Product
    (
        @TranDetailID int
    )

AS

SET NOCOUNT ON


	DELETE 
	FROM AS_Transaction_Details
	WHERE AS_Transaction_Details_ID = @TranDetailID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description	:sp_AS_Document_Deactivate
--Purpose       :De-Activates documents after Recall in AS_Transactions
--              :    to De-Activate Quotes, Jobcards etc.
--              :    BY SETTING ACTIVE FLAG = 0
--Date			:2002/11/12
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AS_Document_Deactivate
	(
		@TransactionID int
	)
AS

SET NOCOUNT ON

	DECLARE @DocumentTypeID int

	SELECT @DocumentTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TransactionID

    IF @DocumentTypeID = 1 OR @DocumentTypeID = 2    --Quotes, Job Cards
        BEGIN
        	UPDATE AS_Transactions
            SET Slu_AW_Active_ID = 0
            WHERE AS_Transactions_ID = @TransactionID
        END


SET NOCOUNT OFF
	







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AS_Drop_Enterprise_Customer_Sales
--Purpose       :Drops and re-creates AS_Enterprise_Customer_Sales table
--Date          :2007/03/16
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AS_Drop_Enterprise_Customer_Sales

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Customer_Sales]

    
    CREATE TABLE [dbo].[AS_Enterprise_Customer_Sales] (
    	[AS_Enterprise_Customer_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Customer_Sales_Search] ON [dbo].[AS_Enterprise_Customer_Sales]([Filter], [Customer], [CustNo]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Enterprise_Customer_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Customer_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Customer_Sales_ID]
    	)  ON [PRIMARY] 




    SET @ReturnValue = 1


RETURN @ReturnValue














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AS_Drop_Enterprise_GP
--Purpose       :Drops and re-creates AS_Enterprise_GP table
--Date          :2009/09/04
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AS_Drop_Enterprise_GP

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AS_Enterprise_GP]


        CREATE TABLE [dbo].[AS_Enterprise_GP] (
        	[AS_Enterprise_GP_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[TotalSales] [money] NULL ,
        	[TotalCost] [money] NULL ,
        	[Total] [money] NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]


         CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_GP_Search] ON [dbo].[AS_Enterprise_GP]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]


        ALTER TABLE [dbo].[AS_Enterprise_GP] ADD 
        	CONSTRAINT [PK_AS_Enterprise_GP] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AS_Enterprise_GP_ID]
        	)  ON [PRIMARY] 


        setuser


        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_GP].[Pack_Size]'


        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[Total]'


        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalCost]'


        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalSales]'


        setuser



    SET @ReturnValue = 1


RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AS_Drop_Enterprise_Sales
--Purpose       :Drops and re-creates AS_Enterprise_Sales table
--Date          :2007/03/12
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_Drop_Enterprise_Sales

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AS_Enterprise_Sales]

        
        CREATE TABLE [dbo].[AS_Enterprise_Sales] (
        	[AS_Enterprise_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [money] NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_Search] ON [dbo].[AS_Enterprise_Sales]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AS_Enterprise_Sales] ADD 
        	CONSTRAINT [PK_AS_Enterprise_Sales] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AS_Enterprise_Sales_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Drop_Enterprise_Sales_All
--Purpose       :Drops and re-creates AS_Enterprise_Sales_All table
--Date          :2009/09/30
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AS_Drop_Enterprise_Sales_All

AS


    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AS_Enterprise_Sales_All]

        
        CREATE TABLE [dbo].[AS_Enterprise_Sales_All] (
        	[AS_Enterprise_Sales_All_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Pack_Size] [decimal](9, 3) NULL ,
        	[Total] [money] NULL ,
        	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
        ) ON [PRIMARY]

        
        CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_All_Search] ON [dbo].[AS_Enterprise_Sales_All]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AS_Enterprise_Sales_All] ADD 
        	CONSTRAINT [PK_AS_Enterprise_Sales_All] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AS_Enterprise_Sales_All_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales_All].[Pack_Size]'

        
        setuser






    SET @ReturnValue = 1


RETURN @ReturnValue
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AS_Edit_Transaction_References_Header
--Purpose       :Selects POS Transaction Header for Document References Edit
--Date          :2008/10/26
--Authors       :TB
--MODS          :
--2004.4.7      :13/09/09 - Added new Stock Transfer transaction type = 23
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_AS_Edit_Transaction_References_Header
	(
        @CustomerID int,
        @SearchString varchar(50),
        @Filter1 varchar(50) = NULL,
        @Filter2 varchar(50) = NULL,
        @Filter3 varchar(50) = NULL,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON


    --> Specific Transaction Type
    IF @TransactionTypeID <> 0
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [No],
                t.Customer_Reference AS [Ref No],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                t.Comment AS [Comment],
               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.AC_Customers_ID = @CustomerID AND
                  t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
            ORDER BY t.Transaction_Date DESC
        END

    --> ALL Transaction Types
    ELSE
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [No],
                t.Customer_Reference AS [Ref No],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                t.Comment AS [Comment],
               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.AC_Customers_ID = @CustomerID AND
                 (t.Sys_AW_Transaction_Types_ID = 1 or
                  t.Sys_AW_Transaction_Types_ID = 2 or 
                  t.Sys_AW_Transaction_Types_ID = 3 or 
                  t.Sys_AW_Transaction_Types_ID = 4 or 
                  t.Sys_AW_Transaction_Types_ID = 5 or 
                  t.Sys_AW_Transaction_Types_ID = 7 or 
                  t.Sys_AW_Transaction_Types_ID = 15 or 
                  t.Sys_AW_Transaction_Types_ID = 16 or 
                  t.Sys_AW_Transaction_Types_ID = 18 or
                  t.Sys_AW_Transaction_Types_ID = 21 or 
                  t.Sys_AW_Transaction_Types_ID = 22 or 
                  t.Sys_AW_Transaction_Types_ID = 23) AND
                  DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
            ORDER BY t.Transaction_Date DESC
        END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_AS_Enterprise_GP
--Description   :was sp_AP_Select_Enterprise_Stock_Replenish_Max
--Purpose       :FILTER Enterprise Gross Profit
--Functionality :Options: using Last, Average, or Standard Cost
--              :         excluding Inter-Company
--Date          :2009/09/04
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AS_Enterprise_GP
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @Filter varchar(100),
        @ExclInterCo tinyint,
        @ExclNonStock tinyint,
        @AssignSecondary tinyint,
        @GPType tinyint,
        @FetchType tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @SecondaryCostMethod smallint


    --> Get Secondary Costing method (Zero Primary Cost override)
    SELECT @SecondaryCostMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optZeroCostOverride' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


    SET @sql = ' SELECT '
    SET @sql = @sql + ' MAX(d.AW_User_Companies_ID) AS [CompanyID], '
    SET @sql = @sql + ' MAX(p.Description) AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.Supplier_Name AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.Description AS [Filter], '

    SET @sql = @sql + ' SUM(CONVERT(money, d.Extended_Amount - d.Tax_Amount)) AS [NetSales], '

    --> Actual GP
    SET @sql = @sql + ' SUM(CONVERT(money, d.Unit_Cost * d.Quantity)) AS [ActCost], '
    SET @sql = @sql + ' SUM(CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost))) AS [ActGP], '
    SET @sql = @sql + ' CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + ' END AS [ActGPPerc], '


    --> Standard GP
    IF @AssignSecondary = 0    --> DO NOT Assign Secondary
        BEGIN
            SET @sql = @sql + ' SUM(CONVERT(money, ISNULL(p.Standard_Cost, 0) * d.Quantity)) AS [StdCost], '
            SET @sql = @sql + ' SUM(CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * ISNULL(p.Standard_Cost, 0)))) AS [StdGP], '
            SET @sql = @sql + ' CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, ISNULL(p.Standard_Cost, 0)))) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100)) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + ' END AS [StdGPPerc] '
        END
    ELSE                       --> Assign Secondary
        BEGIN
            IF @SecondaryCostMethod = 0    --> Average Cost
                BEGIN
                    SET @sql = @sql + ' SUM(CONVERT(money, d.Quantity * '
                    SET @sql = @sql + '     CASE WHEN ISNULL(p.Standard_Cost, 0) = 0 '
                    SET @sql = @sql + '          THEN ISNULL(p.Average_Cost, 0) '
                    SET @sql = @sql + '          ELSE ISNULL(p.Standard_Cost, 0) '
                    SET @sql = @sql + '     END)) AS [StdCost], '

                    SET @sql = @sql + ' SUM(CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * '
                    SET @sql = @sql + '     CASE WHEN ISNULL(p.Standard_Cost, 0) = 0 '
                    SET @sql = @sql + '          THEN ISNULL(p.Average_Cost, 0) '
                    SET @sql = @sql + '          ELSE ISNULL(p.Standard_Cost, 0) '
                    SET @sql = @sql + '     END))) AS [StdGP], '

                    SET @sql = @sql + ' CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0 '
                    SET @sql = @sql + '      THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, '
                    SET @sql = @sql + '           CASE WHEN ISNULL(p.Standard_Cost, 0) = 0 '
                    SET @sql = @sql + '                THEN ISNULL(p.Average_Cost, 0) '
                    SET @sql = @sql + '                ELSE ISNULL(p.Standard_Cost, 0) '
                    SET @sql = @sql + '           END))) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100)) '
                    SET @sql = @sql + '      ELSE 0.00 '
                    SET @sql = @sql + ' END AS [StdGPPerc] '
                END
            ELSE
            IF @SecondaryCostMethod = 1    --> Last Cost
                BEGIN
                    SET @sql = @sql + ' SUM(CONVERT(money, d.Quantity * '
                    SET @sql = @sql + '     CASE WHEN ISNULL(p.Standard_Cost, 0) = 0 '
                    SET @sql = @sql + '          THEN ISNULL(p.Last_Cost, 0) '
                    SET @sql = @sql + '          ELSE ISNULL(p.Standard_Cost, 0) '
                    SET @sql = @sql + '     END)) AS [StdCost], '

                    SET @sql = @sql + ' SUM(CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * '
                    SET @sql = @sql + '     CASE WHEN ISNULL(p.Standard_Cost, 0) = 0 '
                    SET @sql = @sql + '          THEN ISNULL(p.Last_Cost, 0) '
                    SET @sql = @sql + '          ELSE ISNULL(p.Standard_Cost, 0) '
                    SET @sql = @sql + '     END))) AS [StdGP], '

                    SET @sql = @sql + ' CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0 '
                    SET @sql = @sql + '      THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, '
                    SET @sql = @sql + '           CASE WHEN ISNULL(p.Standard_Cost, 0) = 0 '
                    SET @sql = @sql + '                THEN ISNULL(p.Last_Cost, 0) '
                    SET @sql = @sql + '                ELSE ISNULL(p.Standard_Cost, 0) '
                    SET @sql = @sql + '           END))) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100)) '
                    SET @sql = @sql + '      ELSE 0.00 '
                    SET @sql = @sql + ' END AS [StdGPPerc] '
                END
            ELSE                           --> Standard Cost
                BEGIN
                    SET @sql = @sql + ' CONVERT(money, ISNULL(p.Standard_Cost, 0) * d.Quantity) AS [StdCost], '
                    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * ISNULL(p.Standard_Cost, 0))) AS [StdGP], '
                    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
                    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, ISNULL(p.Standard_Cost, 0))) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
                    SET @sql = @sql + '      ELSE 0.00 '
                    SET @sql = @sql + ' END AS [StdGPPerc] '
                END
        END


    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + ' INNER JOIN AS_Transactions h '
    SET @sql = @sql + '     ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + ' INNER JOIN AP_Products p '
    SET @sql = @sql + '     ON d.AP_Products_ID = p.AP_Products_ID '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' INNER JOIN AC_Customers c '
            SET @sql = @sql + '     ON h.AC_Customers_ID = c.AC_Customers_ID '
        END


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND  h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
    SET @sql = @sql + ' AND  h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    SET @sql = @sql + ' AND (h.Sys_AW_Transaction_Types_ID = 3  '
    SET @sql = @sql + '  OR  h.Sys_AW_Transaction_Types_ID = 4) '

    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @ExclNonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Filter = 'Supplier'
        BEGIN
            SET @sql = @sql + ' GROUP BY p.Product_Code, p.Pack_Size, o.Supplier_Name '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' GROUP BY p.Product_Code, p.Pack_Size, o.Description '
        END


    SET @sql = @sql + ' ORDER BY [Filter], [Product] '



EXEC (@sql)



SET NOCOUNT OFF	























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Enterprise_Sales_All
--Description   :Enterprise Sales All by Filter
--Functionality :excludes Inter-Company
--Date          :2009/09/30
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AS_Enterprise_Sales_All
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @Filter varchar(100),
        @ExclInterCo tinyint,
        @ExclNonStock tinyint,
        @FetchType tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @Filter = 'Type'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' o.Supplier_Name AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' o.Description AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' o.Description AS [Filter], '


    IF @FetchType = 1
        BEGIN
            SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [Sales] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ISNULL(d.Quantity, 0) AS [Sales] '
        END


    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + ' INNER JOIN AS_Transactions h '
    SET @sql = @sql + '     ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + ' INNER JOIN AP_Products p '
    SET @sql = @sql + '     ON d.AP_Products_ID = p.AP_Products_ID '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' INNER JOIN AC_Customers c '
            SET @sql = @sql + '     ON h.AC_Customers_ID = c.AC_Customers_ID '
        END


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND  h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
    SET @sql = @sql + ' AND  h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    SET @sql = @sql + ' AND (h.Sys_AW_Transaction_Types_ID = 3  '
    SET @sql = @sql + '  OR  h.Sys_AW_Transaction_Types_ID = 4) '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @ExclNonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    SET @sql = @sql + ' ORDER BY [Filter], [Product] '



EXEC (@sql)



SET NOCOUNT OFF	






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













---------------------------------------------------------------------------------
--Description   :sp_AS_Enterprise_Sales_Search_Lups
--Purpose       :Returns ONLY ACTIVE Lookups
--Date          :2007/03/12
--Authors       :TB
--MODS:         :
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Enterprise_Sales_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]





SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















--sp_AS_Filter_Enterprise_Customer_Sales 1, '2007/03/01 12:00:01 AM ', '2007/03/12 11:59:59 PM', 1, 1, 1, 1
-------------------------------------------------------------------------------
--Description   :sp_AS_Filter_Enterprise_Customer_Sales
--Purpose       :FILTER Enterprise Sales
--Functionality :Uses filter DESCRIPTIONS
--Date          :2007/03/16
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_Filter_Enterprise_Customer_Sales
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @Filter varchar(100),
        @Sort tinyint
	)
   
AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' c.AC_Customers_ID AS [ID], '
    SET @sql = @sql + ' MAX(c.Surname) AS [Customer], '
--    SET @sql = @sql + ' MAX(RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('', '' + c.Firstnames, '''')))) AS [Customer], '

    SET @sql = @sql + ' MAX(ISNULL(c.Customer_Number, '''')) AS [CustNo], '

    SET @sql = @sql + ' MAX(o.[Description]) AS [Filter], '

    SET @sql = @sql + ' SUM(ISNULL(t.Amount, 0)) AS [Value] '

    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = t.AC_Customers_ID '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Customer_Types o ' +
            '     ON o.Lup_AC_Customer_Types_ID = c.Lup_AC_Customer_Types_ID '
    ELSE
    IF @Filter = 'Group'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Customer_Groups o ' +
            '     ON o.Lup_AC_Customer_Groups_ID = c.Lup_AC_Customer_Groups_ID '
    ELSE
    IF @Filter = 'AcctType'
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Account_Types o ' +
            '     ON o.Sys_AC_Account_Types_ID = c.Sys_AC_Account_Types_ID '
    ELSE
    IF @Filter = 'Status'
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Account_Status o ' +
            '     ON o.Sys_AC_Account_Status_ID = c.Sys_AC_Account_Status_ID '


    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND  t.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
    SET @sql = @sql + '  AND  t.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 3  '
    SET @sql = @sql + '   OR  t.Sys_AW_Transaction_Types_ID = 4) '

    SET @sql = @sql + ' GROUP BY c.AC_Customers_ID  '


    IF @Sort = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Customer] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [CustNo] '
        END

EXEC (@sql)



SET NOCOUNT OFF	











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















--sp_AS_Filter_Enterprise_Sales 1, '2007/03/01 12:00:01 AM ', '2007/03/12 11:59:59 PM', 'Dunlop', '', '', '', '', '', 1, 1 
-------------------------------------------------------------------------------
--Description   :sp_AS_Filter_Enterprise_Sales
--Purpose       :FILTER Enterprise Sales
--Functionality :Uses filter DESCRIPTIONS
--Date          :2007/03/12
--Authors       :TB
--MODS:         :
--2004.4.8      :03/07/10 - Added @ExclInterCo parameter
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Filter_Enterprise_Sales
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @Manuf varchar(50) = '',
        @Type varchar(50) = '',
        @Group varchar(50) = '',
        @Department varchar(50) = '',
        @Supplier varchar(50) = '',
        @Location varchar(50) = '',
        @FetchType tinyint,
        @ExclInterCo tinyint,
        @Sort tinyint,
        @NonStock tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @ManufID int,
            @TypeID int,
            @GroupID int,
            @DepartmentID int,
            @SupplierID int,
            @LocationID int,
            @Filter varchar(4000),
            @sql varchar(8000),
            @RetCode int


	SET @Filter = ''
    SET @sql = ''


--> Manufacturer
	IF @Manuf <> ''
		BEGIN
            --> Get Manufacturer ID
            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
        
            IF @ManufID IS NULL OR @ManufID = 0
                BEGIN
                    SET @Manuf = ''
                END
        END

--> Supplier
	IF @Supplier <> ''
		BEGIN
            --> Get Supplier ID
            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
        
            IF @SupplierID IS NULL OR @SupplierID = 0
                BEGIN
                    SET @Supplier = ''
                END
        END

--> Type
	IF @Type <> ''
		BEGIN
            --> Get Product Type ID
            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
        
            IF @TypeID IS NULL OR @TypeID = 0
                BEGIN
                    SET @Type = ''
                END
        END

--> Group
	IF @Group <> ''
		BEGIN
            --> Get Product Group ID
            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
        
            IF @GroupID IS NULL OR @GroupID = 0
                BEGIN
                    SET @Group = ''
                END
        END

--> Department
	IF @Department <> ''
		BEGIN
            --> Get Product Department ID
            SELECT TOP 1 @DepartmentID = Lup_AP_Product_Departments_ID
            FROM Lup_AP_Product_Departments
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Department AND
                  Slu_AW_Active_ID = 1
        
            IF @DepartmentID IS NULL OR @DepartmentID = 0
                BEGIN
                    SET @Department = ''
                END
        END

--> Location
	IF @Location <> ''
		BEGIN
            --> Get Product Location ID
            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
        
            IF @LocationID IS NULL OR @LocationID = 0
                BEGIN
                    SET @Location = ''
                END
        END



--> Manufacturer
	IF @Manuf <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufID)
		END
--> Type
	IF @Type <> ''
		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 @Group <> ''
		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 @Department <> ''
		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 @Supplier <> ''
		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 @Location <> ''
		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


--> 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)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @FetchType = 0
        BEGIN
            SET @sql = @sql + ' ISNULL(td.Quantity, 0) AS [Value], '
        END

    ELSE
    IF @FetchType = 1
        BEGIN
            SET @sql = @sql + ' ISNULL(td.Extended_Amount, 0) - ISNULL(Tax_Amount, 0) AS [Value], '
        END

    SET @sql = @sql + ' m.[Description] AS [Manuf], '
    SET @sql = @sql + ' t.[Description] AS [Type], '
    SET @sql = @sql + ' g.[Description] AS [Group], '
    SET @sql = @sql + ' d.[Description] AS [Department], '
    SET @sql = @sql + ' s.[Supplier_Name] AS [Supplier], '
    SET @sql = @sql + ' l.[Description] AS [Location] '


    SET @sql = @sql + ' FROM AS_Transactions th '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Details td '
    SET @sql = @sql + '     ON td.AS_Transactions_ID = th.AS_Transactions_ID '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' INNER JOIN AC_Customers c '
            SET @sql = @sql + '     ON th.AC_Customers_ID = c.AC_Customers_ID '
        END


    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + '     ON p.AP_Products_ID = td.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Types t '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Groups g '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Groups_ID = g.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Departments d '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Departments_ID = d.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '     ON p.Default_Supplier_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Locations l '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Locations_ID = l.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + @Filter

    SET @sql = @sql + ' AND  th.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
    SET @sql = @sql + ' AND  th.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    SET @sql = @sql + ' AND (th.Sys_AW_Transaction_Types_ID = 3  '
    SET @sql = @sql + '  OR  th.Sys_AW_Transaction_Types_ID = 4) '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Manuf], [Type], [Group], [Department], [Supplier], [Location], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Manuf], [Type], [Group], [Department], [Supplier], [Location], [Product] '
        END

    ----------------------------------
    -- If NO FILTERS FOUND then EXIT    
    ----------------------------------
    IF @Manuf = '' AND
       @Type = '' AND
       @Group = '' AND
       @Department = '' AND
       @Supplier = '' AND
       @Location = ''

        RETURN
    ----------------------------------


--PRINT @sql

EXEC (@sql)



SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_Get_Commission_Category
--Purpose       :
--Functionality :Tables: Lup_AS_Commission_Categories
--Parameters    : 
--Date          :2002/02/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------


CREATE       PROCEDURE sp_AS_Get_Commission_Category
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

-- 	SELECT Lup_AS_Commission_Categories_ID AS [ID],
--            [Description] AS [Commission Category],
--            Date_Captured AS [Date],        --[Date Captured],
--            [User_ID] AS [User ID],
--            Slu_AW_Active_ID AS [Active]
-- 	FROM Lup_AS_Commission_Categories
-- 	WHERE AW_User_Companies_ID = @Company_ID

	SELECT a.Lup_AS_Commission_Categories_ID AS [ID],
           a.[Description] AS [Commission Category],
           a.Date_Captured AS [Date],
            CASE WHEN b.Surname IS NULL and b.FirstName IS NULL
                     THEN ISNULL(b.Surname,'')
                 WHEN b.Surname IS NOT NULL and b.FirstName IS NULL
                     THEN ISNULL(b.Surname,'')
                 ELSE ISNULL(b.Surname,'') + ', ' + 
                      LTRIM(ISNULL(b.FirstName,''))
                 END AS [User],
            c.Description AS [Active]
	FROM Lup_AS_Commission_Categories a
		INNER JOIN AW_users b
            ON a.User_ID = b.AW_Users_ID
        INNER JOIN dbo.Slu_AW_Active c
            ON a.Slu_AW_Active_ID = c.Slu_AW_Active_ID
	WHERE AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_Get_Commission_Category_Per_Group
--Purpose       :Returns the Commission Categories for the selected Group
--Functionality :
--Parameters    :
--Date          :2002/02/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AS_Get_Commission_Category_Per_Group
    (
    	@GroupID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

-- 	SELECT a.AS_Commission_Categories_Groups_ID AS [ID],
--     	   a.Lup_AP_Commission_Groups_ID AS [FK ID],
--     	   b.[Description] AS [Commission Category],
--     	   a.Commission_Percentage AS [Comm %],    --[Percentage],
--     	   a.Date_Captured AS [Date],              --[Date Captured],
--     	   a.[User_ID] AS [User ID],
--     	   a.Slu_AW_Active_ID AS [Active]
-- 	FROM AS_Commission_Categories_Groups a
--         INNER JOIN Lup_AS_Commission_Categories b 
-- 	        ON a.Lup_AS_Commission_Categories_ID = b.Lup_AS_Commission_Categories_ID
-- 	WHERE a.Lup_AP_Commission_Groups_ID = @GroupID AND
--           a.AW_User_Companies_ID = @Company_ID

	SELECT a.AS_Commission_Categories_Groups_ID AS [ID],
    	   a.Lup_AP_Commission_Groups_ID AS [FK ID],
    	   b.[Description] AS [Commission Category],
    	   a.Commission_Percentage AS [Comm %],    --[Percentage],
    	   a.Date_Captured AS [Date],              --[Date Captured],
            CASE WHEN c.Surname IS NULL and c.FirstName IS NULL
                     THEN ISNULL(c.Surname,'')
                 WHEN c.Surname IS NOT NULL and c.FirstName IS NULL
                     THEN ISNULL(c.Surname,'')
                 ELSE ISNULL(c.Surname,'') + ', ' + 
                      LTRIM(ISNULL(c.FirstName,''))
                 END AS [User],
            d.Description AS [Active]
	FROM AS_Commission_Categories_Groups a
        INNER JOIN Lup_AS_Commission_Categories b 
	        ON a.Lup_AS_Commission_Categories_ID = b.Lup_AS_Commission_Categories_ID
		INNER JOIN AW_users c
            ON a.User_ID = c.AW_Users_ID
        INNER JOIN dbo.Slu_AW_Active d
            ON a.Slu_AW_Active_ID = d.Slu_AW_Active_ID
	WHERE a.Lup_AP_Commission_Groups_ID = @GroupID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











--Description   :sp_AS_Get_Group_Per_Commission_Category
--Purpose       :Returns the group Categories for the selected discount
--Functionality :
--Parameters    :@CommCategoryID
--Date          : 2001/08/21
--Version       :1.0.0

CREATE       PROCEDURE sp_AS_Get_Group_Per_Commission_Category
    (
    	@CommCategoryID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

--  MOD maybe cannot update RS because of joins
-- 	SELECT a.AS_Commission_Categories_Groups_ID AS [ID],
-- 		b.[Description] AS [Commission Group],
-- 		a.Lup_AS_Commission_Categories_ID AS [FK ID],
-- 		a.Commission_Percentage AS [Percentage],
-- 		a.Date_Captured AS [Date Captured],
--         CASE WHEN c.Surname IS NULL and c.FirstName IS NULL
--             THEN ISNULL(c.Surname,'')
--             ELSE ISNULL(c.Surname,'') + ', ' + 
--                  LTRIM(ISNULL(c.FirstName,''))
--             END as [User],
--         d.Description  AS [Active]
-- 	FROM AS_Commission_Categories_Groups a
--         INNER JOIN Lup_AP_Commission_Groups b
--             ON a.Lup_AP_Commission_Groups_ID = b.Lup_AP_Commission_Groups_ID
-- 		INNER JOIN AW_users c
--             ON a.User_ID = c.AW_Users_ID
--         INNER JOIN Slu_AW_Active d
--             ON a.Slu_AW_Active_ID = d.Slu_AW_Active_ID
-- 	WHERE a.Lup_AS_Commission_Categories_ID = @CommCategoryID AND
-- 	      a.AW_User_Companies_ID = @Company_ID

	SELECT a.AS_Commission_Categories_Groups_ID AS [ID],
		b.[Description] AS [Commission Group],
		a.Lup_AS_Commission_Categories_ID AS [FK ID],
		a.Commission_Percentage AS [Comm %],        --[Percentage],
		a.Date_Captured AS [Date],                  --[Date Captured],
		a.[User_ID] AS [User ID],
--		a.AW_User_Companies_ID AS [Company],
		a.Slu_AW_Active_ID AS [Active]
	FROM AS_Commission_Categories_Groups a
        INNER JOIN Lup_AP_Commission_Groups b
            ON b.Lup_AP_Commission_Groups_ID = a.Lup_AP_Commission_Groups_ID
	WHERE a.Lup_AS_Commission_Categories_ID = @CommCategoryID AND
          a.AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













---------------------------------------------------------------------------------
--Description   :sp_AS_Get_Post_Code_Shipping_Rate
--Purpose       :Get the Tax Rate for the selected Tax Code
--Date          :2008/06/20
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Get_Post_Code_Shipping_Rate
    (
        @PostCode varchar(10),
        @ShipRateKG money OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @ShipRateKG = ISNULL(Rate_Per_Kg, 0)
    FROM Slu_AW_Shipping_Rates
    WHERE Post_Code = @PostCode














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














---------------------------------------------------------------------------------
--Description   :sp_AS_Get_Document_No_From_ID
--Purpose       :Get the Transaction_Number From AS_Transactions_ID
--Date          :2008/06/21
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Get_Transaction_No_From_ID
    (
        @TranID int,
        @TranNo varchar(19) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @TranNo = ISNULL(Transaction_Number, '')
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TranID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   : sp_AS_Insert_Commission_Categories_Groups
--Purpose       : Cartesian Product Insert - uses CROSS JOIN
--              : for a newly added Lup_AS_Commission_Categories record into
--              : AS_Commission_Categories_Groups
--Functionality : Tables: Lup_AP_Commission_Groups, Lup_AS_Commission_Categories
--Parameters    : 
--Date          : 2002/02/07
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE    PROCEDURE  sp_AS_Insert_Commission_Categories_Groups
    (
        @CategoryOrGroupID smallint,
        @CompanyID int,
        @UserID int,
        @Option bit
    )

AS

SET NOCOUNT ON

    DECLARE @cnt int

    IF @Option = 0    --A LUP_AP_COMMISSION_GROUPS_ID has been inserted
        BEGIN
            SELECT @cnt = count(*)
            FROM Lup_AS_Commission_Categories
        
            IF @cnt > 0    -- Some Lup_AS_Commission_Categories exist
                BEGIN
                	INSERT AS_Commission_Categories_Groups
                        (
                            Lup_AS_Commission_Categories_ID,
                            Lup_AP_Commission_Groups_ID,
                            Commission_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT b.Lup_AS_Commission_Categories_ID,
                           a.Lup_AP_Commission_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AP_Commission_Groups a
                         CROSS JOIN Lup_AS_Commission_Categories b
                    WHERE a.Lup_AP_Commission_Groups_ID = @CategoryOrGroupID
                END
            ELSE        -- Create at least one Lup_AS_Commission_Categories
                BEGIN
                    INSERT Lup_AS_Commission_Categories
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT '<None>',
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
        
                    INSERT AS_Commission_Categories_Groups
                        (
                            Lup_AS_Commission_Categories_ID,
                            Lup_AP_Commission_Groups_ID,
                            Commission_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT b.Lup_AS_Commission_Categories_ID,
                           a.Lup_AP_Commission_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AP_Commission_Groups a
                         CROSS JOIN Lup_AS_Commission_Categories b
                    WHERE a.Lup_AP_Commission_Groups_ID = @CategoryOrGroupID
                END       
        END
    ELSE
    IF @Option = 1    --A LUP_AS_COMMISSION_CATEGORIES_ID has been inserted
        BEGIN
            SELECT @cnt = count(*)
            FROM Lup_AP_Commission_Groups
        
            IF @cnt > 0    -- Some Lup_AP_Commission_Groups exist
                BEGIN
                	INSERT AS_Commission_Categories_Groups
                        (
                            Lup_AS_Commission_Categories_ID,
                            Lup_AP_Commission_Groups_ID,
                            Commission_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT a.Lup_AS_Commission_Categories_ID,
                           b.Lup_AP_Commission_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AS_Commission_Categories a
                         CROSS JOIN Lup_AP_Commission_Groups b
                    WHERE a.Lup_AS_Commission_Categories_ID = @CategoryOrGroupID
        
                END
            ELSE        -- Create at least one Lup_AS_Commission_Categories
                BEGIN
                    INSERT Lup_AP_Commission_Groups
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT '<None>',
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
        
                	   INSERT AS_Commission_Categories_Groups    --there were 25
                        (
                            Lup_AS_Commission_Categories_ID,
                            Lup_AP_Commission_Groups_ID,
                            Commission_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT a.Lup_AS_Commission_Categories_ID,
                           b.Lup_AP_Commission_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AS_Commission_Categories a
                         CROSS JOIN Lup_AP_Commission_Groups b
                    WHERE a.Lup_AS_Commission_Categories_ID = @CategoryOrGroupID
        
                END       
        END 

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   : sp_AS_Insert_Discount_Categories_Groups
--Purpose       : Cartesian Product Insert - uses CROSS JOIN
--              : for a newly added Lup_AC_Discount_Categories record into
--              : AS_Discount_Categories_Groups
--Functionality : Tables: Lup_AP_Discount_Groups, Lup_AC_Discount_Categories
--Parameters    : 
--Date          : 2002/02/09
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE     PROCEDURE  sp_AS_Insert_Discount_Categories_Groups
    (
        @CategoryOrGroupID smallint,
        @CompanyID int,
        @UserID int,
        @Option bit
    )

AS

SET NOCOUNT ON

    DECLARE @cnt int

    IF @Option = 0    --A LUP_AP_Discount_GROUPS_ID has been inserted
        BEGIN
            SELECT @cnt = count(*)
            FROM Lup_AC_Discount_Categories
        
            IF @cnt > 0    -- Some Lup_AC_Discount_Categories exist
                BEGIN
                	INSERT AS_Discount_Categories_Groups
                        (
                            Lup_AC_Discount_Categories_ID,
                            Lup_AP_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT b.Lup_AC_Discount_Categories_ID,
                           a.Lup_AP_Discount_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AP_Discount_Groups a
                         CROSS JOIN Lup_AC_Discount_Categories b
                    WHERE a.Lup_AP_Discount_Groups_ID = @CategoryOrGroupID
                END
            ELSE        -- Create at least one Lup_AC_Discount_Categories
                BEGIN
                    INSERT Lup_AC_Discount_Categories
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT '<None>',
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
        
                    INSERT AS_Discount_Categories_Groups
                        (
                            Lup_AC_Discount_Categories_ID,
                            Lup_AP_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT b.Lup_AC_Discount_Categories_ID,
                           a.Lup_AP_Discount_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AP_Discount_Groups a
                         CROSS JOIN Lup_AC_Discount_Categories b
                    WHERE a.Lup_AP_Discount_Groups_ID = @CategoryOrGroupID
                END       
        END
    ELSE
    IF @Option = 1    --A Lup_AC_Discount_Categories_ID has been inserted
        BEGIN
            SELECT @cnt = count(*)
            FROM Lup_AP_Discount_Groups
        
            IF @cnt > 0    -- Some Lup_AP_Discount_Groups exist
                BEGIN
                	INSERT AS_Discount_Categories_Groups
                        (
                            Lup_AC_Discount_Categories_ID,
                            Lup_AP_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT a.Lup_AC_Discount_Categories_ID,
                           b.Lup_AP_Discount_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AC_Discount_Categories a
                         CROSS JOIN Lup_AP_Discount_Groups b
                    WHERE a.Lup_AC_Discount_Categories_ID = @CategoryOrGroupID
        
                END
            ELSE        -- Create at least one Lup_AC_Discount_Categories
                BEGIN
                    INSERT Lup_AP_Discount_Groups
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT '<None>',
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
        
                	   INSERT AS_Discount_Categories_Groups    --there were 25
                        (
                            Lup_AC_Discount_Categories_ID,
                            Lup_AP_Discount_Groups_ID,
                            Discount_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT a.Lup_AC_Discount_Categories_ID,
                           b.Lup_AP_Discount_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AC_Discount_Categories a
                         CROSS JOIN Lup_AP_Discount_Groups b
                    WHERE a.Lup_AC_Discount_Categories_ID = @CategoryOrGroupID
        
                END       
        END 

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















--sp_AS_Insert_Enterprise_Customer_Sales 'ADV2004', 'Autowiel Menlyn', '000-111', 'Inter-Company', 2345.66

-------------------------------------------------------------------------------
--Description   :sp_AS_Insert_Enterprise_Customer_Sales
--Purpose       :INSERT Enterprise Customer Sales
--Date          :2007/03/16
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AS_Insert_Enterprise_Customer_Sales
	(
        @ColumnName varchar(50),
        @Customer varchar(50),
        @CustNo varchar(20),
        @Filter varchar(50),
        @Value money
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @CustSalesID int


    SET @CustSalesID = 0
    SET @sql = ' '


    SELECT @CustSalesID = AS_Enterprise_Customer_Sales_ID
    FROM AS_Enterprise_Customer_Sales
    WHERE Customer = UPPER(RTRIM(LTRIM(@Customer))) AND
          CustNo = UPPER(RTRIM(LTRIM(@CustNo))) AND
          Filter = UPPER(RTRIM(LTRIM(@Filter)))


    IF @CustSalesID = 0
        BEGIN
            SET @sql = @sql + ' INSERT AS_Enterprise_Customer_Sales '
            SET @sql = @sql + '     ( '
            SET @sql = @sql + '         Customer, '
            SET @sql = @sql + '         CustNo, '
            SET @sql = @sql + '         Filter, '
            SET @sql = @sql + '         Total, '
            SET @sql = @sql +           @ColumnName + ' '
            SET @sql = @sql + '     ) '
            SET @sql = @sql + ' VALUES '
            SET @sql = @sql + '     ( '
            SET @sql = @sql +           '''' + @Customer + '''' + ', '
            SET @sql = @sql +           '''' + @CustNo + '''' + ', '
            SET @sql = @sql +           'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Value) + ' '
            SET @sql = @sql + '     ) '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' UPDATE AS_Enterprise_Customer_Sales '
            --NB NB: ISNULL(' + @ColumnName + ', 0) below is REQUIRED because value of column is originally CREATED as NULL if EMPTY
            SET @sql = @sql + ' SET ' + @ColumnName + ' = ISNULL(' + @ColumnName + ', 0) + ' + CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql + '         Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Value)
            SET @sql = @sql + ' WHERE AS_Enterprise_Customer_Sales_ID = ' + CONVERT(varchar(50), @CustSalesID)
        END


    EXEC (@sql)



SET NOCOUNT OFF	




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



















--sp_AS_Insert_Enterprise_GP 'ADV2004', '"A" FRAME', 'TAC156', 1, 'Bosal', 400, 300, 100

-------------------------------------------------------------------------------
--Description   :sp_AS_Insert_Enterprise_GP
--Purpose       :INSERT Enterprise GP
--Date          :2009/09/04
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_AS_Insert_Enterprise_GP
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @NetSales money,
        @Cost money,
        @Value money
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @GPID int


    SET @GPID = 0
    SET @sql = ' '


    SELECT @GPID = ISNULL(AS_Enterprise_GP_ID, 0)
    FROM AS_Enterprise_GP
    WHERE Product_Code = @Code AND
          Pack_Size = @Size AND
          Filter = @Filter


    IF @GPID = 0
        BEGIN
            SET @sql = @sql + ' INSERT AS_Enterprise_GP '
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     Description, '
            SET @sql = @sql + '     Product_Code, '
            SET @sql = @sql + '     Pack_Size, '
            SET @sql = @sql + '     Filter, '
            SET @sql = @sql + '     TotalSales, '
            SET @sql = @sql + '     TotalCost, '
            SET @sql = @sql + '     Total, '
            SET @sql = @sql +       @ColumnName + ' '
            SET @sql = @sql + ' ) '
            SET @sql = @sql + ' VALUES '
            SET @sql = @sql + ' ( '
            SET @sql = @sql +        '''' + @Description + '''' + ', '
            SET @sql = @sql +        '''' + @Code + '''' + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Size) + ', '
            SET @sql = @sql +        'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @NetSales) + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Cost) + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Value) + ' '
            SET @sql = @sql + ' ) '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' UPDATE AS_Enterprise_GP '
            --NB NB: ISNULL(' + @ColumnName + ', 0) below is REQUIRED because value of column is originally CREATED as NULL if EMPTY
            SET @sql = @sql + ' SET ' + @ColumnName + ' = ISNULL(' + @ColumnName + ', 0) + ' + CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql + '     TotalSales = ISNULL(TotalSales, 0) + ' + CONVERT(varchar(50), @NetSales) + ', '
            SET @sql = @sql + '     TotalCost = ISNULL(TotalCost, 0) + ' + CONVERT(varchar(50), @Cost) + ', '
            SET @sql = @sql + '     Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Value)
            SET @sql = @sql + ' WHERE AS_Enterprise_GP_ID = ' + CONVERT(varchar(50), @GPID)
        END


    EXEC (@sql)



SET NOCOUNT OFF	























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















--sp_AS_Insert_Enterprise_Sales 'ADV2004', '"A" FRAME', 'TAC156', 1, 'Bosal', 5

-------------------------------------------------------------------------------
--Description   :sp_AS_Insert_Enterprise_Sales
--Purpose       :INSERT Enterprise Sales
--Date          :2007/03/12
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AS_Insert_Enterprise_Sales
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @Value money
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @SalesID int


    SET @SalesID = 0
    SET @sql = ' '


    SELECT @SalesID = AS_Enterprise_Sales_ID
    FROM AS_Enterprise_Sales
    WHERE Product_Code = @Code AND
          Pack_Size = @Size AND
          Filter = @Filter


    IF @SalesID = 0
        BEGIN
            SET @sql = @sql + ' INSERT AS_Enterprise_Sales '
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     Description, '
            SET @sql = @sql + '     Product_Code, '
            SET @sql = @sql + '     Pack_Size, '
            SET @sql = @sql + '     Filter, '
            SET @sql = @sql + '     Total, '
            SET @sql = @sql +       @ColumnName + ' '
            SET @sql = @sql + ' ) '
            SET @sql = @sql + ' VALUES '
            SET @sql = @sql + ' ( '
            SET @sql = @sql +        '''' + @Description + '''' + ', '
            SET @sql = @sql +        '''' + @Code + '''' + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Size) + ', '
            SET @sql = @sql +        'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Value) + ' '
            SET @sql = @sql + ' ) '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' UPDATE AS_Enterprise_Sales '
            --NB NB: ISNULL(' + @ColumnName + ', 0) below is REQUIRED because value of column is originally CREATED as NULL if EMPTY
            SET @sql = @sql + ' SET ' + @ColumnName + ' = ISNULL(' + @ColumnName + ', 0) + ' + CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql + '     Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Value)
            SET @sql = @sql + ' WHERE AS_Enterprise_Sales_ID = ' + CONVERT(varchar(50), @SalesID)
        END


    EXEC (@sql)



SET NOCOUNT OFF	




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Insert_Enterprise_Sales_All
--Purpose       :INSERT Enterprise Sales All
--Date          :2009/09/30
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AS_Insert_Enterprise_Sales_All
	(
        @ColumnName varchar(50),
        @Description varchar(50),
        @Code varchar(20),
        @Size decimal(9, 3),
        @Filter varchar(50),
        @Value money
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @SalesID int


    SET @SalesID = 0
    SET @sql = ' '


    SELECT @SalesID = AS_Enterprise_Sales_All_ID
    FROM AS_Enterprise_Sales_All
    WHERE Product_Code = @Code AND
          Pack_Size = @Size AND
          Filter = @Filter


    IF @SalesID = 0
        BEGIN
            SET @sql = @sql + ' INSERT AS_Enterprise_Sales_All '
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     Description, '
            SET @sql = @sql + '     Product_Code, '
            SET @sql = @sql + '     Pack_Size, '
            SET @sql = @sql + '     Filter, '
            SET @sql = @sql + '     Total, '
            SET @sql = @sql +       @ColumnName + ' '
            SET @sql = @sql + ' ) '
            SET @sql = @sql + ' VALUES '
            SET @sql = @sql + ' ( '
            SET @sql = @sql +        '''' + @Description + '''' + ', '
            SET @sql = @sql +        '''' + @Code + '''' + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Size) + ', '
            SET @sql = @sql +        'UPPER(RTRIM(LTRIM(' +  '''' + @Filter + '''' + ')))' + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql +        CONVERT(varchar(50), @Value) + ' '
            SET @sql = @sql + ' ) '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' UPDATE AS_Enterprise_Sales_All '
            --NB NB: ISNULL(' + @ColumnName + ', 0) below is REQUIRED because value of column is originally CREATED as NULL if EMPTY
            SET @sql = @sql + ' SET ' + @ColumnName + ' = ISNULL(' + @ColumnName + ', 0) + ' + CONVERT(varchar(50), @Value) + ', '
            SET @sql = @sql + '     Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Value)
            SET @sql = @sql + ' WHERE AS_Enterprise_Sales_All_ID = ' + CONVERT(varchar(50), @SalesID)
        END


    EXEC (@sql)



SET NOCOUNT OFF	






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   : sp_AS_Insert_Markup_Categories_Groups
--Purpose       : Cartesian Product Insert - uses CROSS JOIN
--              : for a newly added Lup_AC_Markup_Categories record into
--              : AS_Markup_Categories_Groups
--Functionality : Tables: Lup_AP_Markup_Groups, Lup_AC_Markup_Categories
--Parameters    : 
--Date          : 2007/07/23
--Authors       : TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE  sp_AS_Insert_Markup_Categories_Groups
    (
        @CategoryOrGroupID smallint,
        @CompanyID int,
        @UserID int,
        @Option bit
    )

AS

SET NOCOUNT ON

    DECLARE @cnt int

    IF @Option = 0    --A LUP_AP_Markup_GROUPS_ID has been inserted
        BEGIN
            SELECT @cnt = count(*)
            FROM Lup_AC_Markup_Categories
        
            IF @cnt > 0    -- Some Lup_AC_Markup_Categories exist
                BEGIN
                	INSERT AS_Markup_Categories_Groups
                        (
                            Lup_AC_Markup_Categories_ID,
                            Lup_AP_Markup_Groups_ID,
                            Markup_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT b.Lup_AC_Markup_Categories_ID,
                           a.Lup_AP_Markup_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AP_Markup_Groups a
                         CROSS JOIN Lup_AC_Markup_Categories b
                    WHERE a.Lup_AP_Markup_Groups_ID = @CategoryOrGroupID
                END
            ELSE        -- Create at least one Lup_AC_Markup_Categories
                BEGIN
                    INSERT Lup_AC_Markup_Categories
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT '<None>',
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
        
                    INSERT AS_Markup_Categories_Groups
                        (
                            Lup_AC_Markup_Categories_ID,
                            Lup_AP_Markup_Groups_ID,
                            Markup_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT b.Lup_AC_Markup_Categories_ID,
                           a.Lup_AP_Markup_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AP_Markup_Groups a
                         CROSS JOIN Lup_AC_Markup_Categories b
                    WHERE a.Lup_AP_Markup_Groups_ID = @CategoryOrGroupID
                END       
        END
    ELSE
    IF @Option = 1    --A Lup_AC_Markup_Categories_ID has been inserted
        BEGIN
            SELECT @cnt = count(*)
            FROM Lup_AP_Markup_Groups
        
            IF @cnt > 0    -- Some Lup_AP_Markup_Groups exist
                BEGIN
                	INSERT AS_Markup_Categories_Groups
                        (
                            Lup_AC_Markup_Categories_ID,
                            Lup_AP_Markup_Groups_ID,
                            Markup_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT a.Lup_AC_Markup_Categories_ID,
                           b.Lup_AP_Markup_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AC_Markup_Categories a
                         CROSS JOIN Lup_AP_Markup_Groups b
                    WHERE a.Lup_AC_Markup_Categories_ID = @CategoryOrGroupID
        
                END
            ELSE        -- Create at least one Lup_AC_Markup_Categories
                BEGIN
                    INSERT Lup_AP_Markup_Groups
                        (
                            Description,
                            Date_Captured,
                            User_ID,
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT '<None>',
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
        
                	   INSERT AS_Markup_Categories_Groups    --there were 25
                        (
                            Lup_AC_Markup_Categories_ID,
                            Lup_AP_Markup_Groups_ID,
                            Markup_Percentage,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
                    SELECT a.Lup_AC_Markup_Categories_ID,
                           b.Lup_AP_Markup_Groups_ID,
                           0,
                           getdate(),
                           @UserID,
                           @CompanyID,
                           1            -- Enabled
                    FROM Lup_AC_Markup_Categories a
                         CROSS JOIN Lup_AP_Markup_Groups b
                    WHERE a.Lup_AC_Markup_Categories_ID = @CategoryOrGroupID
        
                END       
        END 

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Insert_Sales_Order_Details
--Purpose       :
--Date          :07 JUN 2008
--Authors       :TB
--MODS          :
--RL	V6.3	:2017-02-09 - Added automaticaly add back order products to order Candidates
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Insert_Sales_Order_Details]
    (
        @CustomerID int,
    	@ProductID int,
    	@Description varchar(50),
    	@ProductCode varchar(20),
    	@Quantity decimal(9, 3),
    	@BackOrder decimal(9, 3),
    	@OriginalPrice money,
    	@UnitPrice money,
    	@DiscountAmount money,
    	@Amount money,
    	@Shipping money,
        @Tax_Rate decimal(9, 3),
    	@TaxAmount money,
    	@ExtendedAmount money,
    	@UnitCost money,
        @PromoProductID int,
    	@PromoPrice money,
    	@DateCaptured datetime,
    	@AddToBO int,
    	@Customer_Reference varchar(15),
		@Lup_AP_Product_Bins_ID int,
       	@UserID int,
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewOrderID int
    
    DECLARE @AO_Suppliers_ID		int,
			@RemoteID				int,
			@AO_Order_Candidates_ID int,
			@Notes					varchar(50),
			@Customer_Name			varchar(40)		

    INSERT AS_Sales_Order_Details
        (
            AC_Customers_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Quantity,
            Back_Order,
            Original_Price,
            Unit_Price,
            Discount_Amount,
            Amount,
            Shipping_Cost,
            Tax_Rate,
            Tax_Amount,
            Extended_Amount,
            Unit_Cost,
            AP_Promotion_Products_ID,
            Promo_Price,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID,
            Customer_Reference,
			Lup_AP_Product_Bins_ID
        )
    VALUES
        (
            @CustomerID,
            @ProductID,
            @Description,
            @ProductCode,
            @Quantity,
            @BackOrder,
            @OriginalPrice,
            @UnitPrice,
            @DiscountAmount,
            @Amount,
            @Shipping,
            @Tax_Rate,
            @TaxAmount,
            @ExtendedAmount,
            @UnitCost,
            @PromoProductID,
            @PromoPrice,
            @DateCaptured,
            @UserID,
            @CompanyID,
            @Customer_Reference,
			@Lup_AP_Product_Bins_ID
        )

	SELECT @NewOrderID = Scope_Identity()

RETURN @NewOrderID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description	:sp_AS_Insert_Transaction_Sources
--Purpose       :ALTER  a list of AS_Transactions recalled source transaction numbers
--Date			:2004/02/02
--Authors		:TB
--Version		:1.0.0
--V6.3	RL		:2017/09/27 :Added check for duplicate Transaction_Number
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Insert_Transaction_Sources]
	(
		@ThisTranID int
	)

AS

SET NOCOUNT ON

    DECLARE @XrefID int,
            @TranID int,
            @TranNo varchar(19),
            @TranNoList varchar(200),
			@Found int


    SELECT @XrefID = AS_Transactions_Xref_ID
    FROM AS_Transactions_Xref
    WHERE AS_Transactions_ID = @ThisTranID

    SET @TranNoList = ''


--> CURSOR to concatenate Transaction Numbers in list
	DECLARE Transaction_Numbers CURSOR FOR
        (
            SELECT AS_Transactions_ID
            FROM AS_Transactions_Xref_Sources
            WHERE AS_Transactions_Xref_ID = @XrefID
        )


	OPEN Transaction_Numbers

    	FETCH NEXT FROM Transaction_Numbers 
    	INTO
            @TranID
    	
    	WHILE @@FETCH_STATUS = 0
    	BEGIN

            SELECT @TranNo = Transaction_Number
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @TranID

			SET @Found = 0
			SELECT @Found = CHARINDEX(@TranNo, @TranNoList)

			IF @Found = 0
			BEGIN
				IF LEN(@TranNoList) > 0
					BEGIN
						SET @TranNoList = @TranNoList + ', '
					END

				SET @TranNoList = @TranNoList + @TranNo
			END

        	FETCH NEXT FROM Transaction_Numbers 
        	INTO
                @TranID

        END

	CLOSE Transaction_Numbers
	DEALLOCATE Transaction_Numbers

	IF NOT EXISTS
	(
		SELECT 1
		FROM AS_Transaction_Sources
		WHERE AS_Transactions_ID = @ThisTranID
		AND Transaction_Numbers = @TranNoList
	)
	BEGIN
	--> Insert the TranNo list 
		INSERT AS_Transaction_Sources
			(
				AS_Transactions_ID,
				Transaction_Numbers
			)
		VALUES
			(
				@ThisTranID,
				@TranNoList
			)
	END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Jobcard_Audit_Invoices
--Purpose       :Sales Transactions AUDIT XREF Invoice Sources
--Functionality :
--Date          :2004/06/27
--Authors       :TB
--MODS:         :
--2004.4.2      :21/11/08 - Removed selecting Open/Closed Jobcards (@optActive) filtering
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AS_Jobcard_Audit_Invoices
    (
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @optChecked tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' x.AS_Transactions_Xref_ID AS [xID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' x.AW_YesNo_Checked_ID AS [Checked], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [Type], '
    SET @sql = @sql + ' ISNULL(h.Transaction_Number, '''') AS [Ref No], '
    SET @sql = @sql + ' h.Transaction_Date AS [Date], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' h.Total_Discount_Amount AS [Discount], '
    SET @sql = @sql + ' h.Total_Cost AS [Cost], '
    SET @sql = @sql + ' h.Amount AS [Amount], '
    SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' h.Total_Amount AS [Total], '
    SET @sql = @sql + ' h.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '
    SET @sql = @sql + ' ISNULL(com.Comment, '''') AS [Notes], '
    SET @sql = @sql + ' ISNULL(u.UserName, '''') AS [User], '
    SET @sql = @sql + ' x.Slu_AW_Active_ID AS [Active] '

    SET @sql = @sql + ' FROM AS_Transactions_Xref x '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = x.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON tt.Sys_AW_Transaction_Types_ID = h.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Comments com '
    SET @sql = @sql + '          ON com.AW_Comments_ID = h.AW_Comments_ID '
    SET @sql = @sql + '      INNER JOIN AW_Users u '
    SET @sql = @sql + '          ON u.AW_Users_ID = h.[User_ID] '

    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
    SET @sql = @sql + '   AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '


    IF @optChecked = 0        -- 0 = Unchecked Jobcards
        BEGIN
            SET @sql = @sql + ' AND x.AW_YesNo_Checked_ID = 0 '
        END
    ELSE                      -- 1 = Checked Jobcards
        BEGIN
            SET @sql = @sql + ' AND x.AW_YesNo_Checked_ID <> 0 '
        END


    SET @sql = @sql + ' ORDER BY [Date] ASC '



    EXEC (@sql)



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AS_Jobcard_Audit_Jobcards
--Purpose       :Sales Transactions AUDIT XREF Jobcard Sources
--Functionality :
--Date          :2004/06/27
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Jobcard_Audit_Jobcards
    (
        @XrefID int
    )

AS

SET NOCOUNT ON


    SELECT
        xs.AS_Transactions_Xref_ID AS [xID],
        xs.AS_Transactions_ID AS [TranID],
        ISNULL(tt.[Description], '') AS [Type],
        ISNULL(h.Transaction_Number, '') AS [Ref No],
        h.Transaction_Date AS [Date],
        ISNULL(c.Surname, '') +
            ISNULL(', ' + c.Firstnames, '') +
            ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')'  AS [Customer],
        h.Total_Discount_Amount AS [Discount],
        h.Total_Cost AS [Cost],
        h.Amount AS [Amount],
        h.Total_Tax_Amount AS [Tax],
        h.Total_Amount AS [Total],
        h.Payment_Amount AS [Payment],
        ISNULL(h.Comment, '') AS [Comment],
        ISNULL(com.Comment, '') AS [Notes],
        ISNULL(u.UserName, '') AS [User],
        xs.Slu_AW_Active_ID AS [Active]

    FROM AS_Transactions_Xref_Sources xs
        INNER JOIN AS_Transactions h
            ON h.AS_Transactions_ID = xs.AS_Transactions_ID
        INNER JOIN Sys_AW_Transaction_Types tt
            ON tt.Sys_AW_Transaction_Types_ID = h.Sys_AW_Transaction_Types_ID
        INNER JOIN AC_Customers c
            ON c.AC_Customers_ID = h.AC_Customers_ID
        LEFT JOIN AW_Comments com
            ON com.AW_Comments_ID = h.AW_Comments_ID
        INNER JOIN AW_Users u
            ON u.AW_Users_ID = h.[User_ID]
    WHERE xs.AS_Transactions_Xref_ID = @XrefID



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Jobcard_Audit_Lups
--Purpose       :
--Date          :2004/06/27
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AS_Jobcard_Audit_Lups
    (
       	@Choice int
    )

AS

BEGIN
    IF @Choice = 1	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID],
               [Description]    -- AS [Active]
        FROM Slu_AW_Active 

    ELSE
    IF @Choice = 2 --Transaction Types - ALL
        SELECT Sys_AW_Transaction_Types_ID AS [ID],
               [Description]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or 
              Sys_AW_Transaction_Types_ID = 3 or 
              Sys_AW_Transaction_Types_ID = 4 or 
              Sys_AW_Transaction_Types_ID = 5 or 
              Sys_AW_Transaction_Types_ID = 7 or 
              Sys_AW_Transaction_Types_ID = 13 or
              Sys_AW_Transaction_Types_ID = 15 or 
        	  Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or 
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 3	--'Users'
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [User]
        FROM AW_Users 
        ORDER BY [User]

    ELSE
    IF @Choice = 4	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],
               [Description]
        FROM Slu_AW_YesNo


END   














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_Jobcard_Audit_Transaction_Details
--Purpose       :Jobcard Audit Transactions details
--Functionality :
--Date          :2004/06/27
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Jobcard_Audit_Transaction_Details
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON


    SELECT
        h.AS_Transactions_ID AS [TranID],
        ISNULL(d.Quantity, 0) AS [Qty],
        ISNULL(d.Unit_Price, 0) AS [Unit Price],
        ISNULL((d.Unit_Price - d.Original_Price) * d.Quantity, 0) AS [Price Adj],
        ISNULL(p.Product_Code, '') AS [Code],
        ISNULL(p.[Description], '') AS [Product],
        ISNULL(d.Discount_Amount, 0) AS [Discount],
        ISNULL((d.Quantity * d.Unit_Cost), 0) AS [Cost],
        ISNULL(d.Extended_Amount - d.Tax_Amount, 0) AS [Amount],
        CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0
             THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) * 100))
             ELSE 0.00
             END AS [Std GP%],
        CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
             THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100))
             ELSE 0.00
             END AS [Act GP%]
    FROM AS_Transactions h
        INNER JOIN AS_Transaction_Details d
            ON d.AS_Transactions_ID = h.AS_Transactions_ID
        INNER JOIN AP_Products p
            ON p.AP_Products_ID = d.AP_Products_ID
    WHERE h.AS_Transactions_ID = @TransactionID
           



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AS_Jobcard_Audit_Update
--Purpose       :UPDATE Jobcard Audit items
--Parameters    :
--Date          :2004/06/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Jobcard_Audit_Update
	(
        @TranXrefID int,
        @Checked tinyint,
        @CheckUserID int
	)

AS

SET NOCOUNT ON

    DECLARE @UserID int,
            @WasChecked tinyint


    SELECT @WasChecked = AW_YesNo_Checked_ID,
           @UserID = Checked_User_ID
    FROM AS_Transactions_Xref
    WHERE AS_Transactions_Xref_ID = @TranXrefID


    IF @WasChecked < @Checked             -- is being set as checked
        BEGIN
            SET @UserID = @CheckUserID    -- the user that checked it
        END
    ELSE
    IF @WasChecked > @Checked             -- was set as checked before
        BEGIN
            SET @UserID = @CheckUserID    -- the user that unchecked it
        END
--  ELSE @UserID remains as it was        -- either NULL or a number

    UPDATE AS_Transactions_Xref
    SET AW_YesNo_Checked_ID = @Checked,
        Checked_User_ID = @UserID
    WHERE AS_Transactions_Xref_ID = @TranXrefID



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Retrieves the values for the extended product for use in Advatage POS
--2002/01/04
--TB

--These values are the same as the SSENTITIES Enumerator in VB
/*
    ssEntityQuote = 1
    ssEntityQuoteDetail = 11
    ssEntityJob = 2
    ssEntityJobDetail = 12
    ssEntityInvoice = 3
    ssEntityInvoiceDetail = 13
    ssEntityRefund = 4
    ssEntityRefundDetail = 14
    ssEntityPayment = 5
    ssEntityPaymentDetail = 15
    ssEntityCustomer = 6
    ssEntityCustomerDetail = 16
    ssEntityLookupCountries = ssMainCustomerCountry '111
    ssEntityLookupTitles = ssMainCustomerTitle      '112
    ssEntityLookupLanguage = ssMainCustomerLanguage '114
    ssEntityLookupDiscount = ssMainCustomerDiscount '118
    ssEntityLookupCardTypes = ssMainPayCardType     '206
    ssEntityProduct = 300
    ssEntityProductsExtended = 310
    ssEntitySwitch = 400
    ssEntityIndicator = 500
*/

CREATE   Procedure sp_AS_Lookup
    (
        @LookupType int,
        @Parameter1 int = 1 ,
        @Parameter2 int = 0,
        @Parameter3 int = 0,
        @Parameter4 int = 0,
        @Parameter5 int = 0
    )

AS

SET NOCOUNT ON

--Extended Product-----------------------------------------------------------------------------
    IF @LookupType = 310  
        SELECT * 
        FROM vw_AS_Products_Extended 
        WHERE ID = @Parameter1   
    ELSE
--Products-----------------------------------------------------------------------------------
    IF @LookupType = 300
        SELECT AP_Products_ID as ID, 
		    Description , 
		    Product_Code  
		    --Pack_Selling_1 
	    FROM AP_Products
	    ORDER BY Description
    ELSE
--Switches-----------------------------------------------------------------------------------
--@Parameter1 Contains the SwitchType
    IF @LookupType = 400
        BEGIN
            IF @Parameter1 = 400   --SwitchType
                SELECT Distinct AP_Products_ID as ID, 
            		Description , 
            		Units_Barcode ,  
			        Pack_Selling_1 
                FROM vw_AP_Switches
                WHERE Switch1_ID = @Parameter2 
                  AND Switch2_ID = @Parameter3 
                  AND Switch3_ID = @Parameter4 
                  AND Switch4_ID = @Parameter5
	        ELSE
            IF @Parameter1 = 401
            	SELECT DISTINCT Switch1_ID as ID, 
                                Switch1_Description 
                FROM vw_AP_Switches
        	ELSE
         	IF @Parameter1 = 402
                BEGIN
                    IF @Parameter2 = 0 
                		SELECT Distinct Switch2_ID as ID, 
                                        Switch2_Description as Description
                        FROM vw_AP_Switches
                    ELSE
                        SELECT Distinct Switch2_ID, 
                                        Switch2_Description as Description
                        FROM vw_AP_Switches 
                        WHERE Switch1_ID = @Parameter2
                END
        	ELSE
            IF @Parameter1 = 403
                BEGIN
                    IF @Parameter2 = 0 
                        SELECT DISTINCT Switch3_ID as ID, 
                                        Switch3_Description as Description
                        FROM vw_AP_Switches
                    ELSE
                    IF @Parameter3 = 0
                        SELECT DISTINCT Switch3_ID as ID, 
                                        Switch3_Description as Description
                        FROM vw_AP_Switches 
                        WHERE Switch1_ID = @Parameter2
                    ELSE
                        SELECT DISTINCT Switch3_ID as ID, 
                                        Switch3_Description as Description
                        FROM vw_AP_Switches 
                        WHERE Switch1_ID = @Parameter2 
                          AND Switch2_ID = @Parameter3
                END
        	ELSE
	        IF @Parameter1 = 404
        		BEGIN
                    IF @Parameter2 = 0 
                		SELECT Distinct Switch4_ID as ID, 
                                        Switch4_Description as Description
                        FROM vw_AP_Switches
                    ELSE
                    IF @Parameter3 = 0
                        SELECT DISTINCT Switch4_ID as ID, 
                                        Switch4_Description as Description
                        FROM vw_AP_Switches 
                        WHERE Switch1_ID = @Parameter2
                    ELSE
                    IF @Parameter4 = 0
                        SELECT DISTINCT Switch4_ID as ID, 
                                        Switch4_Description as Description
                        FROM vw_AP_Switches 
                        WHERE Switch1_ID = @Parameter2 
                          AND Switch2_ID = @Parameter3
                    ELSE
                        SELECT DISTINCT Switch4_ID as ID, 
                                        Switch4_Description as Description
                        FROM vw_AP_Switches 
                        WHERE Switch1_ID = @Parameter2 
                          AND Switch2_ID = @Parameter3 
                          AND Switch3_ID = @Parameter4
                END
        END
--Quote--------------------------------------------------------------------------------------
    ELSE
    IF @LookupType = 1
            SELECT t.AS_Quote_Transactions_ID AS ID, 
                CONVERT(varchar(13), t.Quote_Number) AS Transaction_Number, 
                c.Surname + ', ' + c.Firstnames AS FullName, 
                t.Date_Captured, 
                t.Total_Amount
            FROM AS_Customers c INNER JOIN AS_Quote_Transactions t 
                ON c.AS_Customers_ID = t.AS_Customers_ID
            ORDER BY t.Date_Captured DESC
    ELSE
--Job----------------------------------------------------------------------------------------
    IF @LookupType = 2
        SELECT j.AS_Job_Transactions_ID AS ID, 
               CONVERT(varchar(13), j.Job_Number) AS Transaction_Number, 
               c.Surname + ', ' + c.Firstnames AS FullName, 
               j.Date_Captured, 
               j.Total_Amount
        FROM AS_Customers c INNER JOIN AS_Job_Transactions j 
            ON c.AS_Customers_ID = j.AS_Customers_ID
        ORDER BY j.Date_Captured DESC
    ELSE
--Invoice-------------------------------------------------------------------------------------
    IF @LookupType = 3
            SELECT t.AS_Sales_Transactions_ID AS ID, 
                CONVERT(varchar(13), t.Transaction_Number) AS Transaction_Number, 
                c.Surname + ', ' + c.Firstnames AS FullName, 
                t.Date_Captured, 
                t.Total_Amount
            FROM AS_Customers c INNER JOIN AS_Sales_Transactions t 
                ON c.AS_Customers_ID = t.AS_Customers_ID
            WHERE Sys_AW_Transaction_Types_ID = @LookupType
            ORDER BY t.Date_Captured DESC
    ELSE
--Refund--------------------------------------------------------------------------------------
    IF @LookupType = 4
            SELECT t.AS_Sales_Transactions_ID AS ID, 
                CONVERT(varchar(13), t.Transaction_Number) AS Transaction_Number, 
                c.Surname + ', ' + c.Firstnames AS FullName, 
                t.Date_Captured, 
                t.Total_Amount
            FROM AS_Customers c INNER JOIN AS_Sales_Transactions t 
                ON c.AS_Customers_ID = t.AS_Customers_ID
            WHERE Sys_AW_Transaction_Types_ID = @LookupType
            ORDER BY t.Date_Captured DESC
    ELSE
--Customers------------------------------------------------------------------------------------
    IF @LookupType = 6 
            SELECT c.AS_Customers_ID  as ID,
                   CASE WHEN c.Firstnames is null THEN c.Surname ELSE
                   c.Surname + ', ' + c.Firstnames END AS FullName, 
                   c.Street_Address + ', ' + c.Suburb + ', ' + c.City as Street_Address,
                   r.Description as RepName 
            FROM AS_Customers c LEFT JOIN Lup_AS_Reps r
                ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
            ORDER BY Surname, Firstnames, City
    ELSE
--Titles--------------------------------------------------------------------------------------
    IF @LookupType = 112
        SELECT Slu_AW_Titles_ID as ID, 
               Description
        FROM Slu_AW_Titles 
        ORDER BY Description
    ELSE
--Languages-----------------------------------------------------------------------------------
    IF @LookupType = 114
        SELECT Slu_AW_Languages_ID as ID, 
               Description 
        FROM Slu_AW_Languages 
        ORDER BY Description
    ELSE
--Countries-----------------------------------------------------------------------------------
    IF @LookupType = 111
        SELECT Slu_AW_Countries_ID as ID, 
               Description  
        FROM Slu_AW_Countries 
        ORDER BY Description
    ELSE
--Discount Categories-------------------------------------------------------------------------
    IF @LookupType = 118
        SELECT Lup_AS_Discount_Categories_ID as ID,
               Description  
        FROM Lup_AS_Discount_Categories 
        ORDER BY Description
    ELSE
--CardTypes-----------------------------------------------------------------------------------
    IF @LookupType = 206
        SELECT Lup_AS_Card_Types_ID as ID,
               Description
        FROM Lup_AS_Card_Types
        ORDER BY Description
    ELSE

--Marketing Indicators-------------------------------------------------------------------------
    IF @LookupType = 500  --Marketing Indicators
        SELECT * 
        FROM Lup_AS_Marketing_Indicators 
        WHERE Activated = 1 
        ORDER BY Sequence
    ELSE
--Customer Details-----------------------------------------------------------------------------
    IF @LookupType = 16
         SELECT 
            c.AS_Customers_ID as ID,
            c.Surname,
            c.Firstnames,
            c.Street_Address,
            c.Suburb,
            c.Cell_No,
            c.Land_Tel_No,
    
            c.Post_Box,
            c.Post_Office,
            c.Post_Code,
            c.Street_Code,
            c.City,
            c.Slu_AW_Countries_ID,
    
    
            c.Slu_AW_Titles_ID,
            c.Contact_Name,
            c.Slu_AW_Languages_ID,
            c.Fax_No,
            c.Email,
            c.Tax_Number,
    
            c.Lup_AS_Discount_Categories_ID,
            a.Description as Account_Status,
            c.Credit_Limit,
            c.Account_Balance,
            c.Comment,
    
            c.AS_Customers_ID
        FROM AS_Customers c LEFT JOIN  Lup_AS_Account_Status a
             ON c.Lup_AS_Account_Status_ID = a.Lup_AS_Account_Status_ID
        WHERE c.AS_Customers_ID = @Parameter1
    ELSE
--Quote Details-----------------------------------------------------------------------------
    IF @LookupType = 11
        SELECT 
            AP_Products_ID as ID, 
            CASE WHEN Description IS NULL THEN ''
                 ELSE Description END as [Product Description],    
            Units_Barcode as [Unit BarCode], 
            CASE WHEN Packs_Barcode IS NULL THEN '' 
                 ELSE Packs_Barcode END as [Pack BarCode],
            Unit_Cost as [Unit Cost],
            CASE WHEN Units_On_Hand IS NULL THEN 0 
                 ELSE Units_On_Hand END as Units_On_Hand,
            Promotion_Discount as [Promotion Discount],
            Gross_Profit as [Gross Profit],
            Tax_Description as [Tax Type],
            Standard_Discount as [Standard Discount],
            Original_Price as [Original Price],
            Tax_Amount as Tax,
            Transactions_ID as TransactionID,
            Transaction_Details_ID as TransactionDetailID, 
            0 as ReferenceID ,
            300 as ReferenceTypeID, 
            Quantity as [Quantity],
            Discount_Percent as [Discount %],
            Discount_Amount as [Discount],    
            Unit_Price as [Price],
            Extended_Amount
        FROM vwAS_Quote_Details 
        WHERE Transactions_ID = @Parameter1
        ORDER BY AP_Promotion_Products_ID
    ELSE
--Job Details-------------------------------------------------------------------------------
    IF @LookupType = 12
        SELECT 
            AP_Products_ID as ID, 
            CASE WHEN Description IS NULL THEN ''
                 ELSE Description END as [Product Description],    
            Units_Barcode as [Unit BarCode], 
            CASE WHEN Packs_Barcode IS NULL THEN '' 
                 ELSE Packs_Barcode END as [Pack BarCode],
            Unit_Cost as [Unit Cost],
            CASE WHEN Units_On_Hand IS NULL THEN 0 
                 ELSE Units_On_Hand END as Units_On_Hand,
            Promotion_Discount as [Promotion Discount],
            Gross_Profit as [Gross Profit],
            Tax_Description as [Tax Type],
            Standard_Discount as [Standard Discount],
            Original_Price as [Original Price],
            Tax_Amount as Tax,
            Transactions_ID as TransactionID,
            Transaction_Details_ID as TransactionDetailID, 
            0 as ReferenceID ,
            300 as ReferenceTypeID, 
            Quantity as [Quantity],
            Discount_Percent as [Discount %],
            Discount_Amount as [Discount],    
            Unit_Price as [Price],
            Extended_Amount
        FROM vwAS_Job_Details 
        WHERE Transactions_ID = @Parameter1
        ORDER BY AP_Promotion_Products_ID
    ELSE
--Invoice Details---------------------------------------------------------------------------
    IF @LookupType = 13
        SELECT 
            AP_Products_ID as ID, 
            CASE WHEN Description IS NULL THEN ''
                 ELSE Description END as [Product Description],    
            Units_Barcode as [Unit BarCode], 
            CASE WHEN Packs_Barcode IS NULL THEN '' 
                 ELSE Packs_Barcode END as [Pack BarCode],
            Unit_Cost as [Unit Cost],
            CASE WHEN Units_On_Hand IS NULL THEN 0 
                 ELSE Units_On_Hand END as Units_On_Hand,
            Promotion_Discount as [Promotion Discount],
            Gross_Profit as [Gross Profit],
            Tax_Description as [Tax Type],
            Standard_Discount as [Standard Discount],
            Original_Price as [Original Price],
            Tax_Amount as Tax,
            Transactions_ID as TransactionID,
            Transaction_Details_ID as TransactionDetailID, 
            0 as ReferenceID ,
            300 as ReferenceTypeID, 
            Quantity as [Quantity],
            Discount_Percent as [Discount %],
            Discount_Amount as [Discount],    
            Unit_Price as [Price],
            Extended_Amount
        FROM vwAS_Invoice_Details 
        WHERE Transactions_ID = @Parameter1
        ORDER BY AP_Promotion_Products_ID
    ELSE
--Refund Details-----------------------------------------------------------------------------
    IF @LookupType = 14
        SELECT 
            AP_Products_ID as ID, 
            CASE WHEN Description IS NULL THEN ''
                 ELSE Description END as [Product Description],    
            Units_Barcode as [Unit BarCode], 
            CASE WHEN Packs_Barcode IS NULL THEN '' 
                 ELSE Packs_Barcode END as [Pack BarCode],
            Unit_Cost as [Unit Cost],
            CASE WHEN Units_On_Hand IS NULL THEN 0 
                 ELSE Units_On_Hand END as Units_On_Hand,
            Promotion_Discount as [Promotion Discount],
            Gross_Profit as [Gross Profit],
            Tax_Description as [Tax Type],
            Standard_Discount as [Standard Discount],
            Original_Price as [Original Price],
            Tax_Amount as Tax,
            Transactions_ID as TransactionID,
            Transaction_Details_ID as TransactionDetailID, 
            0 as ReferenceID ,
            300 as ReferenceTypeID, 
            Quantity as [Quantity],
            Discount_Percent as [Discount %],
            Discount_Amount as [Discount],    
            Unit_Price as [Price],
            Extended_Amount
        FROM vwAS_Refund_Details 
        WHERE Transactions_ID = @Parameter1
        ORDER BY AP_Promotion_Products_ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Add_BO_To_SO
--Purpose       :Creates or updates a SO with BO Qty
--Date          :2017/09/10
--Authors       :RL
--V6.4	RL	2018-05-14	:Fixed Back Order Issues
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
    (
		@DocumentID				Int = NULL,
		@ProductID				Int = NULL,
		@Back_Order				Decimal(9,3) = 0,

		@Qty					Decimal(9,3) = 0,
		@Cost					Money = 0,
		@Price					Money = 0,
		@OriginalPrice			Money = 0,
		@Discount				Money = 0,
		@Tax					Money = 0,
		@TotalAmount			Money = 0,
		@Commission				Money = 0,
		@PromotionProductID		Int = 0,
		@PromotionPrice			Money = 0,
		@JobRefID				Int = 0,
        @SerialNo				Varchar(13) = '',
        @Make					Varchar(6) = '',
        @Customer				Varchar(20) = '',
		@TDHeader				Varchar(256) = '',
		@TDDetail				Varchar(256) = '',
		@ProductBinsID			Int,
		@TransactionTypeID		Int,
		@OldTransactionTypeID	Int,		
		@UserID					Int = NULL,
		@CompanyID				Int =  NULL
    )
AS

SET NOCOUNT ON

--Insert Into Temp_Test (Field1) Values ('In sp_AS_POS_Add_BO_To_SO')

	Declare @SO_TransID						Int,
			@CustomerID						Int,
			@Customer_Reference				Varchar(15),
			@NewTransID						Int,
			@Transaction_Number				Varchar(19),

			@NewDiscount					Decimal(18,2),
			@NewTax							Decimal(18,2),
			@NewTotalAmount					Decimal(18,2),
			@TaxRate						Decimal(18,2),
			@chkSOAutoAddPO					Varchar(5),
			@AO_Suppliers_ID				Int,
			@RemoteID						Int,
			@Customer_Name					Varchar(100),
			@PONotes						Varchar(50),
			@AO_Order_Candidates_ID			Int,

			@H_Total_Cost					Decimal(18,2),
			@H_Total_Discount_Amount		Decimal(18,2),
			@H_Amount						Decimal(18,2),
			@H_Total_Tax_Amount				Decimal(18,2),
			@H_Total_Amount					Decimal(18,2),
			@DocumentDetailsID				Int,
			--@DateCaptured					Datetime,
			--@Sys_AW_Transaction_Types_ID	Int,
			@Transaction_Type				Varchar(30),
			@OrigTransaction_Number			Varchar(19),
			@chkSOAutoAddPO_DocType			Varchar(5),
			@Found							Int,
			@SO_CommentID					Int,
			@SO_Comment						Varchar(500),
			@OrigDocCommentID				Int,
			@OrigDocComment					Varchar(500),
			@SO_OrigTransaction_Number		Varchar(19)

	SET @DocumentDetailsID = 0
	SET @SO_TransID = 0
	SET @CustomerID = 0

	IF @TransactionTypeID <> 16
	BEGIN
		SET @SO_TransID = 0

		SELECT	@CustomerID = AC_Customers_ID,
				@Customer_Reference = ISNULL(Customer_Reference,''),
				@OrigTransaction_Number = Transaction_Number
		FROM AS_Transactions
		WHERE AS_Transactions_ID = @DocumentID

		SELECT	@SO_TransID = AS_Transactions_ID,
				@SO_CommentID = ISNULL(AW_Comments_ID,0),
				@SO_OrigTransaction_Number = Transaction_Number
		FROM AS_Transactions
		WHERE AC_Customers_ID = @CustomerID AND
			  ISNULL(Customer_Reference,'') = ISNULL(@Customer_Reference,'') AND
			  AW_User_Companies_ID = @CompanyID AND
			  Slu_AW_Active_ID = 1 AND
			  Sys_AW_Transaction_Types_ID = 16 AND 
			  ISNULL(@Customer_Reference,'') <> ''

		IF @SO_TransID <> 0 --Sales Order already exists
		BEGIN

			SELECT @NewTransID = @SO_TransID

			--Update original document with a reference to the Sales Order just created
			SET @OrigDocCommentID = 0
			SET @OrigDocComment = ''

			SELECT	@OrigDocCommentID = ISNULL(c.AW_Comments_ID,0),
					@OrigDocComment = ISNULL(c.Comment,'')
			FROM AS_Transactions t
				INNER JOIN AW_Comments c
					ON t.AW_Comments_ID = c.AW_Comments_ID
			WHERE AS_Transactions_ID = @DocumentID

			IF @OrigDocCommentID = 0
			BEGIN
				SET @OrigDocCommentID = NULL
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @SO_OrigTransaction_Number + ' for details'

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

				UPDATE AS_Transactions
				SET AW_Comments_ID = @OrigDocCommentID
				WHERE AS_Transactions_ID = @DocumentID
			END
			ELSE
			BEGIN
				IF @OrigDocComment NOT Like '%Item was placed on Sales Order for Back Order. Please refer to Sales Order No %'
				BEGIN
					SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @SO_OrigTransaction_Number + ' for details' + '
	' + @OrigDocComment

					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
				END
			END

			--Insert Or update Sales Order transaction comments
			SET @SO_Comment = ''
			IF ISNULL(@SO_CommentID ,0) <> 0
			BEGIN
				SELECT @SO_Comment = LTRIM(RTRIM(ISNULL(Comment,'')))
				FROM AW_Comments
				WHERE AW_Comments_ID = @SO_CommentID
			END

			SELECT @Transaction_Type = [Description]
			FROM Sys_AW_Transaction_Types
			WHERE Sys_AW_Transaction_Types_ID = @TransactionTypeID

			IF @SO_Comment <> '' 
			BEGIN
				IF ( (LEFT(@SO_Comment,5) = 'Quote') OR (LEFT(@SO_Comment,8) = 'Job Card') OR (LEFT(@SO_Comment,11) = 'Tax Invoice') OR (LEFT(@SO_Comment,9) = 'Pro Forma') OR (LEFT(@SO_Comment,16) = 'Consignment Note') )
				BEGIN
					SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + ', ' + @SO_Comment))
					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
				END
				ELSE
				BEGIN
					SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + '
' + @SO_Comment))
					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
				END
			END
			ELSE
			BEGIN
				SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number))
				SET @SO_CommentID = NULL
				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
			END
		END

		IF @SO_TransID = 0
		BEGIN

			If @Transaction_Number = '' OR @Transaction_Number Is Null
				EXEC sp_AW_Get_Next_Transaction_Number 16, 1, @Transaction_Number Output

			SET @SO_Comment = ''
			IF ISNULL(@SO_CommentID ,0) <> 0
			BEGIN
				SELECT @SO_Comment = ISNULL(Comment,'')
				FROM AW_Comments
				WHERE AW_Comments_ID = @SO_CommentID
			END

			SELECT @Transaction_Type = [Description]
			FROM Sys_AW_Transaction_Types
			WHERE Sys_AW_Transaction_Types_ID = @TransactionTypeID

			SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + '
	' + @SO_Comment))
			SET @SO_CommentID = NULL
			EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment


			INSERT INTO AS_Transactions
			(
				AC_Customers_ID, 
				AB_Accounts_ID, 
				Sys_AW_Transaction_Types_ID, 
				Transaction_Date, 
				Transaction_Number, 
				Total_Cost, 
				Amount, 
				Total_Tax_Amount, 
				Total_Discount_Amount, 
				Total_Amount, 
				Payment_Amount, 
				[Expiry_Date], 
				Version_Number, 
				Customer_Reference, 
				Comment, 
				AW_Comments_ID, 
				Lup_AS_Marketing_Indicators_ID, 
				Lup_AW_Stores_ID, 
				Lup_AW_Workstations_ID, 
				Lup_AS_Tills_ID, 
				Lup_AS_Cashiers_ID, 
				Lup_AS_Reps_ID, 
				Slu_AW_Currencies_ID, 
				Old_Sys_AW_Transaction_Types_ID, 
				Cancelled_User_ID, 
				Cancelled_DateTime, 
				Cashed_Up, 
				Day_End, 
				Transmitted, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			SELECT 
				AC_Customers_ID, 
				AB_Accounts_ID, 
				16, 
				Transaction_Date, 
				@Transaction_Number, 
				0,--Total_Cost, 
				0,--Amount, 
				0,--Total_Tax_Amount, 
				0,--Total_Discount_Amount, 
				0,--Total_Amount, 
				0,--Payment_Amount, 
				[Expiry_Date], 
				Version_Number, 
				ISNULL(Customer_Reference,''),
				ISNULL(Comment,''), 
				@SO_CommentID, 
				Lup_AS_Marketing_Indicators_ID, 
				Lup_AW_Stores_ID, 
				Lup_AW_Workstations_ID, 
				Lup_AS_Tills_ID, 
				Lup_AS_Cashiers_ID, 
				Lup_AS_Reps_ID, 
				Slu_AW_Currencies_ID, 
				Old_Sys_AW_Transaction_Types_ID, 
				Cancelled_User_ID, 
				Cancelled_DateTime, 
				Cashed_Up, 
				Day_End, 
				Transmitted, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @DocumentID

			SELECT @NewTransID = Scope_Identity()

			--Update original document with a reference to the Sales Order just created
			SET @OrigDocCommentID = 0
			SET @OrigDocComment = ''

			SELECT	@OrigDocCommentID = c.AW_Comments_ID,
					@OrigDocComment = c.Comment
			FROM AS_Transactions t
				INNER JOIN AW_Comments c
					ON t.AW_Comments_ID = c.AW_Comments_ID
			WHERE AS_Transactions_ID = @DocumentID

			IF @OrigDocCommentID = 0
			BEGIN
				SET @OrigDocCommentID = NULL
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @Transaction_Number + ' for details'

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

				UPDATE AS_Transactions
				SET AW_Comments_ID = @OrigDocCommentID
				WHERE AS_Transactions_ID = @DocumentID
			END
			ELSE
			BEGIN
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @Transaction_Number + ' for details' + '
' + @OrigDocComment

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
			END

		END

	END --@TransactionTypeID <> 16

		IF @Qty = 0
		BEGIN

			--V6.4
			SELECT	@CustomerID = AC_Customers_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @DocumentID

			SELECT @TaxRate = Tax_Rate
			FROM AC_Customers c
				INNER JOIN Sys_AW_Tax_Codes t
					ON c.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
			WHERE AC_Customers_ID = @CustomerID

			SELECT @NewDiscount = 0
			SET @NewTax = 0

--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@CustomerID) + ' @CustomerID')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@Back_Order) + ' @Back_Order')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@Price) + ' @Price')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@TaxRate) + ' @TaxRate')

				SELECT @NewTax =  ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) * (@TaxRate / 100) ,2)
				SELECT @NewTotalAmount = ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) + @NewTax ,2)
				
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewTax) + ' @NewTax')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewTotalAmount) + ' @NewTotalAmount')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewDiscount) + ' @NewDiscount')

		END
		ELSE
		BEGIN

			SELECT @NewDiscount = Round( ((@Discount / @Qty) * @Back_Order),2)

			SET @NewTax = 0

			IF @Tax <> 0
			BEGIN

				SELECT @TaxRate = ROUND( (@Tax / (@TotalAmount - @Tax) * 100) ,0)

				SELECT @NewTax =  ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) * (@TaxRate / 100) ,2)

				SELECT @NewTotalAmount = ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) + @NewTax ,2)

			END
		END

		--Update Sales Order detail record with new quantity
		SELECT @DocumentDetailsID = AS_Transaction_Details_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @SO_TransID AND
			    AP_Products_ID = @ProductID AND
			    --Unit_Cost = @Cost AND
			    Unit_Price = @Price AND
			    Original_Price = @OriginalPrice AND
				Lup_AP_Product_Bins_ID = @ProductBinsID
		
		IF ISNULL(@DocumentDetailsID,0) <> 0
		BEGIN
			Update AS_Transaction_Details
			SET Quantity = Quantity,
				Back_Order = Back_Order + @Back_Order,
				Unit_Cost = @Cost,
				Unit_Price = @Price,
				Original_Price = @OriginalPrice,
				Discount_Amount = Discount_Amount + @Discount,
				Tax_Amount = Tax_Amount + @Tax,
				Extended_Amount = Extended_Amount + @TotalAmount
			WHERE AS_Transaction_Details_ID = @DocumentDetailsID
		END

		--Insert detail record into Sales order
		IF @DocumentDetailsID = 0
		BEGIN
		
			--V6.4
			SELECT @NewTransID = @SO_TransID		
			--V6.4
			IF ISNULL(@NewTransID,0) = 0
				SELECT @NewTransID = @DocumentID
		
			INSERT AS_Transaction_Details
				(
					AS_Transactions_ID,
					AP_Products_ID,
					Quantity,
					Back_Order,

					Unit_Cost,
					Unit_Price,
					Original_Price,
					Discount_Amount,
					Tax_Amount,
					Extended_Amount,
					Commission_Amount,

					AP_Promotion_Products_ID,
					AS_Job_References_ID,
					Serial_No,
					Make,
					Customer,
					User_ID,
					AW_User_Companies_ID,
					TDHeader,
					TDDetail,
					Lup_AP_Product_Bins_ID
				)
			VALUES
				(
					@NewTransID,
					@ProductID,
					0,	--Qty will always be zero because it is created from another document
					@Back_Order,

					ISNULL(@Cost,0),
					ISNULL(@Price,0),
					ISNULL(@OriginalPrice,0),
					ISNULL(@NewDiscount,0),
					ISNULL(@NewTax,0),
					ISNULL(@NewTotalAmount,0),
					NULL,

					@PromotionProductID,
					@JobRefID,
					@SerialNo,
					@Make,
					@Customer,
					@UserID,
					@CompanyID,
					ISNULL(@TDHeader,''),
					ISNULL(@TDDetail,''),
					@ProductBinsID
				)

			SELECT @DocumentDetailsID = Scope_Identity()
		END

		SELECT @H_Total_Cost = SUM((Quantity + @Back_Order) * Unit_Cost),
				@H_Total_Discount_Amount = SUM(Discount_Amount),
				@H_Amount = SUM(Extended_Amount - Tax_Amount),
				@H_Total_Tax_Amount = SUM(Tax_Amount),
				@H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @NewTransID
		
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
			Total_Discount_Amount = @H_Total_Discount_Amount,
			Amount = @H_Amount,
			Total_Tax_Amount = @H_Total_Tax_Amount,
			Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @NewTransID
	


IF @OldTransactionTypeID <> -88
BEGIN		
	SET @chkSOAutoAddPO = '0'

	SELECT @chkSOAutoAddPO = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOAutoAddPO'
		--Add to purchase orders
	IF @chkSOAutoAddPO = '1'
	BEGIN
	
		SET @chkSOAutoAddPO_DocType = '0'

		IF @TransactionTypeID = 1
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOQuote'
		END

		IF @TransactionTypeID = 2
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOJobcard'
		END

		IF @TransactionTypeID = 3
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOInvoice'
		END

		IF @TransactionTypeID = 13
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOProForma'
		END

		IF @TransactionTypeID = 16
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOSalesOrder'
		END

		IF @TransactionTypeID = 33
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOConsignment'
		END

		IF @chkSOAutoAddPO_DocType = '1'
		BEGIN

			SET @AO_Suppliers_ID = 1
				
			SELECT TOP 1 @AO_Suppliers_ID = s.AO_Suppliers_ID
			FROM AP_Products_Suppliers ps
				INNER JOIN AO_Suppliers s
					ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
			WHERE ps.AP_Products_ID = @ProductID AND
				  ps.Slu_AW_Active_ID = 1 AND
				  s.Slu_AW_Active_ID = 1 And
				  GETDATE() Between ps.[Start_Date] And '2999-01-01'
				
			SET @RemoteID = 0
				
			SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
			FROM AW_Remote_Access
			WHERE AW_User_Companies_ID = @CompanyID AND
				  Default_Connection = 1

			IF @CustomerID = 0
			BEGIN
				SELECT	@CustomerID = AC_Customers_ID
				FROM AS_Transactions
				WHERE AS_Transactions_ID = @DocumentID
			END

			SELECT @Customer_Name = Surname
			FROM AC_Customers
			WHERE AC_Customers_ID = @CustomerID
		
   			SELECT @PONotes = Notes
    		FROM AO_Order_Candidates
    		WHERE AP_Products_ID = @ProductID AND
    			  AO_Suppliers_ID = @AO_Suppliers_ID AND
    			  AW_User_Companies_ID = @CompanyID

			SELECT @PONotes = ISNULL(@PONotes,'')

			IF @PONotes = ''
			BEGIN
				SET @PONotes = LEFT('Back Order for ' + @Customer_Name,50)
			END
			ELSE
			BEGIN
				
				SELECT @Found = 0
				SELECT @Found = CHARINDEX(@Customer_Name,@PONotes)

				IF @Found = 0
				BEGIN
					SET @PONotes = LEFT(@PONotes + LEFT(' / ' + @Customer_Name,50),50)
				END				
				
				SET @PONotes = LEFT(@PONotes + LEFT(' / ' + @Customer_Name,50),50)

			END
								
			EXEC @AO_Order_Candidates_ID = sp_AO_Add_Product_To_Order_Candidates_RET @ProductID, @AO_Suppliers_ID, @Back_Order, @PONotes, @UserID ,@UserID , @CompanyID, @RemoteID
		END
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AS_POS_CBilling_Detail_Insert
--Functionality :Inserts Central Billing transaction details
--Parameters    :
--Date          :2004/03/01
--Authors       :TB
--Version       :1.0.0.
--MODS          :09/03/04 - Added @ClaimCodeID
--              :09/03/04 - Change SIGN of Qty and Amounts if item is a TEC
--              :16/08/04 - Added Original_Number (@OriginalNo) field - K Slabbert 5 AUG
--              :21/01/05 - Changed TEC's @ClaimCodeID = 3 (a Refund is now 2)
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_POS_CBilling_Detail_Insert
    (
        @TransactionID int,
        @BillingProviderID smallint,
        @Make varchar(30),
        @Model varchar(30),
        @Model_Year varchar(10),
        @AuthorizationNo varchar(24),
        @RegistrationNo varchar(10),
        @OdometerReading varchar(7),
        @FailReasonsID smallint,
        @CustomerIDNo varchar(13),
        @EngineNo varchar(24),
        @ChassisNo varchar(24),
        @ClaimCodeID smallint,
        @OriginalNo varchar(19)
    )

AS

SET NOCOUNT ON

    DECLARE @TranTypeID tinyint,
            @TranNo varchar(19),
            @TranDate datetime,
            @DateCaptured datetime,
            @UserID int,
            @CompanyID int,
            @ManufacturerCode varchar(20),
            @Quantity decimal(9, 3),
            @DiscountPerc money,
            @NetAmount money,
            @ExtendedAmount money,
            @TaxAmount money,
            @DiscountAmount money,
            @CustomerNumber varchar(10),
            @NetworkIdentityNumber varchar(10),
            @ItemNo int,
            @ReturnCode int


    SET @ReturnCode = 0
    SET @ItemNo = 0



--> Intialise Lookup ID's if not set in POS
    IF @BillingProviderID = 0
        BEGIN
            SET @BillingProviderID = 1
        END

    IF @FailReasonsID = 0
        BEGIN
            SET @FailReasonsID = 1
        END

    IF @ClaimCodeID = 0
        BEGIN
            SET @ClaimCodeID = 1
        END



    BEGIN

        --> Get Transaction Header data
        SELECT @TranTypeID = Sys_AW_Transaction_Types_ID,
               @TranNo = h.Transaction_Number,
               @TranDate = h.Transaction_Date,
               @DateCaptured = h.Date_Captured,
               @UserID = h.[User_ID],
               @CompanyID = h.AW_User_Companies_ID,
               @CustomerNumber = LEFT(c.Customer_Number, 10)
        FROM AS_Transactions h
            INNER JOIN AC_Customers c
                ON h.AC_Customers_ID = c.AC_Customers_ID
        WHERE AS_Transactions_ID = @TransactionID

    
        --> Get the 'Customer Code' field
        SELECT @NetworkIdentityNumber = LEFT(Network_Identity_Number, 10)
        FROM AW_User_Companies
        WHERE AW_User_Companies_ID = @CompanyID
    
    
    	DECLARE CBilling_Cursor CURSOR FOR
            (
                SELECT p.Manufacturer_Code,
                       d.Quantity,
                       d.Extended_Amount,
                       d.Tax_Amount,
                       d.Discount_Amount
                FROM AS_Transaction_Details d
                    INNER JOIN AP_Products p
                        ON d.AP_Products_ID = p.AP_Products_ID
                WHERE d.AS_Transactions_ID = @TransactionID
            )
    
    	OPEN CBilling_Cursor
    
        	FETCH NEXT FROM CBilling_Cursor 
        	INTO
                @ManufacturerCode,
                @Quantity,
                @ExtendedAmount,
                @TaxAmount,
                @DiscountAmount
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
                SET @ItemNo = @ItemNo + 1

                SET @NetAmount = (@ExtendedAmount - @TaxAmount) - @DiscountAmount

                IF @NetAmount <> 0
                    BEGIN
                        SET @DiscountPerc = ABS(ROUND((@DiscountAmount / @NetAmount) * 100, 2))
                    END

                IF @ClaimCodeID = 3            --TEC's
                    BEGIN
                        IF @TranTypeID = 3     --Tax Invoice
                            BEGIN
                                SET @Quantity = ABS(@Quantity)
                                SET @ExtendedAmount = ABS(@ExtendedAmount) * -1
                                SET @TaxAmount = ABS(@TaxAmount) * -1
                            END
                        ELSE
                        IF @TranTypeID = 4     --Tax Credit Note
                            BEGIN
                                SET @Quantity = ABS(@Quantity) * -1
                                SET @ExtendedAmount = ABS(@ExtendedAmount)
                                SET @TaxAmount = ABS(@TaxAmount)
                            END
                    END

            	INSERT AS_Transactions_CBilling
            		(
                        AS_Transactions_ID,
                        Lup_AS_CBilling_Providers_ID,
                        Customer_Number,
                        Network_Identity_Number,
                        Sys_AW_Transaction_Types_ID,
                        Transaction_Number,
                        Original_Number,
                        Transaction_Date,
                        Make,
                        Model,
                        Model_Year,
                        Item_No,
                        Authorization_No,
                        Registration_No,
                        Odometer_Reading,
                        Manufacturer_Code,
                        Extended_Amount,
                        Tax_Amount,
                        Discount_Amount,
                        Quantity,
                        Lup_AP_Fail_Reasons_ID,
                        Client_ID_No,
                        Engine_No,
                        Chassis_No,
                        Lup_AP_Claim_Codes_ID,
                        Date_Captured,
                        [User_ID],
                        AW_User_Companies_ID
            		)
            	VALUES
            		(
                        @TransactionID,
                        @BillingProviderID,
                        LEFT(@CustomerNumber, 10),
                        LEFT(@NetworkIdentityNumber, 10),
                        @TranTypeID,
                        @TranNo,
                        @OriginalNo,
                        @TranDate,
                        LEFT(@Make, 30),
                        LEFT(@Model, 30),
                        LEFT(@Model_Year, 10),
                        @ItemNo,
                        LEFT(@AuthorizationNo, 24),
                        LEFT(@RegistrationNo, 10),
                        LEFT(@OdometerReading, 7),
                        LEFT(@ManufacturerCode, 18),
                        @ExtendedAmount,
                        @TaxAmount,
                        @DiscountPerc,
                        @Quantity,
                        @FailReasonsID,
                        LEFT(@CustomerIDNo, 13),
                        LEFT(@EngineNo, 24),
                        LEFT(@ChassisNo, 24),
                        @ClaimCodeID,
                        @DateCaptured,
                        @UserID,
                        @CompanyID
            		)
    
            	FETCH NEXT FROM CBilling_Cursor 
            	INTO
                    @ManufacturerCode,
                    @Quantity,
                    @ExtendedAmount,
                    @TaxAmount,
                    @DiscountAmount
    
            END
    
    	CLOSE CBilling_Cursor
    
    	DEALLOCATE CBilling_Cursor
    
    
        SET @ReturnCode = 1

    END


RETURN @ReturnCode



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Cash_Up
--Purpose       :User is SpSPOSEntity.CApplication to Cash Up from POS
--Functionality : 
--Parameters    : 
--Date          :2001/01/05
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_POS_Cash_Up
    (
    	@TillID int = 0,
    	@CashierID int = 0
    )

AS

SET NOCOUNT ON

	DECLARE @Date datetime
	SET @Date = getdate()

	IF @TillID > 0 
		UPDATE AS_Transactions
        SET Cashed_Up = @Date
		WHERE Cashed_Up IS NULL AND
              Lup_AS_Tills_ID = @TillID
	ELSE
		UPDATE AS_Transactions
        SET Cashed_Up = @Date
		WHERE Cashed_Up IS NULL AND
              Lup_AS_Cashiers_ID = @CashierID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Cashier_Sales
--Purpose       :Point-of-Sale
--Date          :2004/11/25
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_POS_Cashier_Sales
    (
        @CompanyID int,
        @Option tinyint,
        @CashierID int
    )

AS

SET NOCOUNT ON

    DECLARE @LastDayEndDate datetime,
            @LastPeriodProcedureDate datetime,
            @LastYearEndProcedureDate datetime,
            @ProcedureTypeID int


    SET @ProcedureTypeID = 1        --1 = Customer Month-End


    --Sales Today ( > Last Day-End )
    IF @Option = 0
        BEGIN

            EXEC sp_AW_Get_Last_Day_End_Date
                                @CompanyID,
                                @LastDayEndDate OUTPUT


            SELECT
                ISNULL(SUM(d.Quantity), 0) AS [Qty],
                ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                     THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                     ELSE 0.00
                     END AS [StdGP%],
                CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                     THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                     ELSE 0.00
                     END AS [ActGP%],
                @LastDayEndDate AS [ProcedureDate]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
        		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                       h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                       h.Transaction_Date > @LastDayEndDate AND
                       h.AW_User_Companies_ID = @CompanyID AND
                       h.User_ID = @CashierID
        END

    --Sales this month ( > Last Month-End )
    ELSE
    IF @Option = 1
        BEGIN

            EXEC sp_AW_Get_Last_Period_Procedure_Date
                                    @ProcedureTypeID,    
                                    @CompanyID,
                                    @LastPeriodProcedureDate OUTPUT

            SELECT
                ISNULL(SUM(d.Quantity), 0) AS [Qty],
                ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                     THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                     ELSE 0.00
                     END AS [StdGP%],
                CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                     THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                     ELSE 0.00
                     END AS [ActGP%],
                @LastPeriodProcedureDate AS [ProcedureDate]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
        		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                       h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                       h.Transaction_Date > @LastPeriodProcedureDate AND
                       h.AW_User_Companies_ID = @CompanyID AND
                       h.User_ID = @CashierID

        END

    --Sales YTD ( > Last Year-End )
    ELSE
    IF @Option = 2
        BEGIN

            EXEC sp_AW_Get_Last_Period_Procedure_Year_End_Date
                                                    @ProcedureTypeID,
                                                    @CompanyID,
                                                    @LastYearEndProcedureDate OUTPUT

            SELECT
                ISNULL(SUM(d.Quantity), 0) AS [Qty],
                ISNULL(SUM((d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [PriceDisc],
                ISNULL(SUM(d.Discount_Amount), 0) AS [SalesDisc],
                ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales],
                ISNULL(SUM((d.Quantity * d.Unit_Cost)), 0) AS [Cost],
                ISNULL(SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP],
                CASE WHEN SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) <> 0
                     THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / SUM(dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity))) * 100))
                     ELSE 0.00
                     END AS [StdGP%],
                CASE WHEN SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) <> 0
                     THEN CONVERT(money,((SUM(dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / SUM(dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount))) * 100))
                     ELSE 0.00
                     END AS [ActGP%],
                @LastYearEndProcedureDate AS [ProcedureDate]
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
        		WHERE (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                       h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                       h.AW_User_Companies_ID = @CompanyID AND
                       h.User_ID = @CashierID AND
                       h.Transaction_Date >= @LastYearEndProcedureDate


        END




SET NOCOUNT ON














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AS_POS_Comments_Select
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------
CREATE            PROCEDURE sp_AS_POS_Comments_Select
	(
		@CustomerID int,
		@ActorTypeID int
	)

AS

SET NOCOUNT ON

    SELECT AW_Comments_ID AS CommentID, 
           Sys_AT_Actor_Types_ID AS ActorTypeID, 
           Actor_ID AS CustomerID, 
           Comment AS Comment,
           AW_User_Companies_ID AS CompanyID,
           [User_ID] AS UserID
	FROM AW_Comments
	WHERE Sys_AT_Actor_Types_ID = -1 AND
          Actor_ID = @CustomerID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_CustomerID_Select
--Purpose       :Fetch ONE Customer for a CustomerID
--Date          :2010/03/27
--Authors       :TB
--MODS          :
--V6.3	RL	2017-09-10	:Return Lup_AS_Rep_ID. Used as default Sales Rep dependant on system option
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_CustomerID_Select]
    (
        @CompanyID int,
        @CustomerID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' a.Surname AS [Name], '
    SET @sql = @sql + ' a.Firstnames AS [FirstNames], '
    SET @sql = @sql + ' a.Cell_No AS [CellNo], '
    SET @sql = @sql + ' a.Street_Address AS [StreetAddress], '

    SET @sql = @sql + ' a.City AS [City], '
    SET @sql = @sql + ' a.Initials AS [Initials], '
    SET @sql = @sql + ' a.Tax_Number AS [TaxNumber], '
    SET @sql = @sql + ' a.Suburb AS [Suburb], '
    SET @sql = @sql + ' a.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' a.Home_Tel_No AS [HomeTelNo], '
    SET @sql = @sql + ' ISNULL(a.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '         SELECT SUM(ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0)) '
    SET @sql = @sql + '         FROM AS_Transactions h '
    SET @sql = @sql + '         WHERE h.AC_Customers_ID = a.AC_Customers_ID AND '
    SET @sql = @sql + '               ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) <> 0 AND '
    SET @sql = @sql + '              (h.Sys_AW_Transaction_Types_ID = 3 OR '      --Invoice
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 4 OR '      --Refund
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 5 OR '      --Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 7 OR '      --Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 15 OR '     --Interest Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 18 OR '     --Settlement Discount
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 21 OR '     --Back Office Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 22) '       --EFT Payment
    SET @sql = @sql + '         ), 0) AS [AccountBalance], '

    SET @sql = @sql + ' a.Work_Email AS [WorkEmail], '
    SET @sql = @sql + ' a.Notes AS [Notes], '
    SET @sql = @sql + ' a.Sys_AC_Account_Status_ID AS [AccountStatusID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Types_ID AS [CustomerTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Groups_ID AS [CustomerGroupID], '
    SET @sql = @sql + ' s.[Description] AS [AccountStatus], '
    SET @sql = @sql + ' ct.[Description] AS [CustomerType], '
    SET @sql = @sql + ' g.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' a.[User_ID] AS [UserID], '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' -1 as [ActorTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Discount_Categories_ID, '
    SET @sql = @sql + ' a.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(tc.Tax_Rate, 0) AS [CustTaxRate], '
    SET @sql = @sql + ' a.Slu_AW_Credit_Terms_ID AS [TermsID], '
    SET @sql = @sql + ' e.Terms_Value AS [TermsValue], '
    SET @sql = @sql + ' f.[Description] AS [AccountType], '
    SET @sql = @sql + ' a.Sys_AC_Account_Types_ID AS [AccountTypeID], '
    SET @sql = @sql + ' a.AW_YesNo_Net_Billing_ID AS [NetBilling], '
    SET @sql = @sql + ' a.AW_YesNo_Purchase_Order_ID AS [PurchaseOrder], '
    SET @sql = @sql + ' a.AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling], '
    SET @sql = @sql + ' a.Lup_AC_Markup_Categories_ID AS [CostPlusCategory], '
    SET @sql = @sql + ' a.Delivery_Post_Code AS [DelPostCode], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Credit_Limit AS [OverrideLimit], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Overdue AS [OverrideOverdue], '
    SET @sql = @sql + ' a.AW_YesNo_Apply_Product_Levy AS [CustomerApplyLevy], '           
    SET @sql = @sql + ' a.AW_YesNo_Change_Doc_Details AS [ChangeDocDetails], '
	--V6.3 RL 2017/09/11
	SET @sql = @sql + ' a.Lup_AS_Reps_ID AS [SalesPersonID], ' 

    SET @sql = @sql + ' ISNULL(Surname, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Suburb, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + City, '''') AS [FullName] '

    SET @sql = @sql + ' FROM AC_Customers a '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions b '
    SET @sql = @sql + '         ON a.AC_Customers_ID = b.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Comments c '
    SET @sql = @sql + '         ON c.AW_Comments_ID = b.AW_Comments_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Types ct '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '         ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Credit_Terms e '
    SET @sql = @sql + '         ON a.Slu_AW_Credit_Terms_ID = e.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Types f '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Groups g '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Groups_ID = g.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + ' WHERE a.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' AND '
    SET @sql = @sql + '       a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       a.Slu_AW_Active_ID = 1 '

EXEC (@sql)
--Select @sql
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description	:sp_AS_POS_CustomerRef_AssetNo
--Purpose       :Insert Customer Reference and Asset Number into AS_Transactions
--              :
--              :
--Date			:2002/12/30
--Authors		:TB
--Version		:1.0.0
--MODS          :09/01/03 - Increased AssetNo field size to 20
--V6.3	RL	2017-09-10	:Update Sales Order Customer_Reference And Comment
--						:SpSPOSTrans.dll does not sends it through as NULL. WTF!!!!
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_CustomerRef_AssetNo]
	(
		@TranID int,
        @CustomerRef varchar(15),
        @AssetNo varchar(20)
	)

AS

SET NOCOUNT ON

	Declare	@Date_Captured	Datetime,
			@SO_TranID		Int

    BEGIN
        UPDATE AS_Transactions
        SET Customer_Reference = ISNULL(@CustomerRef,''),
            Comment = ISNULL(@AssetNo,'')
        WHERE AS_Transactions_ID = @TranID

		SELECT @Date_Captured = Date_Captured
		FROM AS_Transactions
		WHERE AS_Transactions_ID = @TranID

		SET @SO_TranID = 0
		SELECT @SO_TranID = AS_Transactions_ID
		FROM AS_Transactions
		WHERE Date_Captured = @Date_Captured
		AND Sys_AW_Transaction_Types_ID = 16

		IF @SO_TranID <> 0
		BEGIN
			UPDATE AS_Transactions
			SET Customer_Reference = ISNULL(@CustomerRef,''),
				Comment = ISNULL(@AssetNo,'')
			WHERE AS_Transactions_ID = @SO_TranID
		END


    END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











--TEST: exec sp_AS_POS_Customer_Discounts_Select 1

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customer_Discounts_Select
--Purpose       :Fetches Customer Discount Group ID and Discount Percentages
--              :    for the Customer
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       :1
-------------------------------------------------------------------------------


CREATE             PROCEDURE sp_AS_POS_Customer_Discounts_Select
	(
		@CategoryID int
	)

AS

SET NOCOUNT ON
	
	SELECT AS_Discount_Categories_Groups_ID AS [ID],
           Lup_AP_Discount_Groups_ID AS [GroupID],
           Discount_Percentage AS Percentage
	FROM AS_Discount_Categories_Groups
	WHERE Lup_AC_Discount_Categories_ID = @CategoryID


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customer_Insert_Update
--Purpose       :POS Customers SELECT
--Functionality :NB: Parameter name must be identical to the field aliases
--              :    in vw_AS_POS_Customers_Select excluding the '@' prefix
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS          :06/10/02 - When INSERT NEW Customer from POS,
--              :               Added:    Post_Box = LEFT(@StreetAddress, 20),
--              :                         Post_Office = LEFT(@Suburb, 30),
--              :                         Initials = LEFT(@FirstNames, 1)
--              :           because POS PRINTING uses POSTAL ADDRESSES to print
--              :26/05/03 - Commented out inserting Date-Captured (@Date). This
--              :           inserted a NULL value into AC_Customers
--              :26/05/03 - Replaced LEFT(@FirstNames, 1) with @Initials to
--              :           insert actual initials captured in POS Add Customer
--              :20/08/04 - Added @CustomerTypeID and @CustomerGroupID input
--              :           parameters for new fields in POS Customer Add/Edit
--              :09/12/04 - Added @TaxNumber input parameters for new fields
--              :           in POS Customer Add/Edit 
--2004.5.0      :14/01/11 - Added INSERT/UPDATE Orders_URL & Home_Email values from @WorkEmail
--              :           when INSERTING NEW and UPDATING EXISTING Customer
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_POS_Customer_Insert_Update
	(
		@Name varchar(40) = NULL, 
		@FirstNames varchar(50) = NULL, 
		@Initials varchar(10) = NULL,
        @TaxNumber varchar(16) = NULL,
		@Suburb varchar(30) = NULL, 
		@CellNo varchar(16) = NULL, 
		@WorkTelNo varchar(16) = NULL, 
		@HomeTelNo varchar(16) = NULL, 
		@StreetAddress varchar(40) = NULL, 
		@City varchar(30) = NULL, 
		@WorkEmail varchar(40) = NULL, 
		@CustomerTypeID smallint = NULL,
		@CustomerGroupID smallint = NULL,
		@Notes varchar(500) = NULL, 
		@Date DateTime = NULL, 
		@UserID int = NULL, 
		@CompanyID int = NULL, 
		@CustomerID int = NULL OUTPUT 	
	)

AS

SET NOCOUNT ON

    --> NEW 2004.5.0
    DECLARE @AccountsEmail varchar(100),
            @HomeEmail varchar(40)


    IF @WorkEmail IS NULL
        BEGIN
            SET @WorkEmail = ''
        END

    SET @AccountsEmail = @WorkEmail
    SET @HomeEmail = @WorkEmail
    -------------------------------


	IF @CustomerID IS NULL OR @CustomerID = 0
		BEGIN
			INSERT AC_Customers
                (
                	Surname,
                	Firstnames,
                	Initials,
                    Tax_Number,
                    Post_Box,
                    Post_Office,
                	Street_Address,
                	Suburb, 
                	City, 
                	Cell_No,
                	Work_Tel_No,
                	Home_Tel_No,
                    Orders_URL,
                    Home_Email,
                	Work_Email,
                    Lup_AC_Customer_Types_ID,
                    Lup_AC_Customer_Groups_ID,
                	Notes, 
                	[User_ID],
                	AW_User_Companies_ID
                )
			VALUES
				(
					@Name ,
					@FirstNames,
					@Initials,
                    @TaxNumber,
        			LEFT(@StreetAddress, 20),
		        	LEFT(@Suburb, 30),
					@StreetAddress,
					@Suburb,
					@City,
					@CellNo,
					@WorkTelNo,
					@HomeTelNo,
					@WorkEmail,
					@WorkEmail,
					@WorkEmail,
            		@CustomerTypeID,
            		@CustomerGroupID,
					@Notes,
					@UserID,
					@CompanyID 
				)
			SELECT @CustomerID = Scope_Identity()
		END		
	ELSE
        --> NEW 2004.5.0
        SELECT @AccountsEmail = ISNULL(Orders_URL, @WorkEmail),
               @HomeEmail = ISNULL(Home_Email, @WorkEmail)
        FROM AC_Customers
        WHERE AC_Customers_ID = @CustomerID
        -------------------------------


		UPDATE AC_Customers
        SET Surname = @Name, 
            Firstnames = @FirstNames, 
            Initials = @Initials,
            Tax_Number = @TaxNumber,
            Street_Address = @StreetAddress, 
            Suburb = @Suburb, 
            City = @City, 
            Cell_No = @CellNo,
            Work_Tel_No = @WorkTelNo, 
            Home_Tel_No = @HomeTelNo, 
            Orders_URL = @AccountsEmail,
            Home_Email = @HomeEmail,
            Work_Email = @WorkEmail, 
            Lup_AC_Customer_Types_ID = @CustomerTypeID,
            Lup_AC_Customer_Groups_ID = @CustomerGroupID,
            Notes = @Notes, 
            [User_ID] = @UserID, 
            AW_User_Companies_ID = @CompanyID
        WHERE AC_Customers_ID = @CustomerID


	RETURN @CustomerID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customer_Transactions
--Purpose       :Gets ALL (including DEACTIVATED) Customer Transactions of preceding year
--Functionality :
--Date          :2010/04/26
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AS_POS_Customer_Transactions
    (
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

	SELECT t.AS_Transactions_ID AS [TranID], 
           t.AC_Customers_ID AS [CustomerID],
           t.Sys_AW_Transaction_Types_ID AS [TranTypeID],
           ISNULL(tt.[Description], '') AS [Type],
           t.Transaction_Date AS [Date], 
           ISNULL(t.Transaction_Number, '') AS [Doc No], 
           ISNULL(t.Customer_Reference, '') AS [Order No], 
           ISNULL(t.Comment, '') AS [Comment],
           t.Total_Amount AS [Amount], 
           ISNULL(ts.Transaction_Numbers, '') AS [Source No],
           u.UserName AS [Cashier],
           t.Slu_AW_Active_ID AS [ActiveID]

	FROM AS_Transactions t 
        LEFT JOIN AS_Transaction_Sources ts
            ON t.AS_Transactions_ID = ts.AS_Transactions_ID
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AW_Users u
            ON t.User_ID = u.AW_Users_ID
	WHERE t.AC_Customers_ID = @CustomerID AND
          t.AW_User_Companies_ID = @CompanyID AND
          t.Transaction_Date >= DATEADD(year, -1, getdate())
	ORDER BY t.Date_Captured DESC


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_InvDel
--Purpose       :POS Customer Invoice and Delivery Address Details
--Date          :2013/08/08
--Authors       :RL
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
--V6.4	RL	2018-03-27	:Added Cellphone and email
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Customers_InvDel]
	(    
    	 @AC_Customer_ID int
	)
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
			@WhichAddress tinyint,
			@WhichName tinyint
	
	SET @WhichAddress = 0
	SET @WhichName = 0

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SELECT @WhichAddress = ISNULL(Control_Index, 0)
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
		Control_Name = 'optPOSPrintAddress' AND
		Control_Value = 'True'

	--> Get Which Name Format To Use
	SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM Sys_AW_Options
	WHERE Control_Index = 0 AND
	Control_Type = 'CheckBox' AND
	Control_Name = 'chkPOSPrintTradeName'

    SET @sql = ' SELECT DISTINCT '        -- DISTINCT is NB NB

	IF @WhichName = 1
		BEGIN
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		--SET @sql = @sql + ' RTRIM(LTRIM(a.Surname)) + ISNULL('', '' + A.Initials, '''') + '' / '' + IsNull(A.Firstnames,'''') AS [CurrentInvName], '
			SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
			SET @sql = @sql + ' 	THEN '
			SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
			SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
			SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
			SET @sql = @sql + ' 		END '
			SET @sql = @sql + ' 	ELSE '
			SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
			SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
			SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
			SET @sql = @sql + ' 		END '
			SET @sql = @sql + ' 	END AS [CurrentInvName], '
		END	
	ELSE
		BEGIN
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		--SET @sql = @sql + ' RTRIM(LTRIM(A.Surname)) + ISNULL('', '' + A.Initials, '''') AS [CurrentInvName], '	
			SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
			SET @sql = @sql + ' 	THEN LTRIM(RTRIM(c.Surname)) '
			SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
			SET @sql = @sql + ' 	END AS [CurrentInvName], '
	END
	
	IF @WhichAddress = 0
		BEGIN
			SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(c.Post_Office, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(c.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(c.Post_Code, '''') AS [CurrentInvPostCode], '
		END	
	ELSE
		BEGIN
			SET @sql = @sql + ' ISNULL(c.Street_Address, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(c.Suburb, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(c.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(c.Street_Post_Code, '''') AS [CurrentInvPostCode], '	
		END
		
    SET @sql = @sql + ' ISNULL(c.Tax_Number, '''') AS [TaxNumber], '
	--V6.4 Added Cell no and email
	SET @sql = @sql + '		ISNULL(c.Cell_No,'''') AS [Cell_No], '
	SET @sql = @sql + '		ISNULL(c.Orders_URL,'''') AS [Email], '	
    
	SET @sql = @sql + ' ISNULL(c.Delivery_Address, '''') AS [CurrentDeliverAddress], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Suburb, '''') AS [CurrentDeliverSuburb], '
	SET @sql = @sql + ' ISNULL(c.Delivery_City, '''') AS [CurrentDeliverCity], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Post_Code, '''') AS [CurrentDeliverPostCode] '

    SET @sql = @sql + ' FROM AC_Customers c '    
    SET @sql = @sql + ' WHERE c.AC_Customers_ID = ' + CONVERT(varchar(10), @AC_Customer_ID) + ' '
    
EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_Select
--Purpose       :POS Customer Lookup by filter arguments
--Functionality :Searches: Name, Trade/First Name, CellNo, WorkTelNo, HomeTelNo
--              :          Comment, Notes
--Parameters    :
--Date          :2002/04/09
--Authors       :TB
--MODS          :09/09/02 - Inserted ActiveID to SELECT ONLY Active Customers
--              :23/09/02 - Added Search on FirstNames filter
--              :30/12/02 - Added Search on Asset No in AS_Transactions.Comment
--              :           and CellNo, WorkTelNo, HomeTelNo from the VIEW
--              :03/02/03 - Added Search on text in AW_Comments.Comment
--              :29/10/05 - Commented the not yet implemented JOIN AC_Assets
--2004.3.7      :24/07/07 - Reworked as DYNAMIC sp to improve performance and
--              :           ELIMINATED using vw_AS_POS_Customers_Select
--              :24/07/07 - Replaced @Filter* input parameter NULL initialization
--              :           with NULLSTRING ('') initialization
--              :25/07/07 - Added new [CostPlusBilling] field
--              :25/07/07 - Added new [CostPlusCategory] field
--              :04/08/07 - Re-Ordered SELECT SEQUENCE in Customers grid replaced
--              :           TaxNumber and Suburb with CellNo and StreetAddress
--              :17/08/07 - Added new [TermsID] field for Promotions !!
--2004.3.8      :20/06/08 - Added Delivery_Post_Code AS [DelPostCode]
--2004.4.5      :13/06/09 - Added new [OverrideLimit] and [OverrideOverdue] field
--2004.4.8      :26/04/10 - Added new [FullName] field
--RL	V6.0	:Added FirstNames to order by
--V6.3	RL	2017-09-10	:Return Lup_AS_Rep_ID. Used as default Sales Rep dependant on system option
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Customers_Select]
	(    
    	 @CompanyID int,
    	 @Filter1 varchar(50) = '',
    	 @Filter2 varchar(50) = '',
    	 @Filter3 varchar(50) = ''
	)
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT DISTINCT '        -- DISTINCT is NB NB
    SET @sql = @sql + ' a.Surname AS [Name], '
    SET @sql = @sql + ' a.Firstnames AS [FirstNames], '
    SET @sql = @sql + ' a.Cell_No AS [CellNo], '
    SET @sql = @sql + ' a.Street_Address AS [StreetAddress], '

    SET @sql = @sql + ' a.City AS [City], '
    SET @sql = @sql + ' a.Initials AS [Initials], '
    SET @sql = @sql + ' a.Tax_Number AS [TaxNumber], '
    SET @sql = @sql + ' a.Suburb AS [Suburb], '
    SET @sql = @sql + ' a.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' a.Home_Tel_No AS [HomeTelNo], '
    SET @sql = @sql + ' ISNULL(a.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '         SELECT SUM(ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0)) '
    SET @sql = @sql + '         FROM AS_Transactions h '
    SET @sql = @sql + '         WHERE h.AC_Customers_ID = a.AC_Customers_ID AND '
    SET @sql = @sql + '               ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) <> 0 AND '
    SET @sql = @sql + '              (h.Sys_AW_Transaction_Types_ID = 3 OR '      --Invoice
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 4 OR '      --Refund
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 5 OR '      --Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 7 OR '      --Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 15 OR '     --Interest Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 18 OR '     --Settlement Discount
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 21 OR '     --Back Office Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 22) '       --EFT Payment
    SET @sql = @sql + '         ), 0) AS [AccountBalance], '

    SET @sql = @sql + ' a.Work_Email AS [WorkEmail], '
    SET @sql = @sql + ' a.Notes AS [Notes], '
    SET @sql = @sql + ' a.Sys_AC_Account_Status_ID AS [AccountStatusID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Types_ID AS [CustomerTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Groups_ID AS [CustomerGroupID], '
    SET @sql = @sql + ' s.[Description] AS [AccountStatus], '
    SET @sql = @sql + ' ct.[Description] AS [CustomerType], '
    SET @sql = @sql + ' g.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' a.[User_ID] AS [UserID], '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' -1 as [ActorTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Discount_Categories_ID, '
    SET @sql = @sql + ' a.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(tc.Tax_Rate, 0) AS [CustTaxRate], '
    SET @sql = @sql + ' a.Slu_AW_Credit_Terms_ID AS [TermsID], '
    SET @sql = @sql + ' e.Terms_Value AS [TermsValue], '
    SET @sql = @sql + ' f.[Description] AS [AccountType], '
    SET @sql = @sql + ' a.Sys_AC_Account_Types_ID AS [AccountTypeID], '
    SET @sql = @sql + ' a.AW_YesNo_Net_Billing_ID AS [NetBilling], '
    SET @sql = @sql + ' a.AW_YesNo_Purchase_Order_ID AS [PurchaseOrder], '
    SET @sql = @sql + ' a.AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling], '
    SET @sql = @sql + ' a.Lup_AC_Markup_Categories_ID AS [CostPlusCategory], '
    SET @sql = @sql + ' a.Delivery_Post_Code AS [DelPostCode], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Credit_Limit AS [OverrideLimit], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Overdue AS [OverrideOverdue], '
    SET @sql = @sql + ' a.AW_YesNo_Apply_Product_Levy AS [CustomerApplyLevy], '           
    SET @sql = @sql + ' a.AW_YesNo_Change_Doc_Details AS [ChangeDocDetails], '       
	--V6.3 RL 2017/09/11
	SET @sql = @sql + ' a.Lup_AS_Reps_ID AS [SalesPersonID], '

    SET @sql = @sql + ' ISNULL(Surname, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Suburb, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + City, '''') AS [FullName] '

    SET @sql = @sql + ' FROM AC_Customers a '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions b '
    SET @sql = @sql + '         ON a.AC_Customers_ID = b.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Comments c '
    SET @sql = @sql + '         ON c.AW_Comments_ID = b.AW_Comments_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Types ct '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '         ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Credit_Terms e '
    SET @sql = @sql + '         ON a.Slu_AW_Credit_Terms_ID = e.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Types f '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Groups g '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Groups_ID = g.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       a.Slu_AW_Active_ID = 1 '


    IF @Filter3 <> ''
        BEGIN
            SET @sql = @sql + '   AND ((a.Surname like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Surname like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Surname like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Firstnames like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Firstnames like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Firstnames like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Cell_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Cell_No like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Cell_No like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Work_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Work_Tel_No like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Work_Tel_No like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Home_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Home_Tel_No like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Home_Tel_No like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (b.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         b.Comment like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         b.Comment like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (c.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         c.Comment like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         c.Comment like ''%' + @Filter3 + '%'')) '

        END

    ELSE
	IF @Filter2 <> ''
		BEGIN 
            SET @sql = @sql + '   AND ((a.Surname like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Surname like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Firstnames like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Firstnames like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Cell_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Cell_No like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Work_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Work_Tel_No like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Home_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Home_Tel_No like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (b.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         b.Comment like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (c.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         c.Comment like ''%' + @Filter2 + '%'')) '
        END

    ELSE
	IF @Filter1 <> ''
        BEGIN
            SET @sql = @sql + '   AND ((a.Surname like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Firstnames like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Cell_No like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Work_Tel_No like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Home_Tel_No like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (b.Comment like ''%' + @Filter1 + + '%'' ) OR '
            SET @sql = @sql + '        (c.Comment like ''%' + @Filter1 + + '%'' )) '
        END
--RGL 6.0 Added FirstNames to order by
    SET @sql = @sql + '   ORDER BY [Name], [FirstNames] '

EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-- *** NOT USED ***
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Day_End
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2001/01/05
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AS_POS_Day_End
    (
    	@TillID int = 0,
    	@CashierID int = 0
    )

AS

SET NOCOUNT ON

	DECLARE @Date datetime
	SET @Date = getdate()

	IF @TillID > 0 
		UPDATE AS_Transactions
        SET Day_End = @Date
		WHERE Day_End IS NULL AND
              Lup_AS_Tills_ID = @TillID
	ELSE
		UPDATE AS_Transactions
        SET Day_End = @Date
		WHERE Day_End IS NULL AND
              Lup_AS_Cashiers_ID = @CashierID


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Latest_Transactions
--Purpose       :POS ALL latest <n> transactions
--Date          :2011/09/04
--Authors       :TB
--MODS:         :
--V6.3	RL	2017/04/04	:Added transaction note so I can display window if note exists for conformation
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AS_POS_Latest_Transactions]
    (
        @CompanyID int,
        @TopNo smallint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT TOP ' + CONVERT(varchar(10), @TopNo) + ' '

    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' h.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [Type], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, ''''))) + '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + c.Firstnames, ''''))) + '
    SET @sql = @sql + ' ''('' + RTRIM(LTRIM(CONVERT(varchar(10), c.AC_Customers_ID))) + '')'' AS [Customer], '
    SET @sql = @sql + ' h.Transaction_Date AS [Date], '
    SET @sql = @sql + ' h.Transaction_Number AS [Doc No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Asset], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) AS [Amount], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Order No], '
    SET @sql = @sql + ' ISNULL(u.UserName, '''') AS [Cashier], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(m.Comment, '''') AS [TransactionComment] '

    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Comments m '
    SET @sql = @sql + '          ON h.AW_Comments_ID = m.AW_Comments_ID '


    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 1 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 2 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 13 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 16 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 17 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 23 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 24) '


    SET @sql = @sql + ' ORDER BY h.AS_Transactions_ID DESC '


--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Login
--Purpose       :Select POS Login User
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--MODS:         :16/07/03 - Changed user Fullname to Firstname/Surname
--2004.4.8      :Added check validation on ACTIVE users only
--V6.4		RL	:2018-02-14 - Return User Email
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Login]
    (
        @Username varchar(50) = '',
        @Password varchar(50) = '',
        @CompanyID int = 0,
        @TillID int =0
    )

AS

SET NOCOUNT ON

    SELECT DISTINCT 
        u.UserName, 
        u.[Password], 
        cu.AW_User_Companies_ID, 
        ut.Lup_AS_Tills_ID, 
        u.AW_Users_ID as [ID],
        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') as [Fullname],
        ISNULL(u.User_Email,'') AS [User Email]
    FROM AW_Users u 
        INNER JOIN AW_Users_Tills ut
            ON u.AW_Users_ID = ut.AW_Users_ID 
        INNER JOIN AW_Company_Users cu
            ON u.AW_Users_ID = cu.AW_Users_ID 
    WHERE u.UserName = @UserName AND
          u.[Password] = @Password AND
          cu.AW_User_Companies_ID = @CompanyID AND
          ut.Lup_AS_Tills_ID = @TillID AND
          u.Slu_AW_Active_ID = 1


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Lookups_Select
--Purpose       :POS Look-ups
--Date          :2002/02/06
--Authors       :TB
--Version       :1.0.0
--MODS          :09/07/03 - Added select ONLY ACTIVE Sys_AW_Payment_Methods from
--              :           NEW Slu_AW_Active_ID column in Sys_AW_Payment_Methods
--              :           (modified esspecially for !! Autowiel !!)
--              :31/01/04 - Added new 'CBilling' Lookup from Slu_AS_Card_Institutions
--              :29/02/04 - Added new Central Billing 'Fail Reasons' Lookup
--              :02/04/04 - Added new Central Billing 'Billing Providers' Lookup
--              :03/04/04 - Removed 'CBilling' Lookup from Slu_AS_Card_Institutions
--              :09/04/04 - Added new Central Billing 'Claim Codes' Lookup
--              :20/08/04 - Added new Lup_AC_Customer_Groups Lookup for Add/Edit
--2004.3.7      :24/07/07 - Added new Customer Cost+Plus as 'CostPlus'
--              :01/09/07 - Added ACTIVE validation in 'Discounts' for Customer Discounts
--2004.3.8      :29/05/08 - Added ORDER BY for Reps
--2004.4.8      :11/05/10 - Added fetch only Active Reps
--V6.4	RL	2018-04-11	:Option Methods. Removed i-Pay from drop down list
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Lookups_Select]
    (
       @DataMember varchar(20),
       @CompanyID int,
       @Filter int = 0
    )

AS

SET NOCOUNT ON

    IF @DataMember = 'Account Statuses'
        SELECT Sys_AC_Account_Status_ID as [ID],
               [Description]
        FROM Sys_AC_Account_Status
    
    ELSE
    IF @Datamember = 'Banks'
        SELECT Slu_AW_Banks_ID as [ID],
               [Description]
        FROM Slu_AW_Banks
    
    ELSE
    IF @DataMember = 'Customer Type'
        SELECT Lup_AC_Customer_Types_ID as [ID],
               [Description]
        FROM Lup_AC_Customer_Types
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @DataMember = 'Methods'
        SELECT Sys_AW_Payment_Methods_ID as [ID],
               [Description],
               Sys_AW_Institution_Types_ID as [InstitutionType]
        FROM Sys_AW_Payment_Methods
        WHERE Slu_AW_Active_ID = 1 AND
              NOT (Sys_AW_Payment_Methods_ID = 1 OR
                   Sys_AW_Payment_Methods_ID = 2 OR
                   Sys_AW_Payment_Methods_ID = 7 OR
                   Sys_AW_Payment_Methods_ID = 10 OR
                   Sys_AW_Payment_Methods_ID = 14)
    
    ELSE
    IF @DataMember = 'Institutions'
        SELECT Slu_AS_Card_Institutions_ID as [ID],
               [Description]
        FROM Slu_AS_Card_Institutions
        WHERE Sys_AW_Institution_Types_ID = 3
    
    ELSE
    IF @DataMember = 'Workstations'
        SELECT Lup_AW_Workstations_ID as [ID],
               [Description]
        FROM Lup_AW_Workstations
        WHERE AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'Tills'
        SELECT Lup_AS_Tills_ID as [ID],
               [Description]
        FROM Lup_AS_Tills
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @DataMember = 'Reps'
        SELECT Lup_AS_Reps_ID as [ID],
               [Description]
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
        ORDER BY [Description]

    ELSE
    IF @DataMember = 'Asset Types'
        SELECT Lup_AC_Asset_Types_ID as [ID],
               [Description]
        FROM Lup_AC_Asset_Types
    
    ELSE
    IF @DataMember = 'Users'
        SELECT a.AW_Users_ID as [ID],
               a.UserName  
        FROM AW_Users a
            JOIN AW_Company_Users b
                ON a.AW_Users_ID = b.AW_Users_ID
        WHERE b.AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'PLU'
        SELECT Lup_AP_PLU_Tabs_ID as [ID],
               [Description],
               Tab_No as [Tab]
        FROM Lup_AP_PLU_Tabs
        WHERE AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'Types'
        SELECT Lup_AP_Product_Types_ID as [ID],
               [Description]
        FROM Lup_AP_Product_Types 
        WHERE AW_User_Companies_ID = @CompanyID
        UNION SELECT 0, '<All>' 
        ORDER BY [Description]
    
    ELSE
    IF @DataMember = 'Switch1'
        SELECT AP_Switch1_ID as [ID],
               [Description]
        FROM AP_Switch1
        WHERE AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'Filter_Switch2'
        SELECT AP_Switch2_ID as [ID],
               [Description],
               AP_Switch1_ID as [FKID]
        FROM AP_Switch2 
    
    ELSE
    IF @DataMember = 'Filter_Switch3'
        SELECT AP_Switch3_ID as [ID],
               [Description],
               AP_Switch2_ID as [FKID]
    FROM AP_Switch3
    
    ELSE
    IF @DataMember = 'Discounts'
    	SELECT AS_Discount_Categories_Groups_ID as [ID],
               Lup_AP_Discount_Groups_ID as [GroupID],
               Lup_AC_Discount_Categories_ID as [CategoryID],
               Discount_Percentage as [Perc]
    	FROM AS_Discount_Categories_Groups
        WHERE Slu_AW_Active_ID = 1

    ELSE
    IF @DataMember = 'Fail Reasons'
        SELECT Lup_AP_Fail_Reasons_ID as [ID],
               [Description]
        FROM Lup_AP_Fail_Reasons
        ORDER BY Lup_AP_Fail_Reasons_ID

    ELSE
    IF @DataMember = 'Billing Providers'
        SELECT Lup_AS_CBilling_Providers_ID as [ID],
               [Description]
        FROM Lup_AS_CBilling_Providers
        ORDER BY [Description]

    ELSE
    IF @DataMember = 'Claim Codes'
        SELECT Lup_AP_Claim_Codes_ID as [ID],
               [Description]
        FROM Lup_AP_Claim_Codes
--        ORDER BY [Description]

    ELSE
    IF @DataMember = 'Customer Groups'
        SELECT Lup_AC_Customer_Groups_ID as [ID],
               [Description]
        FROM Lup_AC_Customer_Groups
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @DataMember = 'CostPlus'
    	SELECT AS_Markup_Categories_Groups_ID as [ID],
               Lup_AP_Markup_Groups_ID as [GroupID],
               Lup_AC_Markup_Categories_ID as [CategoryID],
               Markup_Percentage as [Perc]
    	FROM AS_Markup_Categories_Groups

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Open_Jobcards
--Purpose       :POS ALL OPEN QUOTES, JOBCARDS and SALES ORDERS for ACTIVE Customers
--Functionality :
--Date          :2010/01/23
--Authors       :TB
--MODS:         :
--2004.4.8      :07/05/10 - Changed JOINS to LEFT JOIN and removed Active validation on Customers
--2004.5.0      :14/12/10 - Added options to list Manager Console Daily Summary lists
-------------------------------------------------------------------------------

CREATE                        PROCEDURE sp_AS_POS_Open_Jobcards
    (
        @CompanyID int,
        @Option tinyint,
        @QuoteDays smallint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @filter varchar(1000),
            @LastDayEnd datetime



	SELECT TOP 1 @LastDayEnd = Day_End
    FROM AS_Transactions
    WHERE AW_User_Companies_ID = @CompanyID
    ORDER BY Day_End DESC




    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' h.Sys_AW_Transaction_Types_ID AS [TranTypeID], '

    SET @sql = @sql + ' h.Transaction_Number AS [No], '
    SET @sql = @sql + ' h.Transaction_Date AS [Date], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, ''''))) + '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + c.Firstnames, ''''))) + '
    SET @sql = @sql + ' ''('' + RTRIM(LTRIM(CONVERT(varchar(10), c.AC_Customers_ID))) + '')'' AS [Customer], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Asset], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) AS [Amount], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Order No], '
    SET @sql = @sql + ' ISNULL(u.UserName, '''') AS [Cashier], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [ActiveID] '

    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @Option < 4    --Open Stuff
        BEGIN
            SET @sql = @sql + ' AND h.Slu_AW_Active_ID = 1 '
        END


    SET @filter = ' '


    IF @Option = 1    --Open Job Cards
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 2 '
        END

    IF @Option = 2   --Open Sales Orders
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 16 '
        END

    IF @Option = 3   --Open Quotes
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 1 ' +
                          ' AND h.Transaction_Date >= DATEADD(day, -' + CONVERT(varchar(10), @QuoteDays) + ' , getdate()) '
        END


    IF @Option = 4    --Daily Summary Quotes
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 1 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 5    --Daily Summary Job Cards
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 2 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 6    --Daily Summary Sales Orders
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 2 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 7    --Daily Summary Invoices
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 3 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 8    --Daily Summary Refunds
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 4 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 9    --Daily Summary Journals
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 5 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 10    --Daily Summary POS Receipts
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 7 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 11    --Daily Summary Back Office Receipts
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 21 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 12    --Daily Summary EFT Receipts
        BEGIN
            SET @filter = ' AND h.Sys_AW_Transaction_Types_ID = 22 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 13    --Daily Summary Cash Sales
        BEGIN
            SET @filter = ' AND (h.Sys_AW_Transaction_Types_ID = 3 ' +
                          '  OR  h.Sys_AW_Transaction_Types_ID = 4) ' +
                          ' AND h.Payment_Amount <> 0 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 14    --Daily Summary Credit Sales
        BEGIN
            SET @filter = ' AND (h.Sys_AW_Transaction_Types_ID = 3 ' +
                          '  OR  h.Sys_AW_Transaction_Types_ID = 4) ' +
                          ' AND h.Payment_Amount = 0 ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END

    IF @Option = 15    --Daily Summary Total Sales
        BEGIN
            SET @filter = ' AND (h.Sys_AW_Transaction_Types_ID = 3 ' +
                          '  OR  h.Sys_AW_Transaction_Types_ID = 4) ' +
                          ' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
        END


    SET @sql = @sql + @filter

    SET @sql = @sql + ' ORDER BY [TranID], [Date] '


--PRINT @sql

EXEC (@sql)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Payment_Methods_Select
--Purpose       :Return list of Payment Methods
--Output        :Returns POS Payment Methods from Sys_AW_Payment_Methods
--              :
--Date          :2002/01/30
--Authors       :TB
--Version       :1.0.0
--Mods          :2002/01/30 - Now select ALL payment methods
-------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AS_POS_Payment_Methods_Select
	(
		@CompanyID int,
		@Date smalldatetime
	)
AS
	SELECT 
		Sys_AW_Payment_Methods_ID AS [ID], 
		[Description], 
		@CompanyID AS [CompanyID],  
		@Date AS [Cashed_Up]       
	FROM Sys_AW_Payment_Methods

-- 	WHERE Sys_AW_Payment_Methods_ID <> 1 AND    -- <None>
-- 	      Sys_AW_Payment_Methods_ID <> 7 AND    -- Payment
-- 		  Sys_AW_Payment_Methods_ID <> 10       -- COD







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Products_Select
--Purpose       :NEW POS Product Search (Normal) Results for 3 ARGUMENTS max
--Functionality :Uses:    vw_AS_POS_Products    -- now REDUNDANT
--              :         vw_AS_POS_Products_Top_20_Perc
--              :         vw_AS_POS_Products_Gross_Contribution
--Date          :2002/02/16
--Authors       :TB
--MODS          :26/07/02 - Changed Previous search to WILDCARD(*) search and
--              :20/08/02 - Added new Search String ARGUMENTS: '+', '-', and '#'
--              :           '+' = by MARGIN DESCENDING     (GP Value: High to Low) 
--              :           '-' = by MARGIN ASCENDING      (GP Value: Low to High)
--              :           '#' = by Unit Price ASCENDING  (Price: Cheap to Expensive)
--              :           '%' = by GP% DESCENDING        (GP%: High to Low)
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :28/05/03 - Changed SORT ORDER for NORMAL search from [Description]
--              :           to [Qty on Hand] DESC, [Description]
--              :15/11/03 - Added KEYWORDS field as a search filter
--              :28/02/04 - Added [GrossProfit] SORT ORDER for MARGIN sorts (+ & -)
--              :19/03/04 - Top 20% by GP% now returned using '%' instead of nullstring
--              :19/03/04 - Modified Product Search to return ZERO rows if nullstring
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS in remaining views and
--              :           2. eliminated using vw_AS_POS_Products (the default search)
--              :           3. by moving its code to the top if this SP
--              :26/07/07 - Added p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID]
--              :29/07/07 - Added p.Standard_Cost as [Std Cost]
--              :09/08/07 - Removed unused [Job_Reserved] field
--              :26/08/07 - Added p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem]
--2004.3.8      :10/05/08 - Removed JOIN with Lup_AP_Product_Departments and its
--              :           Min_GP_Percentage field and renamed the alias of the
--              :           Max_Discount_Perc to [MinGPPerc] and the alias of the
--              :           Slu_AW_YesNo_Max_Discount_Perc to [UseMinGPPerc] (new Profit Protector)
--2004.3.9      :05/06/08 - Converted [Qty on Hand] to decimal(9, 3) (Sales Order formatting)
--              :05/06/08 - Added p.Pack_Mass AS [Pack Mass] (Sales Orders)
--              :16/06/08 - Removed unused [Price], [Date], [UserID], [Tax Code]
--              :16/06/08 - Rename [OpenOrderQty] to [On Order]
--2004.4.2      :24/10/08 - Added new field [Standard Margin]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.4.8      :28/03/10 - Added WILDCARD Pattern Matching using _ (underscore) character
--              :           in Normal Search (@SearchType = 0) for the 3 @Filter(n)
--        ****  :02/09/10 - Added validation in WILDCARD search string: AND ISNUMERIC(@Filter1) > 0
--        ****  :02/09/10 - REMOVED WILDCARD search
--2004.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_POS_Products_Select]
    (    
        @CompanyID int,
        @Filter1 varchar(50) = '',
        @Filter2 varchar(50) = '',
        @Filter3 varchar(50) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @SearchType tinyint
--             @Wildcard varchar(50),
--             @wc1 varchar(50),
--             @wc2 varchar(50)

--     SET @Wildcard = ''
--     SET @wc1 = ''
--     SET @wc2 = ''

	--DECLARE @Include_Res_Stock_Validation	Varchar(5)
	
	--SET @Include_Res_Stock_Validation = '1'
	
	--SELECT @Include_Res_Stock_Validation = ISNULL(Control_Value,'0')
	--FROM Sys_AW_Options
	--WHERE Control_Name = 'chkStockReservedJob'

	--IF @Include_Res_Stock_Validation = '1'
	--BEGIN



	DECLARE @POS_Products_Temp table
	(
		[Description] [varchar](50) NOT NULL,
		[Code] [varchar](20) NOT NULL,
		[Last Cost] [money] NULL,
		[Standard Discount] [int] NOT NULL,
		[Price 1] [money] NULL,
		[Promotion] [money] NULL,
		[Qty on Hand] [decimal](9, 3) NULL,
		[PromoProductID] [int] NULL,
		[Avg Cost] [money] NULL,
		[Gross Margin] [money] NULL,
		[Price 2] [money] NULL,
		[Unit Price] [money] NULL,
		[Qty] [decimal](9, 3) NULL,
		[Discount %] [int] NOT NULL,
		[Discount] [int] NOT NULL,
		[ID] [int] NOT NULL,
		[TypeID] [int] NULL,
		[Tax Rate] [decimal](5, 2) NULL,
		[Pack Mass] [decimal](9, 3) NULL,
		[Pack Volume] [decimal](9, 3) NULL,
		[On Hand] [decimal](9, 3) NULL,
		[Edit Price] [tinyint] NULL,
		[Edit Discount] [tinyint] NULL,
		[Keywords] [varchar](50) NULL,
		[GroupID] [smallint] NULL,
		[Reserved] [decimal](9, 3) NULL,
		[On Order] [decimal](9, 3) NULL,
		[CompanyID] [int] NOT NULL,
		[Active] [tinyint] NULL,
		[NonStockItem] [tinyint] NULL,
		[Average Margin] [money] NULL,
		[MinGPPerc] [decimal](5, 2) NOT NULL,
		[UseMinGPPerc] [tinyint] NULL,
		[GrossProfit] [money] NULL,
		[CostPlusGroupID] [smallint] NULL,
		[IsCostPlusItem] [tinyint] NULL,
		[Std Cost] [money] NULL,
		[Standard Margin] [money] NULL,
		[SKU_Code] [varchar](20) NULL,
		[Supercession] [varchar](20) NULL,
		[Alternate_Code1] [varchar](20) NULL,
		[Alternate_Code2] [varchar](20) NULL,
		[SellBelowCost] [tinyint] NULL,
		[ConsignmentStock] [decimal](9, 3) NULL,	
		UniqueID [int] IDENTITY(1,1) PRIMARY KEY		
	)
	
    -------------------------------------------------------------------------------
    SET @SearchType = 0

    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '+' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '+' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '+' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 1
        END

    ELSE
    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '-' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '-' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '-' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 2
        END

	ELSE
    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '#' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '#' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '#' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 3
        END

	ELSE
    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '%' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '%' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '%' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 4
        END

    ELSE
    IF LTRIM(RTRIM(@Filter1)) = ''        --> Returns an EMPTY rs
        BEGIN
            SET @SearchType = 5
        END

--     --> WILDCARD Pattern Matching using _ (underscore) character
--     IF LTRIM(RTRIM(@Filter1)) <> '' AND ISNUMERIC(@Filter1) > 0
--         BEGIN
--             SET @wc1 = REPLACE(LTRIM(RTRIM(@Filter1)), '/', '')
--             SET @wc2 = REPLACE(@wc1, '-', '')
--             IF LEN(@wc2) >= 5 AND ISNUMERIC(LEFT(@wc2, 3)) > 0
--                 BEGIN
--                     SET @Wildcard = 
--                         CASE LEN(@wc2)
--                              WHEN 5 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2)
--                              WHEN 6 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 1)
--                              WHEN 7 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '_' + RIGHT(@wc2, 2)
--                              WHEN 8 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '__' + RIGHT(@wc2, 2)
--                         END    
--                     SET @Wildcard = '%' + @Wildcard + '%'
--                 END
--         END

--> Normal Search BY DESCRIPTION ASCENDING (ANY ONE of the 3 arguments)
    IF @SearchType = 0
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  @Filter3 + '%'
					SET @Filter2 = '%' +  @Filter2 + '%'
					SET @Filter1 = '%' +  @Filter1 + '%'

                	SELECT 
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code], 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Qty],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.On_Hand AS [On Hand], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],                        
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
                	FROM AP_Products p  
                		LEFT JOIN Sys_AW_Tax_Codes tc
                            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
					WHERE p.AW_User_Companies_ID = @CompanyID AND 
                          p.Slu_AW_Active_ID = 1 AND
                        ((p.Description like @Filter1 AND
--                          p.Description like @Wildcard OR
                          p.Description like @Filter2 AND
                          p.Description like @Filter3 ) OR 
                         (p.Product_Code like @Filter1 AND
                          p.Product_Code like @Filter2 AND
                          p.Product_Code like @Filter3) OR
                         (p.SKU_Code like @Filter1 AND
                          p.SKU_Code like @Filter2 AND
                          p.SKU_Code like @Filter3) OR
                         (p.Supercession like @Filter1 AND
                          p.Supercession like @Filter2 AND
                          p.Supercession like @Filter3) OR
                         (p.Alternate_Code1 like @Filter1 AND
                          p.Alternate_Code1 like @Filter2 AND
                          p.Alternate_Code1 like @Filter3) OR
                         (p.Alternate_Code2 like @Filter1 AND
                          p.Alternate_Code2 like @Filter2 AND
                          p.Alternate_Code2 like @Filter3) OR
                         (p.Keywords like @Filter1 AND
                          p.Keywords like @Filter2 AND
                          p.Keywords like @Filter3))
					ORDER BY [Qty on Hand] DESC, p.Description


				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  @Filter2 + '%'
					SET @Filter1 = '%' +  @Filter1 + '%'

                	SELECT 
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code], 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Qty],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.On_Hand AS [On Hand], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
                	FROM AP_Products p  
                		LEFT JOIN Sys_AW_Tax_Codes tc
                            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
					WHERE p.AW_User_Companies_ID = @CompanyID AND 
                          p.Slu_AW_Active_ID = 1 AND
                        ((p.Description like @Filter1 AND
--                          p.Description like @Wildcard OR
                          p.Description like @Filter2) OR 
                         (p.Product_Code like @Filter1 AND
                          p.Product_Code like @Filter2) OR
                         (p.SKU_Code like @Filter1 AND
                          p.SKU_Code like @Filter2) OR
                         (p.Supercession like @Filter1 AND
                          p.Supercession like @Filter2) OR
                         (p.Alternate_Code1 like @Filter1 AND
                          p.Alternate_Code1 like @Filter2) OR
                         (p.Alternate_Code2 like @Filter1 AND
                          p.Alternate_Code2 like @Filter2) OR
                         (p.Keywords like @Filter1 AND
                          p.Keywords like @Filter2))
					ORDER BY [Qty on Hand] DESC, p.Description


				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  @Filter1 + '%'

                	SELECT 
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code], 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Qty],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.On_Hand AS [On Hand], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
                	FROM AP_Products p  
                		LEFT JOIN Sys_AW_Tax_Codes tc
                            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
					WHERE p.AW_User_Companies_ID = @CompanyID AND 
                          p.Slu_AW_Active_ID = 1 AND
                         (p.Description like @Filter1 OR
--                          p.Description like @Wildcard OR
                          p.Product_Code like @Filter1 OR
                          p.SKU_Code like @Filter1 OR
                          p.Supercession like @Filter1 OR
                          p.Alternate_Code1 like @Filter1 OR
                          p.Alternate_Code2 like @Filter1 OR
                          p.Keywords like @Filter1)
					ORDER BY [Qty on Hand] DESC, p.Description

				END
		END


--> BY Gross Contibution DESCENDING (ANY ONE of the 3 arguments end with '+')
	ELSE
    IF @SearchType = 1
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] DESC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] DESC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] DESC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] DESC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] DESC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> BY Gross Contibution ASCENING (ANY ONE of the 3 arguments end with '-')
	ELSE
    IF @SearchType = 2
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] ASC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] ASC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> BY Unit Price ASCENING (ANY ONE of the 3 arguments end with '#')
	ELSE
    IF @SearchType = 3
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [Price 1] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [Price 1] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [Price 1] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [Price 1] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [Price 1] ASC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)                    				
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [Price 1] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> BY GP% DESC (ANY ONE of the 3 arguments end with '%')
	ELSE
    IF @SearchType = 4
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [Gross Margin] DESC                          
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))					                          
					ORDER BY [Gross Margin] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [Gross Margin] DESC        
                          
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					--ORDER BY [Qty on Hand] DESC, [Gross Margin] DESC					                          
					ORDER BY [Gross Margin] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
                    ORDER BY [Gross Margin] DESC      
                          
                    Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)                    
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					--ORDER BY [Qty on Hand] DESC, [Gross Margin] DESC                          
					ORDER BY [Gross Margin] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> Returns an EMPTY rs
    ELSE
    IF @SearchType = 5
        BEGIN
        	SELECT 
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.Last_Cost AS [Last Cost], 
                0 as [Standard Discount],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
        		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
        		p.Average_Cost AS [Avg Cost], 
        		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
        		p.Pack_Size AS [Qty],
                0 as [Discount %],
                0 as [Discount],
        		p.AP_Products_ID as [ID],
        		p.Lup_AP_Product_Types_ID as [TypeID],
        		tc.Tax_Rate as [Tax Rate], 
                p.Pack_Mass AS [Pack Mass], 
        		p.Pack_Volume AS [Pack Volume], 
        		p.On_Hand AS [On Hand], 
        		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
        		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
        		p.Keywords as [Keywords],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                p.AW_User_Companies_ID AS [CompanyID],
                p.Slu_AW_Active_ID AS [Active],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Standard_Cost AS [Std Cost],
                CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 9
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Invoice_Print
--Purpose       :POS Invoice printing
--Parameters    :
--Date          :2002/04/12
--Authors       :TB
--MODS:         :12/04/02 - Added Time extracted from Transaction_Date
--              :18/04/02 - Added AW_Users.UserName
--              :21/04/02 - Added (AC_Customers_ID) to Customer_Number
--              :22/04/02 - Changed Customer Addresses from Physical to Postal
--              :10/06/02 - Added Company Tel_No & Company Fax_No fields
--              :18/07/02 - Added Discount % per Line Item as [DetailDiscPerc]
--              :10/09/02 - Convert Discount % per Line from SMALLMONEY to MONEY
--              :30/12/02 - Added t.SmallComment AS [Comment] for POS Asset No
--              :26/05/03 - Added ISNULL validation to customer address fields
--              :26/05/03 - Added Cell/Home/Work telephone number (next to Post Code)
--              :09/07/03 - Added Tax_Number (VATNo) effective 1 APR 2004 per SARS
--              :29/01/04 - Added [TranTypeID] to print a PICKLIST with a JOBCARD
--              :09/02/04 - Added [JobSource] to print any JOBCARD source docs
--              :07/06/04 - Added t.AW_User_Companies_ID to locate Company Logo
--              :           path parameter in SpSPOSPrint.CCutSheetLogoA4
--              :17/08/04 - Added p.Pack_Mass to aggregate invoice load mass
--              :21/12/04 - Added XREF to Sys_AW_Payment_Methods and PRINT
--              :08/01/05 - Added [JobRefNo] to print on new MAXIPREST layout
--              :02/02/05 - Added [TextMessage] to print on all invoice documents
--              :19/05/05 - Removed Payment Method from primary SELECT and pre-fetch
--2004.2.4      :28/08/05 - Added t.Amount AS TransactionAmount for OPOS printing
--              :28/10/05 - Added Street and Delivery Adresses
--              :28/10/05 - Added System Option address choice using @WhichAddress
--2004.2.7      :13/04/06 - Replaced SELECT vw_AS_Transactions with AS_Transactions
--2004.3.1      :21/08/09 - Rearranged order of telephone numbers: Work/Cell/Home
--2004.3.2      :08/10/06 - Added [SerialNo] fields
--2004.3.3      :23/11/06 - Added [NameType] for Company Trading Name
--2004.3.4      :23/11/06 - Added Old_Customer_Number as [MerchantNo] for Card Companies
--              :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :05/07/08 - Renamed Job XRef from AS_Transaction_Sources
--              :           from 'Jobcard No: ' to 'Sales Order/Job No: '
--2004.4.5      :18/07/09 - Converted into DYNAMIC script to include NEW
--              :           POS Document Print Order of items settings
--2004.4.8      :17/04/10 - Reworked setting DEFAULT message and Added new QUOTE message
--2004.5.0      :26/01/11 - Added [Emails] for all customer e-mail addresses
--              :26/01/11 - Added [CompanyEmail] for company e-mail address
--2004.5.3      :18/07/11 - Added REPLACE syntax to REMOVE single APOSTROPHE in MESSAGES text
--2004.5.7 RGL  :2012-09-20 - Added check to to print tradeing name with company name
--2004.5.8 RGL  :2013-02-20 - Fixed check to to print tradeing name with customer and not company name
--RL	V6.0	:2014-01-28 - Use product print description instead of description
--RL	V6.0	:2014-04-22 - Return Customer ID
--RL	V6.0	:2014-07-19 - Return TDHeader & TDDetail
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
--RL	V6.3	:2017-03-21 - Reworked Reg_No And Millage
--RL	V6.4	:2018-04-12 - Cell_No and EMail for document has been moved to AS_Transactions_Address_Detail table
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
    (
    	@TransactionID int
    )
AS

SET NOCOUNT ON

    DECLARE @SortOrder tinyint,
            @TranTypeID tinyint,
            @Message varchar(100),
            @DefaultMessage varchar(100),
            @QuoteMessage varchar(100),
            @PrintDefaultMessage varchar(10),
            @PrintQuoteMessage varchar(10),
            @OrderFilter tinyint,
            @sql varchar(8000)
            
	DECLARE @Customer_Name varchar(100),
 			@Inv_Address1 varchar(40),
 			@Inv_Address2 varchar(40),
 			@Inv_City varchar(30),
			@Inv_Code varchar(10),
			@Tax_Number varchar(16),
			@AW_YesNo_Invoice tinyint,
			
			@Delivery_Address varchar(40),
			@Delivery_Suburb varchar(40),
			@Delivery_City varchar(30),
			@Delivery_Post_Code varchar(10),
			@AW_YesNo_Delivery_Address tinyint,
			@AC_Customers_ID int,
			@IPay_Link varchar(100),
			@EMail varchar(100),
			@Cell_No varchar(100)
            
    --> Get TranTypeID
    SELECT @TranTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TransactionID

    --> Get POS Document Print Sort Order settings
    SELECT @SortOrder = ISNULL(Control_Value, 0)
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
    Control_Type = 'CheckBox' AND
    Control_Name = 'chkPOSPrintSortOrder'
    
    --> Get POS Document Print Sort Order Filter
    SELECT @OrderFilter = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
    Control_Name = 'optPOSSortOrderFilter' AND
    Control_Value = 'True'

    --------------------------------------------------------------------
    -- Set the MESSAGES text
    --------------------------------------------------------------------
    --> Get the DEFAULT Message text
    SELECT TOP 1 @DefaultMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'

    --> Get the DEFAULT Message CheckBox setting
    SELECT TOP 1 @PrintDefaultMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    --> Get the QUOTE Message text
    SELECT TOP 1 @QuoteMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSQuoteText'

    --> Get the QUOTE Message CheckBox setting
    SELECT TOP 1 @PrintQuoteMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSQuoteText'

    SET @Message = ''

    IF @TranTypeID = 1        --Quote message
        BEGIN
            IF @PrintQuoteMessage = '1' SET @Message = @QuoteMessage
        END
    ELSE                      --Default message
        BEGIN
            IF @PrintDefaultMessage = '1' SET @Message = @DefaultMessage
        END

    SET @Message = LEFT(@Message, 80)
        
    SET @AC_Customers_ID = 0
    SET @AW_YesNo_Invoice = 0
    SET @AW_YesNo_Delivery_Address = 0
    
    SELECT @AC_Customers_ID = AC_Customers_ID
    FROM AS_Transactions_Address a
	INNER JOIN AS_Transactions_Address_Detail d ON
		a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
	WHERE a.AS_Transactions_ID = @TransactionID

    IF @AC_Customers_ID <> 0
	BEGIN
		SELECT	@Customer_Name = REPLACE(ISNULL(Customer_Name, ''), '''', ''),
				@Inv_Address1 = REPLACE(ISNULL(Inv_Address1, ''), '''', ''),
				@Inv_Address2 = REPLACE(ISNULL(Inv_Address2, ''), '''', ''), 
				@Inv_City = REPLACE(ISNULL(Inv_City, ''), '''', ''),
				@Inv_Code = REPLACE(ISNULL(Inv_Code, ''), '''', ''),
				@Tax_Number = REPLACE(ISNULL(Tax_Number, ''), '''', ''),
				@AW_YesNo_Invoice = AW_YesNo_Invoice,
				@Delivery_Address = REPLACE(ISNULL(Delivery_Address, ''), '''', ''),
				@Delivery_Suburb = REPLACE(ISNULL(Delivery_Suburb, ''), '''', ''),
				@Delivery_City = REPLACE(ISNULL(Delivery_City, ''), '''', ''),
				@Delivery_Post_Code = REPLACE(ISNULL(Delivery_Post_Code, ''), '''', ''),
				@AW_YesNo_Delivery_Address = AW_YesNo_Delivery_Address,
				--V6.4 Added to Inv/Del Address
				@Cell_No = REPLACE(ISNULL(Cell_No, ''), '''', ''),
				@EMail = REPLACE(ISNULL(EMail, ''), '''', '')
		FROM AS_Transactions_Address a
		INNER JOIN AS_Transactions_Address_Detail d ON 
			a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
		WHERE a.AS_Transactions_ID = @TransactionID
	END    
	
	--V6.4 Added i-Pay link to show on Invoices
	IF @TranTypeID = 3
	BEGIN
		SELECT TOP 1 @IPay_Link = ISNULL(IPay_URL,'')
		FROM AS_Transaction_Payments_IPay
		WHERE AS_Transactions_ID = @TransactionID
		AND Ipay_Action IN ('PAY SUC','PAYDONE')
	END

	SELECT @IPay_Link = ISNULL(@IPay_Link,'')
	
    --------------------------------------------------------------------

	SET @sql = ' ' 
	SET @sql = @sql + ' DECLARE @WhichAddress tinyint, '
	SET @sql = @sql + ' @WhichName tinyint, '
	SET @sql = @sql + ' @PaymentMethod varchar(20) '

	SET @sql = @sql + ' SET @WhichAddress = 0 '

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SET @sql = @sql + ' SELECT @WhichAddress = ISNULL(Control_Index, 0) '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Type = ''OptionButton'' AND '
	SET @sql = @sql + ' Control_Name = ''optPOSPrintAddress'' AND '
	SET @sql = @sql + ' Control_Value = ''True'' '

	SET @sql = @sql + ' SELECT TOP 1 @WhichName = ISNULL(Control_Value, ''0'') '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Index = 0 AND '
	SET @sql = @sql + ' Control_Type = ''CheckBox'' AND '
	SET @sql = @sql + ' Control_Name = ''chkPOSPrintTradeName'' '

	SET @sql = @sql + ' SELECT TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''''), 20) '
	SET @sql = @sql + ' FROM AS_Transactions_Transactions att '
	SET @sql = @sql + ' LEFT JOIN AS_Transaction_Payments tp '
	SET @sql = @sql + ' ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID '
	SET @sql = @sql + ' LEFT JOIN Sys_AW_Payment_Methods pm '
	SET @sql = @sql + ' ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID '
	SET @sql = @sql + ' WHERE att.Source_AS_Transactions_ID = ' + CONVERT(varchar(20), @TransactionID)
	SET @sql = @sql + ' ORDER BY att.Source_AS_Transactions_ID '

    --------------------------------------------------------------------------------------------------
    --The query starts here
    --------------------------------------------------------------------------------------------------
	SET @sql = @sql + ' SELECT '

	IF @AW_YesNo_Invoice = 1
	BEGIN
      SET @sql = @sql + '''' + @Customer_Name + '''' + ' AS [CustomerName], '	  
	END
	ELSE
	BEGIN		
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
		SET @sql = @sql + ' THEN '
		SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
		SET @sql = @sql + ' 	THEN '
		SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
		SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(c.Surname)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
		SET @sql = @sql + ' 		END '
		SET @sql = @sql + ' 	ELSE '
		SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
		SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
		SET @sql = @sql + ' 		END '
		SET @sql = @sql + ' 	END '
		SET @sql = @sql + ' ELSE '
		SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
		SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
		SET @sql = @sql + ' 	END '
		SET @sql = @sql + ' END AS [CustomerName], '
	END
	           	
    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
    --> POSTAL Address
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [PostBox], '
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [PostBox], '      
		SET @sql = @sql + '''' + @Inv_Address2 + '''' + ' AS [PostOffice], '
		SET @sql = @sql + '''' + @Inv_City + '''' + ' AS [PostCity], '
		SET @sql = @sql + '''' + @Inv_Code + '''' + ' AS [PostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [PostBox], '
		SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [PostBox], '
		SET @sql = @sql + ' ISNULL(c.Post_Office, '''') AS [PostOffice], '
		SET @sql = @sql + ' ISNULL(c.City, '''') AS [PostCity], '
		SET @sql = @sql + ' ISNULL(c.Post_Code, '''') AS [PostCode], '
	END

	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [StreetAddress], '      
		SET @sql = @sql + '''' + @Inv_Address2 + '''' + ' AS [StreetSuburb], '
		SET @sql = @sql + '''' + @Inv_City + '''' + ' AS [StreetCity], '
		SET @sql = @sql + '''' + @Inv_Code + '''' + ' AS [StreetPostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Street_Address, '''') AS [StreetAddress], '
		SET @sql = @sql + ' ISNULL(c.Suburb, '''') AS [StreetSuburb], '
		SET @sql = @sql + ' ISNULL(c.City, '''') AS [StreetCity], '
		SET @sql = @sql + ' ISNULL(c.Street_Post_Code, '''') AS [StreetPostCode], '
	END

	IF @AW_YesNo_Delivery_Address = 1
	BEGIN
		SET @sql = @sql + '''' + @Delivery_Address + '''' + ' AS [DeliverAddress], '      
		SET @sql = @sql + '''' + @Delivery_Suburb + '''' + ' AS [DeliverSuburb], '
		SET @sql = @sql + '''' + @Delivery_City + '''' + ' AS [DeliverCity], '
		SET @sql = @sql + '''' + @Delivery_Post_Code + '''' + ' AS [DeliverPostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Delivery_Address, '''') AS [DeliverAddress], '
		SET @sql = @sql + ' ISNULL(c.Delivery_Suburb, '''') AS [DeliverSuburb], '
		SET @sql = @sql + ' ISNULL(c.Delivery_City, '''') AS [DeliverCity], '
		SET @sql = @sql + ' ISNULL(c.Delivery_Post_Code, '''') AS [DeliverPostCode], '
	END

	SET @sql = @sql + ' CONVERT(VARCHAR(12), c.AC_Customers_ID) AS [CustomerID], '
	SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') + ''('' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + '')'' AS [CustomerNo], '

    SET @sql = @sql + ' CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> '''' '
    SET @sql = @sql + ' THEN ''Merchant No: '' + RTRIM(LTRIM(c.Old_Customer_Number)) '
    SET @sql = @sql + ' ELSE '''' '
    SET @sql = @sql + ' END AS [MerchantNo], '

    SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' tt.[Description] AS [TransactionType], '
    SET @sql = @sql + ' comp.Tax_Number AS [CompanyTaxNumber], '
    SET @sql = @sql + ' comp.E_Mail AS [CompanyEmail], '
    SET @sql = @sql + ' comp.Company_Name AS [CompanyName], '
--    SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
--    SET @sql = @sql + ' THEN comp.Company_Name + '' / '' + IsNull(comp.Company_Trading_Name,'''')'
--    SET @sql = @sql + ' ELSE comp.Company_Name '
--    SET @sql = @sql + ' END AS [CompanyName], '
    
    SET @sql = @sql + ' comp.Company_Trading_Name AS [TradingName], '
    SET @sql = @sql + ' comp.Company_Addr1 AS [CompanyAddress1], '
    SET @sql = @sql + ' comp.Company_Addr2 AS [CompanyAddress2], '
    SET @sql = @sql + ' comp.Company_City AS [CompanyCity], '
    SET @sql = @sql + ' comp.Company_Post_Code AS [CompanyPostCode], '
    SET @sql = @sql + ' comp.Company_Registration_Number AS [CompanyRegNo], '
    SET @sql = @sql + ' comp.Tel_No AS [CompanyTelNo], '
    SET @sql = @sql + ' comp.Fax_No AS [CompanyFaxNo], '
    SET @sql = @sql + ' comp.Delivery_Addr1 AS [Delivery_Addr1], '
    SET @sql = @sql + ' comp.Delivery_Addr2 AS [Delivery_Addr2], '
    SET @sql = @sql + ' comp.Delivery_Addr3 AS [Delivery_Addr3], '            
    SET @sql = @sql + ' rep.[Description] AS [RepName], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TransactionID], '
	SET @sql = @sql + ' t.Transaction_Number + ISNULL(tranNumbers.Number_Suffix, '''') AS [TransactionNo], '
	--SET @sql = @sql + ' t.Transaction_Number + tranNumbers.Number_Suffix AS [TransactionNo], '
    SET @sql = @sql + ' CONVERT(varchar(12), t.Transaction_Date, 103) AS [TransactionDate], '
    SET @sql = @sql + ' t.Customer_Reference AS [TransactionCustomerRef], '
    SET @sql = @sql + ' t.Amount AS [TransactionAmount], '
    SET @sql = @sql + ' t.Total_Amount AS [TransactionTotalAmount], '
    SET @sql = @sql + ' t.Total_Discount_Amount AS [TransactionTotalDiscount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [TransactionTotalTax], '
    SET @sql = @sql + ' com.Comment AS [TransactionComment], '
-------------------------------------------------------------------------------
    SET @sql = @sql + ' p.Product_Code AS [ProductCode], '

--    SET @sql = @sql + ' p.Description AS [ProductDescription], '
    --RL 2014-01-28 Vs 6.0 Use print discription if there is a value instead of Description
    SET @sql = @sql + ' CASE WHEN LEN(ISNULL(Print_Description,'''')) > 0 '
    SET @sql = @sql + ' THEN p.Print_Description '
    SET @sql = @sql + ' ELSE p.Description '
    SET @sql = @sql + ' END AS [ProductDescription], '
    
    --V6.3 RL 2017/04/21 Added back order qty to display on Sales Order document
    SET @sql = @sql + ' (td.Quantity + td.Back_Order) AS [DetailQty], '    
    
    SET @sql = @sql + ' td.Unit_Price AS [DetailUnitPrice], '

    SET @sql = @sql + ' CASE WHEN (td.Unit_Price * (td.Quantity + td.Back_Order)) <> 0 '
    SET @sql = @sql + ' THEN CONVERT(money,ABS(ROUND((((td.Discount_Amount) / (td.Unit_Price * (td.Quantity + td.Back_Order))) * 100), 2))) '
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END AS [DetailDiscPerc], '

    SET @sql = @sql + ' td.Discount_Amount AS [DetailDiscount] , '
    SET @sql = @sql + ' (td.Unit_Price * (td.Quantity + td.Back_Order)) + td.Discount_Amount AS [DetailAmount], '
    SET @sql = @sql + ' td.Tax_Amount AS [DetailTaxAmount], '
    SET @sql = @sql + ' td.Extended_Amount AS [DetailExtendedAmount], '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime], '
    SET @sql = @sql + ' u.UserName AS [UserCode], '
    SET @sql = @sql + ' t.Comment AS [Comment], '

  	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Cell_No + '''' + ' AS [TelNos], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '''') + '
		SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Cell_No)), '''') + '
		SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Home_Tel_No)), '''') AS [TelNos], '
	END
	--> TAX Number
    --SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Tax_Number + '''' + ' AS [VATNo], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	END

    SET @sql = @sql + ' CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> '''' '
    SET @sql = @sql + ' THEN ''Sales Order/Job No: '' + RTRIM(LTRIM(ts.Transaction_Numbers)) '
    SET @sql = @sql + ' ELSE '''' '
    SET @sql = @sql + ' END AS [JobSource], '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass], '
    SET @sql = @sql + ' @PaymentMethod AS [PayMethod], '

    SET @sql = @sql + ' CASE WHEN td.AS_Job_References_ID = 0 '
    SET @sql = @sql + ' THEN NULL '
    SET @sql = @sql + ' ELSE td.AS_Job_References_ID '
    SET @sql = @sql + ' END AS [JobRefNo], '

    SET @sql = @sql +  '''' + @Message + '''' + ' AS [TextMessage], '
    SET @sql = @sql + ' @WhichAddress AS [AddressType], '
    SET @sql = @sql + ' td.Serial_No AS [SerialNo], '
    SET @sql = @sql + ' td.Make AS [Make], '
    SET @sql = @sql + ' td.Customer AS [Customer], '
    SET @sql = @sql + ' @WhichName AS [NameType], '
    
  	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @EMail + '''' + ' AS [Emails], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Orders_URL)), '''') + '
		SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') + '
		SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') AS [Emails], '
	END
	    
    SET @sql = @sql + ' td.TDHeader AS [TDHeader], '
    SET @sql = @sql + ' td.TDDetail AS [TDDetail], '
	SET @sql = @sql + ' ISNULL(ca.Reg_No, '''') AS [Reg_No], '
	SET @sql = @sql + ' ISNULL(ca.Mileage, '''') AS [Mileage], '	
	--V6.4
	SET @sql = @sql + '''' + @IPay_Link + '''' + ' AS [IPay_Link] '

--	FROM vw_AS_Transactions t 
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + ' LEFT JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + ' ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_User_Companies comp '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + ' ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Details td '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = td.AS_Transactions_ID '
    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + ' ON td.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + ' ON t.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Sources ts '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = ts.AS_Transactions_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Comments com '
    SET @sql = @sql + ' ON t.AW_Comments_ID = com.AW_Comments_ID '
    SET @sql = @sql + ' LEFT JOIN AC_Assets ca '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = ca.AS_Transactions_ID '
	SET @sql = @sql + ' LEFT JOIN Sys_AW_Transaction_Numbers tranNumbers '

    SET @sql = @sql + ' ON t.Sys_AW_Transaction_Types_ID = tranNumbers.Sys_AW_Transaction_Types_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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Payment_Print
--Purpose       :POS Receipt printing
--Parameters    :
--Date          :2002/04/20
--Authors       :TB
--Version       :1
--MODS:         :12/04/02 - Added Time extracted from Transaction_Date
--              :18/04/02 - Added AW_Users.UserName
--              :21/04/02 - Added (AC_Customers_ID) to Customer_Number
--              :22/04/02 - Changed Customer Addresses to Postal
--              :10/06/02 - Added Company Tel_No & Company Fax_No fields
--              :30/12/02 - Added t.SmallComment AS [Comment] for POS Asset No
--              :29/01/04 - Added [TranTypeID] to print a PICKLIST with a JOBCARD
--2004.2.4      :07/06/04 - Added t.AW_User_Companies_ID to locate Company Logo
--              :           path parameter in SpSPOSPrint.CCutSheetLogoA4
--              :28/08/05 - Added t.Amount AS TransactionAmount for OPOS printing
--              :28/10/05 - Added Street and Delivery Adresses
--              :28/10/05 - Added System Option address choice using @WhichAddress
--2004.2.7      :13/04/06 - Replaced SELECT vw_AS_Transactions with AS_Transactions
--2004.3.3      :23/11/06 - Added [NameType] for Company Trading Name
--2004.3.4      :23/11/06 - Added Old_Customer_Number as [MerchantNo] for Card Companies
--RL	V6.0	:2014-04-22 - Return Customer ID
--RL	V6.3	:2017-11-07 - Reworked Reg_No
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Payment_Print]
    (
    	@TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @WhichAddress tinyint,
            @WhichName tinyint,
            @AddressOption0 varchar(20),
            @AddressOption1 varchar(20)


    SET @WhichAddress = 0


    SELECT TOP 1 @AddressOption0 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 0

    SELECT TOP 1 @AddressOption1 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 1

    IF @AddressOption0 = 'True'
        BEGIN
            SET @WhichAddress = 0        --Print POSTAL Address
        END
    ELSE
    IF @AddressOption1 = 'True'
        BEGIN
            SET @WhichAddress = 1        --Print STREET Addres
        END


    SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSPrintTradeName'


	SELECT 
		RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') as CustomerName,

    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
		ISNULL(c.Post_Box, '') AS [PostBox],
		ISNULL(c.Post_Office, '') AS [PostOffice],
		ISNULL(c.City, '') AS [PostCity],
		ISNULL(c.Post_Code, '') AS [PostCode],

		ISNULL(c.Street_Address, '') AS [StreetAddress],
		ISNULL(c.Suburb, '') AS [StreetSuburb],
		ISNULL(c.City, '') AS [StreetCity],
		ISNULL(c.Street_Post_Code, '') AS [StreetPostCode],

		ISNULL(c.Delivery_Address, '') AS [DeliverAddress],
		ISNULL(c.Delivery_Suburb, '') AS [DeliverSuburb],
		ISNULL(c.Delivery_City, '') AS [DeliverCity],
		ISNULL(c.Delivery_Post_Code, '') AS [DeliverPostCode],

		CONVERT(VARCHAR(12), c.AC_Customers_ID) AS [CustomerID], 
		ISNULL(c.Customer_Number, '') + '(' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + ')' as [CustomerNo],

        CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> ''
             THEN 'Merchant No: ' + RTRIM(LTRIM(c.Old_Customer_Number))
             ELSE ''
             END AS [MerchantNo],

        t.Sys_AW_Transaction_Types_ID AS [TranTypeID],
		tt.[Description] as TransactionType,
		comp.Tax_Number as CompanyTaxNumber,
		comp.Company_Name as CompanyName,
		comp.Company_Trading_Name AS TradingName,
		comp.Company_Addr1 as CompanyAddress1,
		comp.Company_Addr2 as CompanyAddress2,
		comp.Company_City as CompanyCity,
		comp.Company_Post_Code as CompanyPostCode,
        comp.Company_Registration_Number as CompanyRegNo,
        comp.Tel_No as CompanyTelNo,
        comp.Fax_No as CompanyFaxNo,
		rep.[Description] as RepName,
		t.AS_Transactions_ID as TransactionID,
		t.Transaction_Number as TransactionNo,
		CONVERT(varchar(12), t.Transaction_Date, 103) as TransactionDate,
		t.Customer_Reference as TransactionCustomerRef,
        t.Amount AS TransactionAmount,
		t.Total_Amount as TransactionTotalAmount,
		t.Total_Discount_Amount as TransactionTotalDiscount,
		t.Total_Tax_Amount as TransactionTotalTax,
		com.Comment AS TransactionComment,
-------------------------------------------------------------------------------
		pm.Description as PaymentMethod,
		tp.Payor_Name as PaymentPayorName,
		tp.Card_Expiry_Date as PaymentCardExpiry,
		tp.Card_Number as PaymentCardNo,
		tp.Authorisation_Number as PaymentAuthorisationNo,
		tp.Amount as PaymentAmount,
        CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS TransactionTime,
        u.UserName as [UserCode],
--        t.SmallComment AS [Comment],
        t.Comment AS [Comment],
        t.AW_User_Companies_ID AS [CompanyID],
        @WhichAddress AS [AddressType],
        @WhichName AS [NameType],
	    ISNULL(ca.Reg_No, '') AS [Reg_No]

--	FROM vw_AS_Transactions t 
	FROM AS_Transactions t 
		LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID
		LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
		LEFT JOIN AW_User_Companies comp
            ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID
		LEFT JOIN Lup_AS_Reps rep
            ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID
		LEFT JOIN AS_Transaction_Payments tp
            ON	t.AS_Transactions_ID = tp.AS_Transactions_ID
		LEFT JOIN Sys_AW_Payment_Methods pm
            ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN AW_Comments com
            ON t.AW_Comments_ID = com.AW_Comments_ID
        LEFT JOIN AC_Assets ca
            ON t.AS_Transactions_ID = ca.AS_Transactions_ID   
	WHERE t.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Sales_Order_Print
--Purpose       :POS Sales Order printing
--Parameters    :
--Date          :2008/06/12
--Authors       :TB
--MODS:         :
--V6.3	RL	2017/04/21	:Added Back Order Qty
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Sales_Order_Print]
    (
    	@TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @TextMessage varchar(100),
            @TextMessagePrint varchar(100),
            @Message varchar(100),
            @WhichAddress tinyint,
            @WhichName tinyint,
            @PaymentMethod varchar(20),
            @AddressOption0 varchar(20),
            @AddressOption1 varchar(20)


    SET @WhichAddress = 0
    SET @Message = ''


    SELECT TOP 1 @TextMessage = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'



    SELECT TOP 1 @AddressOption0 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 0

    SELECT TOP 1 @AddressOption1 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 1

    IF @AddressOption0 = 'True'
        BEGIN
            SET @WhichAddress = 0        --Print POSTAL Address
        END
    ELSE
    IF @AddressOption1 = 'True'
        BEGIN
            SET @WhichAddress = 1        --Print STREET Addres
        END


    SELECT TOP 1 @TextMessagePrint = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    IF @TextMessagePrint = '1'
        BEGIN
            SET @Message = @TextMessage
        END


    SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSPrintTradeName'


    SELECT TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''), 20)
	FROM AS_Transactions_Transactions att
        LEFT JOIN AS_Transaction_Payments tp
            ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID
        LEFT JOIN Sys_AW_Payment_Methods pm
            ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID
	WHERE att.Source_AS_Transactions_ID = @TransactionID
    ORDER BY att.Source_AS_Transactions_ID


	SELECT 
		RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') AS [CustomerName],
        ISNULL(c.Firstnames, '') AS [TradeName],
        ISNULL(c.Contact_Name, '') AS [Contact],

    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
		ISNULL(c.Post_Box, '') AS [PostBox],
		ISNULL(c.Post_Office, '') AS [PostOffice],
		ISNULL(c.City, '') AS [PostCity],
		ISNULL(c.Post_Code, '') AS [PostCode],

		ISNULL(c.Street_Address, '') AS [StreetAddress],
		ISNULL(c.Suburb, '') AS [StreetSuburb],
		ISNULL(c.City, '') AS [StreetCity],
		ISNULL(c.Street_Post_Code, '') AS [StreetPostCode],

		ISNULL(c.Delivery_Address, '') AS [DeliverAddress],
		ISNULL(c.Delivery_Suburb, '') AS [DeliverSuburb],
		ISNULL(c.Delivery_City, '') AS [DeliverCity],
		ISNULL(c.Delivery_Post_Code, '') AS [DeliverPostCode],

		ISNULL(c.Customer_Number, '') + '(' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + ')' AS [CustomerNo],

        CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> ''
             THEN 'Merchant No: ' + RTRIM(LTRIM(c.Old_Customer_Number))
             ELSE ''
             END AS [MerchantNo],

        t.Sys_AW_Transaction_Types_ID AS [TranTypeID],
		tt.[Description] AS [TransactionType],
		comp.Tax_Number AS [CompanyTaxNumber],
		comp.Company_Name AS [CompanyName],
		comp.Company_Trading_Name AS [TradingName],
		comp.Company_Addr1 AS [CompanyAddress1],
		comp.Company_Addr2 AS [CompanyAddress2],
		comp.Company_City AS [CompanyCity],
		comp.Company_Post_Code AS [CompanyPostCode],
        comp.Company_Registration_Number AS [CompanyRegNo],
        comp.Tel_No AS [CompanyTelNo],
        comp.Fax_No AS [CompanyFaxNo],
		rep.[Description] AS [RepName],
		t.AS_Transactions_ID AS [TransactionID],
		t.Transaction_Number AS [TransactionNo],
		CONVERT(varchar(12), t.Transaction_Date, 103) AS [TransactionDate],
		t.Customer_Reference AS [TransactionCustomerRef],
        t.Amount AS [TransactionAmount],
		t.Total_Amount AS [TransactionTotalAmount],
		t.Total_Discount_Amount AS [TransactionTotalDiscount],
		t.Total_Tax_Amount AS [TransactionTotalTax],
		com.Comment AS [TransactionComment],
-------------------------------------------------------------------------------
		p.Product_Code AS [ProductCode],
		p.Description AS [ProductDescription],
		(td.Quantity + td.Back_Order) AS [DetailQty],
		td.Unit_Price AS [DetailUnitPrice],

        CASE WHEN (td.Unit_Price * (td.Quantity + td.Back_Order)) <> 0
             THEN CONVERT(money,ABS(ROUND((((td.Discount_Amount) / (td.Unit_Price * (td.Quantity + td.Back_Order))) * 100), 2)))
             ELSE 0.00
             END AS [DetailDiscPerc],

		td.Discount_Amount AS [DetailDiscount],
       (td.Unit_Price * (td.Quantity + td.Back_Order)) + td.Discount_Amount AS [DetailAmount],
		td.Tax_Amount AS [DetailTaxAmount],
		td.Extended_Amount AS [DetailExtendedAmount],
        CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime],
        u.UserName AS [UserCode],
        t.Comment AS [Comment],

        ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Cell_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Home_Tel_No)), '') AS [TelNos],
        ISNULL('Fax No ' + RTRIM(LTRIM(c.Fax_No)), '') AS [FaxNo],

        ISNULL(RTRIM(LTRIM(c.Tax_Number)), '') AS [VATNo],

        CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> ''
             THEN 'Jobcard No: ' + RTRIM(LTRIM(ts.Transaction_Numbers))
             ELSE ''
             END AS [JobSource],

        t.AW_User_Companies_ID AS [CompanyID],
        ROUND(ISNULL((td.Quantity + td.Back_Order), 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass],
        ROUND(ISNULL((td.Quantity + td.Back_Order), 0) * ISNULL(p.Pack_Volume, 0), 2) AS [PackVolume],
        @PaymentMethod AS [PayMethod],

        CASE WHEN td.AS_Job_References_ID = 0 
             THEN NULL
             ELSE td.AS_Job_References_ID
             END AS [JobRefNo],

        @Message AS [TextMessage],
        @WhichAddress AS [AddressType],
        td.Serial_No AS [SerialNo],
        td.Make AS [Make],
        td.Customer AS [Customer],
        @WhichName AS [NameType]

	FROM AS_Transactions t 
        LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AW_User_Companies comp
            ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID
        LEFT JOIN Lup_AS_Reps rep
            ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID
        LEFT JOIN AS_Transaction_Details td
            ON t.AS_Transactions_ID = td.AS_Transactions_ID
        LEFT JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN AS_Transaction_Sources ts
            ON t.AS_Transactions_ID = ts.AS_Transactions_ID
        LEFT JOIN AW_Comments com
            ON t.AW_Comments_ID = com.AW_Comments_ID
	WHERE t.AS_Transactions_ID = @TransactionID
    ORDER BY AS_Transaction_Details_ID



SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








CREATE     PROCEDURE sp_AS_POS_Report_Transaction_Select
   @TransactionID int
AS

SELECT 
   t.TransactionID, 
   t.TransactionNumber, 
   t.TransactionVersion, 
   t.TransactionComments, 
   t.TransactionType, 
   t.TransactionVersionNumber, 
   t.TransactionDate, 
   t.CustomerName, 
   t.CustomerPostBox, 
   t.CustomerPostOffice, 
   t.CustomerPostCode, 
   t.CustomerStreetAddress, 
   t.CustomerSuburb, 
   t.CustomerCity, 
   t.CustomerStreetPostCode, 
   t.CustomerDeliveryAddress, 
   t.CustomerDeliverySuburb, 
   t.CustomerDeliveryCity, 
   t.CustomerDeliveryPostCode, 
   t.CustomerReference, 
   t.CustomerNumber, 
   t.CompanyName, 
   t.CompanyAddess1, 
   t.CompanyAddress2, 
   t.CompanyCity, 
   t.CompanyPostCode, 
   t.CompanyRegNo, 
  -- t.CompanyVATNumber, 
   t.CompanyTAXNumber, 
   t.RepName, 
   t.RepID, 
   td.DetailTransactionDetailID, 
   td.DetailProductPrintDescription, 
   td.DetailProductDescription, 
   td.DetailProductCode, 
   td.DetailQty, 
   td.DetailOriginalPrice, 
   td.DetailDiscountAmount, 
   td.DetailAmount, td.DetailTax
FROM vw_POS_Print_Select_Transactions t 
   LEFT OUTER JOIN vw_POS_Print_Select_Transaction_Details td 
   ON t.TransactionID = td.DetailTransactionID
WHERE  t.TransactionID = @TransactionID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_Companies_Per_User
--Purpose       :Select POS Login User
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS:         :02/10/02 - Removed Lup_AS_Cashiers and the CONDITION in the WHERE
--              :           clause if User is a member of the (4 = )'Cashier' Role
--              :04/10/02 - Inserted validate IsCashier field in AW_Users to
--              :           establish Users as members of Cashiers
--              :01/05/06 - Removed JOIN with AW_Users_Per_Role
-------------------------------------------------------------------------------


CREATE       Procedure sp_AS_POS_Select_Companies_Per_User
    (
        @UserName varchar(50) = ''
    )

AS

SET NOCOUNT ON


    SELECT DISTINCT
            uc.AW_User_Companies_ID AS [ID], 
            uc.Company_Name AS [CompanyName]
    FROM AW_Users u 
        INNER JOIN AW_Company_Users cu
            ON u.AW_Users_ID = cu.AW_Users_ID 
        INNER JOIN AW_User_Companies uc
            ON cu.AW_User_Companies_ID = uc.AW_User_Companies_ID
--         INNER JOIN AW_Users_Per_Role upr
--             ON u.AW_Users_ID = upr.AW_Users_ID
    WHERE u.UserName = @UserName AND
--          upr.AW_Roles_ID = 4
          u.IsCashier = 1


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_Contract_Prices
--Purpose       :Fetch product prices ON CONTRACT
--Date          :2004/03/13
--Authors       :TB
--Version       :1.0.0
--MODS          :03/06/04 - Added validation If Contract Product ACTIVE
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_Select_Contract_Prices]
    (
        @CustomerID int,
        @ProductID int,
        @Qty decimal(9,3),
        @UnitPrice money OUTPUT,
        @DiscPerc decimal(9, 3) OUTPUT,
        @DiscAmount money OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE @Today datetime

    SET @Today = CONVERT(datetime, CONVERT(CHAR(10), getdate(), 121))

    SELECT TOP 1 @UnitPrice = ISNULL(Unit_Price, 0),
                 @DiscPerc = ISNULL(Discount_Perc, 0),
                 @DiscAmount = ISNULL(Discount_Amount, 0)
    FROM AC_Contract_Prices
    WHERE AC_Customers_ID = @CustomerID AND
          AP_Products_ID = @ProductID AND
         (@Today >= Start_Date AND            -- If PRODUCT still ACTIVE
          @Today <= End_Date) AND
          Slu_AW_Active_ID = 1 AND            -- If Contract Product ACTIVE
          MinSaleQty <= @Qty
    Order BY MinSaleQty DESC    

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_CostPlus_Prices
--Purpose       :Fetch Cost+Plus product price
--Date          :2007/07/26
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------
CREATE             PROCEDURE sp_AS_POS_Select_CostPlus_Prices
    (
        @CostPlusCatID smallint,
        @CostPlusGroupID smallint,
        @ProductCost money,
        @UnitPrice money OUTPUT
    )

AS

SET NOCOUNT ON

    SET @ProductCost = ISNULL(@ProductCost, 0)

    SELECT @UnitPrice = ROUND(@ProductCost + (ROUND((@ProductCost * (ISNULL(Markup_Percentage, 0) / 100)), 2)), 2)
    FROM AS_Markup_Categories_Groups
    WHERE Lup_AC_Markup_Categories_ID = @CostPlusCatID AND
          Lup_AP_Markup_Groups_ID = @CostPlusGroupID AND
          Slu_AW_Active_ID = 1



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_IsSupervisor
--Purpose       :Select if POS User is a Supervisor
--Date          :2006/07/30
--Authors       :TB
--MODS:         :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE           Procedure sp_AS_POS_Select_IsSupervisor
    (
        @UserID int,
        @IsSupervisor tinyint OUTPUT
    )

AS

SET NOCOUNT ON


    SET @IsSupervisor = 0

    SELECT @IsSupervisor = IsSupervisor
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @IsSupervisor IS NULL 
        BEGIN	
    		SET @IsSupervisor = 0 
        END


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_IsTillPayout
--Purpose       :Select if POS User is a Till Payout User
--Date          :2017/09/11
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_POS_Select_IsTillPayout]
    (
        @UserID int,
        @IsTillPayout tinyint OUTPUT
    )

AS

SET NOCOUNT ON

    SET @IsTillPayout = 0

    SELECT @IsTillPayout = IsTillPayout
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @IsTillPayout IS NULL 
        BEGIN	
    		SET @IsTillPayout = 0 
        END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_Promotion_Price_Terms
--Purpose       :Fetch product ON PROMOTION
--Date          :2004/02/25
--Functionality :
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------
CREATE           PROCEDURE sp_AS_POS_Select_Promotion_Price_Terms
    (    
        @ProductID int,
        @TermsID tinyint,
        @PromoPrice money OUTPUT
    )

AS

SET NOCOUNT ON


    DECLARE @FoundProductID int,
            @Today datetime

    SET @Today = CONVERT(datetime, CONVERT(CHAR(10), getdate(), 121))

    SELECT TOP 1 @FoundProductID = a.AP_Products_ID,
                 @PromoPrice = ISNULL(a.Selling_Price, 0)
    FROM AP_Promotion_Products a
        LEFT JOIN AP_Promotions b
            ON a.AP_Promotions_ID = b.AP_Promotions_ID
    WHERE a.AP_Products_ID = @ProductID AND
          @TermsID <= a.Slu_AW_Credit_Terms_ID AND   -- Customer qualifies
         (@Today >= a.Start_Date AND                 -- If PRODUCT still ACTIVE
          @Today <= a.End_Date) AND                  -- AND
         (@Today >= b.Start_Date AND                 -- If PROMOTION still ACTIVE
          @Today <= b.End_Date) AND                  -- AND
          a.Qty_Sold < a.Qty_Cutoff                  -- not SOLD OUT



SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_Tills_Per_User
--Purpose       :Select POS Login User Till
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--MODS:         :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------


CREATE              Procedure sp_AS_POS_Select_Tills_Per_User
    (
        @UserName varchar(50) = '',
        @CompanyID int = 0
    )

AS

SET NOCOUNT ON

    SELECT t.Lup_AS_Tills_ID AS [ID], 
           t.[Description], 
           u.UserName, 
           t.AW_User_Companies_ID
    FROM AW_Users u 
        INNER JOIN AW_Users_Tills ut
            ON u.AW_Users_ID = ut.AW_Users_ID 
        INNER JOIN Lup_AS_Tills t
            ON ut.Lup_AS_Tills_ID = t.Lup_AS_Tills_ID 
        INNER JOIN AW_Company_Users cu
            ON u.AW_Users_ID = cu.AW_Users_ID 
        INNER JOIN AW_User_Companies uc
            ON cu.AW_User_Companies_ID = uc.AW_User_Companies_ID
    WHERE u.UserName = @UserName AND 
          t.AW_User_Companies_ID = @CompanyID AND 
          uc.AW_User_Companies_ID = @CompanyID AND
          u.Slu_AW_Active_ID = 1


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_User_ID
--Purpose       :Select POS Login User From ID
--Date          :2006/04/30
--Authors       :TB
--MODS:         :
--2004.4.8      :Added check validation on ACTIVE users only
--V6.4		RL	:2018-02-14 - Return User Email
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_POS_Select_User_ID]
    (
        @UserID int
    )
AS

SET NOCOUNT ON

    SELECT UserName,
          [Password],
           Surname + ISNULL(', ' + Firstname, '') AS [Fullname],
           ISNULL(User_Email,'') AS [User Email]
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_Users
--Purpose       :Select POS Login Users
--Date          :2006/04/30
--Authors       :TB
--MODS:         :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE         Procedure sp_AS_POS_Select_Users
    (
        @UserID int
    )

AS


SET NOCOUNT ON

    SELECT
        UserName,
        [Password],
        Surname + ISNULL(', ' + Firstname, '') AS [Fullname]
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AS_POS_TillPayout_Insert
--Purpose       :Post POS Till Expense GL Journal and Supplier Payout Journals
--Parameters    :
--Date          :2009/08/07
--Authors       :TB
--Mods          :
--2004.4.8      :30/01/10 - Added Expense Payout - (Tax Invoice)
--              :02/06/10 - Fixed Option 1 AND 2 when 'Reverse signs to balance double entry'
--                          to reverse the '@Total' NOT '@Amount' parameter !!!!!!!!
--              :18/07/10 - Changed format of @Narration in Supplier Payout section
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AS_POS_TillPayout_Insert
	(
        @optPayType tinyint,
        @CashControlID int,
        @CreditorsControlID int,
        @VATControlID int,
        @MonthID int,
        @YearID int,
        @Total money,
        @Amount money,
        @Tax money,
        @Description varchar(36),
        @SupplierID int,
        @GLAccountID int,
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @TranDate DateTime,
            @RefNo varchar(20),
            @NextGLTranNo varchar(20),
            @NextAOTranNo varchar(20),
            @JNLHeaderID int,
            @Narration varchar(50),
            @Comment varchar(20),
            @NewSupplierJournalID int,
            @SupplierName varchar(30),
            @InsertGLTran bit,
            @RetCode int


    SET @NextGLTranNo = ''
    SET @NextAOTranNo = ''
    SET @JNLHeaderID = 0
    SET @TranDate = getdate()
    SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
    SET @RetCode = 0


    -------------------------------------------------------------------------------
    --> Expense Payout - (Tax Invoice) - UPDATE GL TRANSACTIONS
    -------------------------------------------------------------------------------
    IF @optPayType = 0
        BEGIN
            SET @Narration = LEFT('Till Payout - ' + @Description, 50)

            --> Create NORMAL JOURNAL header
            EXEC @NextGLTranNo = sp_AB_Next_Transaction_Number 15, @CompanyID


            --> INSERT Till Payout
        	INSERT AS_Till_Payouts 
        		(
                    Payout_Type_ID,
                    AB_Account_DR_ID,
                    AB_Account_CR_ID,
                    AO_Suppliers_ID,
                    Sys_AB_Transaction_Types_ID,
                    Description,
                    Narration,
                    Payout_Number,
                    Payout_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    Amount,
                    Date_Captured,
                    AW_User_Companies_ID,
                    User_ID
        		)
        	VALUES
        		(
                    @optPayType,
                    @GLAccountID,
                    @CashControlID,
                    @SupplierID,
                    15,
                    @Description,
                    @Narration,
        			@NextGLTranNo,
        			@TranDate,
                    @MonthID,
                    @YearID,
        			@Total,
                    @TranDate,
        			@CompanyID,
        			@UserID
        		)

            SET @RetCode = Scope_Identity()


            EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @TranDate,
                                    @NextGLTranNo,
                                    @Narration,
                                    @MonthID,
                                    @YearID,
                                    @UserID,
                                    @CompanyID


            --> Create JOURNAL DETAIL for Expense Account
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @GLAccountID,
                    @Amount,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> Create JOURNAL DETAIL for V.A.T. Account
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @VATControlID,
                    @Tax,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> Create GL TRANSACTION for Expense Account
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @GLAccountID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @Amount,
                    @UserID,
                    @CompanyID

            --> Create GL TRANSACTION for V.A.T. Account
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @VATControlID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @Tax,
                    @UserID,
                    @CompanyID

            --> Reverse signs to balance double entry
            SET @Total = @Total * -1

            --> Create JOURNAL DETAIL for CASH CONTROL
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @CashControlID,
                    @Total,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> Create GL TRANSACTION for CASH CONTROL
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @CashControlID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @Total,
                    @UserID,
                    @CompanyID
        END


    -------------------------------------------------------------------------------
    --> Expense Payout - (No Tax) - UPDATE GL TRANSACTIONS
    -------------------------------------------------------------------------------
    IF @optPayType = 1
        BEGIN
            SET @Narration = LEFT('Till Payout - ' + @Description, 50)

            --> Create NORMAL JOURNAL header
            EXEC @NextGLTranNo = sp_AB_Next_Transaction_Number 15, @CompanyID


            --> INSERT Till Payout
        	INSERT AS_Till_Payouts 
        		(
                    Payout_Type_ID,
                    AB_Account_DR_ID,
                    AB_Account_CR_ID,
                    AO_Suppliers_ID,
                    Sys_AB_Transaction_Types_ID,
                    Description,
                    Narration,
                    Payout_Number,
                    Payout_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    Amount,
                    Date_Captured,
                    AW_User_Companies_ID,
                    User_ID
        		)
        	VALUES
        		(
                    @optPayType,
                    @GLAccountID,
                    @CashControlID,
                    @SupplierID,
                    15,
                    @Description,
                    @Narration,
        			@NextGLTranNo,
        			@TranDate,
                    @MonthID,
                    @YearID,
        			@Total,
                    @TranDate,
        			@CompanyID,
        			@UserID
        		)

            SET @RetCode = Scope_Identity()


            EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @TranDate,
                                    @NextGLTranNo,
                                    @Narration,
                                    @MonthID,
                                    @YearID,
                                    @UserID,
                                    @CompanyID


            --> Create JOURNAL DETAIL for Expense Account
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @GLAccountID,
                    @Total,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> Create GL TRANSACTION for Expense Account
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @GLAccountID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @Total,
                    @UserID,
                    @CompanyID

            --> Reverse signs to balance double entry
            SET @Total = @Total * -1

            --> Create JOURNAL DETAIL for CASH CONTROL
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @CashControlID,
                    @Total,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> Create GL TRANSACTION for CASH CONTROL
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @CashControlID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NextGLTranNo,
                    @Total,
                    @UserID,
                    @CompanyID
        END

    -------------------------------------------------------------------------------
    --> Supplier Payout - (No Tax) - UPDATE SUPPLIER TRANSACTIONS
    -------------------------------------------------------------------------------
    IF @optPayType = 2
        BEGIN
            --> Create SUPPLIER Transaction No
            EXEC @NextAOTranNo = sp_AW_Next_Transaction_Number 10, @CompanyID


            SELECT @SupplierName = LEFT(ISNULL(Supplier_Name, ''), 25)
            FROM AO_Suppliers
            WHERE AO_Suppliers_ID = @SupplierID


--            SET @Narration = LEFT(RTRIM(LTRIM(@SupplierName)), 25) + ' - ' + LEFT(@Description, 20)
            SET @Comment = 'Till Payout'
            SET @Narration = @Comment + ' - ' +  LEFT(RTRIM(LTRIM(@SupplierName)), 34)


            --> Create NORMAL JOURNAL header
            EXEC @NextGLTranNo = sp_AB_Next_Transaction_Number 15, @CompanyID


            --> INSERT Till Payout
        	INSERT AS_Till_Payouts 
        		(
                    Payout_Type_ID,
                    AB_Account_DR_ID,
                    AB_Account_CR_ID,
                    AO_Suppliers_ID,
                    Sys_AB_Transaction_Types_ID,
                    Description,
                    Narration,
                    Payout_Number,
                    Payout_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    Amount,
                    Date_Captured,
                    AW_User_Companies_ID,
                    User_ID
        		)
        	VALUES
        		(
                    @optPayType,
                    @CreditorsControlID,
                    @CashControlID,
                    @SupplierID,
                    15,
                    @Description,
                    @Narration,
        			@NextGLTranNo,
        			@TranDate,
                    @MonthID,
                    @YearID,
        			@Total,
                    @TranDate,
        			@CompanyID,
        			@UserID
        		)

            SET @RetCode = Scope_Identity()


            --> INSERT SUPPLIER Journal (Payment Amount should be NEGATIVE on Supplier Account)
        	INSERT AO_Transactions 
        		(
        	         Document_Number,
        		     Document_Date,
                     Slu_AW_Months_ID,
                     Slu_AW_Years_ID,
        	         Net_Amount ,
        	         Total_Tax_Amount,
        	         Total_Amount,
        	         AB_Accounts_ID ,
        	         Comment,
        	         Sys_AW_Transaction_Types_ID ,
        	         AO_Suppliers_ID,	
        		     AW_User_Companies_ID,
        		     [User_ID]
        		)
        	VALUES
        		(
        			@NextAOTranNo,
        			@TranDate,
                    @MonthID,
                    @YearID,
        			(@Total * -1),
        			0,
        			(@Total * -1),
        			@CashControlID,
        			@Comment,
        			10,
        			@SupplierID,
        			@CompanyID,
        			@UserID
        		)
        
        	SET @NewSupplierJournalID = Scope_Identity()
        
        
        --> UPDATE Supplier Account Balance
        	UPDATE AO_Suppliers
            SET Account_Balance = Account_Balance + @Total
            WHERE AO_Suppliers_ID = @SupplierID


            EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @TranDate,
                                    @NextGLTranNo,
                                    @Narration,
                                    @MonthID,
                                    @YearID,
                                    @UserID,
                                    @CompanyID

            --> Create JOURNAL DETAIL for Expense Account
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @CreditorsControlID,
                    @Total,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            -------------------------------------------------------------------------------
            --> Create GL TRANSACTION for CREDITORS CONTROL
            -------------------------------------------------------------------------------
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @CreditorsControlID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NewSupplierJournalID,
                    @Total,
                    @UserID,
                    @CompanyID

            --> Reverse signs to balance double entry
            SET @Total = @Total * -1

            --> Create JOURNAL DETAIL for CASH CONTROL
            EXEC sp_AB_Insert_Journal_Detail
                    @JNLHeaderID,
                    @CashControlID,
                    @Total,
                    @Narration,
                    @UserID,
                    @CompanyID,
                    @InsertGLTran

            --> Create GL TRANSACTION for CASH CONTROL
            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @CashControlID,
                    @TranDate,
                    'Till Payout',
                    @MonthID,
                    @YearID,
                    @NewSupplierJournalID,
                    @Total,
                    @UserID,
                    @CompanyID
        END



RETURN @RetCode















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AS_POS_TillPayout_Lups
--Purpose       :Lups for POS Till Payout
--Functionality : 
--Date          :2009/08/06
--Authors       :TB
--Mods          :
--2004.4.8      :30/01/10 - Added V.A.T. Control Account
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AS_POS_TillPayout_Lups
    (
        @Choice tinyint,
    	@CompanyID int
    )

AS
SET NOCOUNT ON

    DECLARE @CashControl int,
            @CreditorsControl int,
            @VATControl int


    --> Years
    IF @Choice = 1 
        BEGIN
        	SELECT Slu_AW_Years_ID AS [ID], 
                	[Description] AS [Year] 
        	FROM Slu_AW_Years
        END

    --> Months
    ELSE 
    IF @Choice = 2
        BEGIN
        	SELECT Slu_AW_Months_ID AS [ID], 
                	[Description] AS [Month] 
        	FROM Slu_AW_Months
        END

    --> Suppliers
    ELSE 
    IF @Choice = 3
        BEGIN
            SELECT AO_Suppliers_ID AS [ID],
            	   Supplier_Name AS [Supplier]
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [Supplier]
        END

    --> GL Accounts
    ELSE 
    IF @Choice = 4
        BEGIN
        	SELECT AB_Accounts_ID AS [ID], 
                  [Description] AS [GL_Account] 
        	FROM AB_Accounts
        	WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID = 1
            ORDER BY [GL_Account]
        END

    --> Cash Control
    ELSE
    IF @Choice = 5
        BEGIN
			SELECT @CashControl = ISNULL(AB_Accounts_ID , 0)
            FROM AB_Control_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Control_Number = 206

			SELECT AB_Accounts_ID AS [ID],
                  [Description] AS [GL_Account] 
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @CashControl
        END

    --> Trade Creditors Control
    ELSE
    IF @Choice = 6
        BEGIN
			SELECT @CreditorsControl = ISNULL(AB_Accounts_ID, 0)
            FROM AB_Control_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Control_Number = 201

			SELECT AB_Accounts_ID AS [ID],
                  [Description] AS [GL_Account] 
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @CreditorsControl
        END

    --> V.A.T. Control
    ELSE
    IF @Choice = 7
        BEGIN
			SELECT @VATControl = ISNULL(AB_Accounts_ID, 0)
            FROM AB_Control_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Control_Number = 401

			SELECT AB_Accounts_ID AS [ID],
                  [Description] AS [GL_Account] 
            FROM AB_Accounts
            WHERE AB_Accounts_ID = @VATControl
        END


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Comment_Insert_Update
--Purpose       :INSERTS POS TRANSACTION Comments
--Tables        :AW_Comments
--Parameters    :
--Date          :2002/01/02
--Authors       :TB
--Version       :1.0.0
--MODS          :11/09/04 - Wanted to changed Sys_AT_Actor_Types_ID from -7 to 
--              :           -8 = Sales Transaction, saves but does not print on invoice
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_POS_Transaction_Comment_Insert_Update
	(
		@CommentID int OUTPUT,	
		@Comment varchar(500)
	)

AS

SET NOCOUNT ON

	IF @CommentID IS NULL AND @Comment <> ''
		BEGIN
			INSERT AW_Comments
                (
                    Sys_AT_Actor_Types_ID,
                    Comment
                ) 
            VALUES
                (
                    -7,
                    @Comment
                )

			SELECT @CommentID = Scope_Identity()
		END
	ELSE
		UPDATE AW_Comments
        SET Sys_AT_Actor_Types_ID = -7,
			Comment = @Comment
		WHERE AW_Comments_ID = @CommentID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Detail_Insert
--Purpose       :INSERTS POS transaction details and UPDATES Product On_Hand
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Details_Select
--              :       and sp_AS_POS_Transaction_Document_Details_Select_Absolute
--              :       MUST correspond to the INPUT PARAMETER NAMES BECAUSE
--              :       their values are ASSIGNED to each other after stripping the @
--              :       in POS TRANSACTION object's .Save()
--Parameters    :NB NB: The last Parameter (@TransactionTypeID) is used to
--              :       determine the sign inserted in the amount fields
--Date          :2002/01/04
--Authors       :TB
--MODS          :26/02/04 - Added SET @Cost = -(@Cost) if TranType = 4 (Credit Note)
--              :28/02/04 - Added [PromotionPrice] parameter
--              :28/02/04 - Added update to Qty_Sold if Promotion Product WAS SOLD
--              :           at the PROMOTION PRICE
--              :05/04/04 - Removed SET @Cost = -(@Cost) if TranType = 4 (Credit Note)
--              :           The Cost must be POSITIVE otherwise Item Cost is positive 
--              :           when multiplying Qty * Cost for a Refund transaction
--              :07/06/04 - Put a space after minus in SET On_Hand = On_Hand - @Qty
--              :08/01/05 - Added [JobRefID] for new AS_Job_References_ID field
--2004.3.2      :08/10/06 - Added [SerialNo] for new Serial_No field
--2004.3.4      :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :10/06/08 - Removed UPDATE of ALL RESERVED fields in AP_Products
--2004.4.7      :22/08/09 - Added UPDATE STOCK QTY if @TransactionTypeID = 23 (Stock Transfer)
--2004.4.8      :27/03/10 - Removed redundant vars
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
--V6.2	RL	2015-07-16	:Consignment stock transactions
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017-09-10	:Added Back Order Functionality
--V6.4	RL	2018-05-14	:Fixed Back Order Issues
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Detail_Insert]
    (
		@DocumentDetailsID int = NULL OUTPUT,
		@DocumentID int = NULL,
		@ProductID int = NULL,
		@Qty decimal(9,3) = 0,
		@Cost money = 0,
		@Price money = 0,
		@OriginalPrice money = 0,
		@Discount money = 0,
		@Tax money = 0,
		@TotalAmount money = 0,
		@Commission money = 0,
		@PromotionProductID int = 0,
		@PromotionPrice money = 0,
		@JobRefID int = 0,
        @SerialNo varchar(13) = '',
        @Make varchar(6) = '',
        @Customer varchar(20) = '',
		@DateCaptured datetime = NULL,
		@UserID int = NULL,
		@CompanyID int =  NULL,
		@TDHeader varchar(256) = '',
		@TDDetail varchar(256) = '',
		@ProductBinsID int,
		@BackOrder decimal(9,3) = 0,		
		@OldTransactionTypeID int = NULL,
		@TransactionTypeID int = NULL
    )
AS

SET NOCOUNT ON
	DECLARE @PromoSalesQty				decimal(9,3),
			@IsConsignmentStock			int,
			@CostingMethod				int,
			@Cost_Original				money,
			@Cost_Diff					money,
			@Oppisite_Qty				decimal(9,3),

			@H_Total_Cost				money,
			@H_Amount					money,
			@H_Total_Tax_Amount			money,
			@H_Total_Discount_Amount	money,
			@H_Total_Amount				money,
			@ExistingTransID			int

	IF ISNULL(@ProductBinsID,0) <= 0
		SET @ProductBinsID = 1

	SELECT @BackOrder = ISNULL(@BackOrder,0)

-------------------------------------------------------------------------------
    --> Based on the TransactionType, determine where Qty is to be updated
-------------------------------------------------------------------------------

    --> Invoice
	IF @TransactionTypeID = 3
	BEGIN
		--> Invoice - Check if product sold was consignment stock
		SET @IsConsignmentStock = 0
		EXEC sp_AS_Transaction_Detail_Consignment @ProductID, @Qty, @UserID, @CompanyID, @IsConsignmentStock OUTPUT
		
        UPDATE AP_Products
        SET On_Hand = On_Hand - @Qty,
            Last_Sale_Date = getdate()
        WHERE AP_Products_ID = @ProductID
                       
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			SELECT @Oppisite_Qty = @Qty * -1
				
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Oppisite_Qty,	--@Qty decimal(9,3)
    			'INV',			--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int		    	
		END	            
	END		

    --> Refund
	IF @TransactionTypeID = 4
	BEGIN
        UPDATE AP_Products
        SET On_Hand = On_Hand + @Qty
        WHERE AP_Products_ID = @ProductID
            
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Qty,			--@Qty decimal(9,3)
    			'CRN',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int
		    	
		END	
	END
	
    --> Stock Transfer - NEW 2004.4.7
	IF @TransactionTypeID = 23
	BEGIN
        UPDATE AP_Products
        SET On_Hand = On_Hand - @Qty,
            Last_Sale_Date = getdate()
        WHERE AP_Products_ID = @ProductID
            
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			SELECT @Oppisite_Qty = @Qty * -1
				
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Oppisite_Qty,	--@Qty decimal(9,3)
    			'StockTrans',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int		    	
		END	            
	END

    --> Consignment Note - NEW 2016.6.2
	IF @TransactionTypeID = 33
	BEGIN
        UPDATE AP_Products
        SET On_Hand = On_Hand - @Qty,
            Last_Sale_Date = getdate()
        WHERE AP_Products_ID = @ProductID
            
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			SELECT @Oppisite_Qty = @Qty * -1
				
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Oppisite_Qty,	--@Qty decimal(9,3)
    			'StockTrans',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int		    	
		END	
	END


-------------------------------------------------------------------------------
    --> Refund or Sales Order Reversal
	IF @TransactionTypeID = 4 or @TransactionTypeID = 17
	BEGIN
		SET @Qty = -(@Qty)
--            SET @Cost = -(@Cost)    --NB NB NB: DO NOT DO THIS because
--                                    --when multiplying -Qty * -Cost for a Refund transaction
--                                    --the cost amount is POSITIVE reflecting incorrect GP's !!
		SET @Tax = -(@Tax)
		SET @TotalAmount = -(@TotalAmount)
		SET @Commission = -(@Commission)
	END
	ELSE
	BEGIN
		SET @Discount = -(@Discount)
	END
-------------------------------------------------------------------------------


-------------------------------------------------------------------------------
    --> If a Promotion Product WAS SOLD AT the Promotion Price, add to Qty Sold
-------------------------------------------------------------------------------
    IF @TransactionTypeID = 3 OR @TransactionTypeID = 4
    BEGIN
        IF @PromotionProductID > 0
        BEGIN
            IF @Price = @PromotionPrice
            BEGIN
                SELECT @PromoSalesQty = Qty_Sold
                FROM AP_Promotion_Products
                WHERE AP_Promotion_Products_ID = @PromotionProductID
        
                SET @PromoSalesQty = @PromoSalesQty + @Qty
        
                UPDATE AP_Promotion_Products
                SET Qty_Sold = @PromoSalesQty
                WHERE AP_Promotion_Products_ID = @PromotionProductID
            END
        END
    END
-------------------------------------------------------------------------------

	IF @IsConsignmentStock = 1
	BEGIN
		
		SET @Cost_Original = @Cost
		
		SET @CostingMethod = 0
		SELECT @CostingMethod = Control_Index 
		FROM Sys_AW_Options 
		WHERE Control_Name = 'optInventoryValuation' 
		AND Control_Value = 'True'
	
		--0 - Average Cost
		--1	- Last Cost
		--2 - Standard Cost
		IF @CostingMethod IS NULL
			SET @CostingMethod = 0
			
		IF @CostingMethod = 0
		BEGIN
			SELECT @Cost = ISNULL(Average_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END

		IF @CostingMethod = 1
		BEGIN
			SELECT @Cost = ISNULL(Last_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END
		
		IF @CostingMethod = 2
		BEGIN
			SELECT @Cost = ISNULL(Standard_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END		
	END 

	SELECT @DocumentDetailsID = 0

	IF @TransactionTypeID = 16
	BEGIN
		SELECT @DocumentDetailsID = 0
		
		SELECT @DocumentDetailsID = AS_Transaction_Details_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID AND
			    AP_Products_ID = @ProductID AND
			    --Unit_Cost = @Cost AND
			    Unit_Price = @Price AND
			    Original_Price = @OriginalPrice AND
				Lup_AP_Product_Bins_ID = @ProductBinsID
		
		IF ISNULL(@DocumentDetailsID,0) <> 0
		BEGIN
			Update AS_Transaction_Details
			SET Quantity = Quantity + @Qty,
				Back_Order = Back_Order + @BackOrder,
				Unit_Cost = @Cost,
				Unit_Price = @Price,
				Original_Price = @OriginalPrice,
				Discount_Amount = Discount_Amount + @Discount,
				Tax_Amount = Tax_Amount + @Tax,
				Extended_Amount = Extended_Amount + @TotalAmount
			WHERE AS_Transaction_Details_ID = @DocumentDetailsID
		END
	END

	--If @DocumentDetailsID = 0, Insert will be done later
	IF @TransactionTypeID In (1, 2, 3, 13, 16, 33)
	BEGIN
		IF @BackOrder <> 0 
		BEGIN
			IF @OldTransactionTypeID >= -99
			BEGIN
				EXEC sp_AS_POS_Add_BO_To_SO
											@DocumentID,
											@ProductID,
											@BackOrder,
											@Qty,
											@Cost,
											@Price,
											@OriginalPrice,
											@Discount,
											@Tax,
											@TotalAmount,
											@Commission,
											@PromotionProductID,
											@PromotionPrice,
											@JobRefID,
											@SerialNo,
											@Make,
											@Customer,
											@TDHeader,
											@TDDetail,
											@ProductBinsID,
											@TransactionTypeID,
											@OldTransactionTypeID,
											@UserID,
											@CompanyID
			END

			IF @TransactionTypeID <> 16
				SET @BackOrder = 0

		END
	END

	IF ISNULL(@DocumentDetailsID,0) = 0
	BEGIN
		INSERT AS_Transaction_Details
			(
				AS_Transactions_ID,
				AP_Products_ID,
				Quantity,
				Unit_Cost,
				Unit_Price,
				Original_Price,
				Discount_Amount,
				Tax_Amount,
				Extended_Amount,
				Commission_Amount,
				AP_Promotion_Products_ID,
				AS_Job_References_ID,
				Serial_No,
				Make,
				Customer,
				User_ID,
				AW_User_Companies_ID,
				TDHeader,
				TDDetail,
				Lup_AP_Product_Bins_ID,
				Back_Order
			)
		VALUES
			(
				@DocumentID,
				@ProductID,
				(CASE WHEN @TransactionTypeID = 16 AND  @BackOrder <> 0 THEN 0 ELSE @Qty END),
				@Cost,
				@Price,
				@OriginalPrice,
				@Discount,
				@Tax,
				@TotalAmount,
				@Commission,
				@PromotionProductID,
				@JobRefID,
				@SerialNo,
				@Make,
				@Customer,
				@UserID,
				@CompanyID,
				ISNULL(@TDHeader,''),
				ISNULL(@TDDetail,''),
				@ProductBinsID,
				@BackOrder
			)

		SELECT @DocumentDetailsID = Scope_Identity()
	END
	--V6.3 RL 2017-05-13 Recalc Header Totals
	IF	( 
			@TransactionTypeID = 1 Or		--Quote
			@TransactionTypeID = 2 Or		--Job Card
			@TransactionTypeID = 3 Or		--Tax Invoice
			@TransactionTypeID = 4 Or		--Tax Credit Note
			@TransactionTypeID = 13 Or		--Pro Forma
			@TransactionTypeID = 16 Or		--Sales Order
			@TransactionTypeID = 23 Or		--Stock Transfer
			@TransactionTypeID = 33 Or		--Consignment Note
			@TransactionTypeID = 34 Or		--Consignment Sold
			@TransactionTypeID = 35			--Consignment Returned
		)
	BEGIN
		
		SELECT @H_Total_Cost = SUM((Quantity + Back_Order) * Unit_Cost),
			   @H_Total_Discount_Amount = SUM(Discount_Amount),
			   @H_Amount = SUM(Extended_Amount - Tax_Amount),
			   @H_Total_Tax_Amount = SUM(Tax_Amount),
			   @H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
            Total_Discount_Amount = @H_Total_Discount_Amount,
            Amount = @H_Amount,
            Total_Tax_Amount = @H_Total_Tax_Amount,
            Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @DocumentID
		
	END

RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Detail_Insert_SO
--Purpose       :INSERTS POS transaction details and UPDATES Product On_Hand
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Details_Select
--              :       and sp_AS_POS_Transaction_Document_Details_Select_Absolute
--              :       MUST correspond to the INPUT PARAMETER NAMES BECAUSE
--              :       their values are ASSIGNED to each other after stripping the @
--              :       in POS TRANSACTION object's .Save()
--Parameters    :NB NB: The last Parameter (@TransactionTypeID) is used to
--              :       determine the sign inserted in the amount fields
--Date          :2002/01/04
--Authors       :TB
--MODS          :26/02/04 - Added SET @Cost = -(@Cost) if TranType = 4 (Credit Note)
--              :28/02/04 - Added [PromotionPrice] parameter
--              :28/02/04 - Added update to Qty_Sold if Promotion Product WAS SOLD
--              :           at the PROMOTION PRICE
--              :05/04/04 - Removed SET @Cost = -(@Cost) if TranType = 4 (Credit Note)
--              :           The Cost must be POSITIVE otherwise Item Cost is positive 
--              :           when multiplying Qty * Cost for a Refund transaction
--              :07/06/04 - Put a space after minus in SET On_Hand = On_Hand - @Qty
--              :08/01/05 - Added [JobRefID] for new AS_Job_References_ID field
--2004.3.2      :08/10/06 - Added [SerialNo] for new Serial_No field
--2004.3.4      :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :10/06/08 - Removed UPDATE of ALL RESERVED fields in AP_Products
--2004.4.7      :22/08/09 - Added UPDATE STOCK QTY if @TransactionTypeID = 23 (Stock Transfer)
--2004.4.8      :27/03/10 - Removed redundant vars
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
--V6.2	RL	2015-07-16	:Consignment stock transactions
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017-04-21	:Added Back order amount for Sales Orders
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Detail_Insert_SO]
    (
		@DocumentDetailsID int = NULL OUTPUT,
		@DocumentID int = NULL,
		@ProductID int = NULL,
		@Qty decimal(9,3) = 0,
		@Back_Order decimal(9,3) = 0,
		@Cost money = 0,
		@Price money = 0,
		@OriginalPrice money = 0,
		@Discount money = 0,
		@Tax money = 0,
		@TotalAmount money = 0,
		@Commission money = 0,
		@PromotionProductID int = 0,
		@PromotionPrice money = 0,
		@JobRefID int = 0,
        @SerialNo varchar(13) = '',
        @Make varchar(6) = '',
        @Customer varchar(20) = '',
		@DateCaptured datetime = NULL,
		@UserID int = NULL,
		@CompanyID int =  NULL,
		@TDHeader varchar(256) = '',
		@TDDetail varchar(256) = '',
		@ProductBinsID int,		
		@OldTransactionTypeID int = NULL,
		@TransactionTypeID int = NULL
    )
AS

SET NOCOUNT ON

	DECLARE @PromoSalesQty				decimal(9,3),
			@IsConsignmentStock			int,
			@CostingMethod				int,
			@Cost_Original				money,
			@Cost_Diff					money,
			@Oppisite_Qty				decimal(9,3),

			@H_Total_Cost				money,
			@H_Amount					money,
			@H_Total_Tax_Amount			money,
			@H_Total_Discount_Amount	money,
			@H_Total_Amount				money

	IF ISNULL(@ProductBinsID,0) <= 0
		SET @ProductBinsID = 1

-------------------------------------------------------------------------------
    --> Based on the TransactionType, determine where Qty is to be updated
-------------------------------------------------------------------------------

--Insert Into Temp_Debug Values('27 - @TransactionTypeID',Convert(Varchar(100),@TransactionTypeID))  

    --> Invoice
	IF @TransactionTypeID = 3
		BEGIN
			--> Invoice - Check if product sold was consignment stock
			SET @IsConsignmentStock = 0
			EXEC sp_AS_Transaction_Detail_Consignment @ProductID, @Qty, @UserID, @CompanyID, @IsConsignmentStock OUTPUT
		
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate()
            WHERE AP_Products_ID = @ProductID
                       
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					@ProductBinsID,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'FAC INV',			--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END	
            
		END		
	

    --> Refund
	IF @TransactionTypeID = 4
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty
            WHERE AP_Products_ID = @ProductID
            
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					@ProductBinsID,	--@ProductBinID int,
    				@Qty,			--@Qty decimal(9,3)
    				'FAC CRN',	--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int
		    	
			END	
		END
	
    --> Stock Transfer - NEW 2004.4.7
	IF @TransactionTypeID = 23
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate()
            WHERE AP_Products_ID = @ProductID
            
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					@ProductBinsID,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'StockTrans',	--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END	
            
		END

    --> Consignment Note - NEW 2016.6.2
	IF @TransactionTypeID = 33
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate()
            WHERE AP_Products_ID = @ProductID
            
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					@ProductBinsID,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'StockTrans',	--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END	
            
		END


-------------------------------------------------------------------------------
    --> Refund or Sales Order Reversal
	IF @TransactionTypeID = 4 or @TransactionTypeID = 17
		BEGIN
			SET @Qty = -(@Qty)
--            SET @Cost = -(@Cost)    --NB NB NB: DO NOT DO THIS because
--                                    --when multiplying -Qty * -Cost for a Refund transaction
--                                    --the cost amount is POSITIVE reflecting incorrect GP's !!
			SET @Tax = -(@Tax)
			SET @TotalAmount = -(@TotalAmount)
			SET @Commission = -(@Commission)
		END
	ELSE
		BEGIN
			SET @Discount = -(@Discount)
		END
-------------------------------------------------------------------------------


-------------------------------------------------------------------------------
    --> If a Promotion Product WAS SOLD AT the Promotion Price, add to Qty Sold
-------------------------------------------------------------------------------
    IF @TransactionTypeID = 3 OR @TransactionTypeID = 4
        BEGIN
            IF @PromotionProductID > 0
                BEGIN
                    IF @Price = @PromotionPrice
                        BEGIN
                            SELECT @PromoSalesQty = Qty_Sold
                            FROM AP_Promotion_Products
                            WHERE AP_Promotion_Products_ID = @PromotionProductID
        
                            SET @PromoSalesQty = @PromoSalesQty + @Qty
        
                            UPDATE AP_Promotion_Products
                            SET Qty_Sold = @PromoSalesQty
                            WHERE AP_Promotion_Products_ID = @PromotionProductID
                        END
                END
        END
-------------------------------------------------------------------------------

	IF @IsConsignmentStock = 1
	BEGIN
		
		SET @Cost_Original = @Cost
		
		SET @CostingMethod = 0
		SELECT @CostingMethod = Control_Index 
		FROM Sys_AW_Options 
		WHERE Control_Name = 'optInventoryValuation' 
		AND Control_Value = 'True'
	
		--0 - Average Cost
		--1	- Last Cost
		--2 - Standard Cost
		IF @CostingMethod IS NULL
			SET @CostingMethod = 0
			
		IF @CostingMethod = 0
		BEGIN
			SELECT @Cost = ISNULL(Average_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END

		IF @CostingMethod = 1
		BEGIN
			SELECT @Cost = ISNULL(Last_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END
		
		IF @CostingMethod = 2
		BEGIN
			SELECT @Cost = ISNULL(Standard_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END		
		
	END 

	IF @TransactionTypeID = 16
	BEGIN
		SELECT @DocumentDetailsID = 0
		
		SELECT @DocumentDetailsID = AS_Transaction_Details_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		AND AP_Products_ID = @ProductID
		
		IF ISNULL(@DocumentDetailsID,0) <> 0
		BEGIN
			DELETE FROM AS_Transaction_Details
			WHERE AS_Transaction_Details_ID = @DocumentDetailsID
		END
	END

	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Back_Order,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Discount_Amount,
			Tax_Amount,
			Extended_Amount,
			Commission_Amount,
			AP_Promotion_Products_ID,
            AS_Job_References_ID,
            Serial_No,
            Make,
            Customer,
			User_ID,
			AW_User_Companies_ID,
			TDHeader,
			TDDetail,
			Lup_AP_Product_Bins_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@Back_Order,
			@Cost,
			@Price,
			@OriginalPrice,
			@Discount,
			@Tax,
			@TotalAmount,
			@Commission,
			@PromotionProductID,
            @JobRefID,
            @SerialNo,
            @Make,
            @Customer,
			@UserID,
			@CompanyID,
			ISNULL(@TDHeader,''),
			ISNULL(@TDDetail,''),
			@ProductBinsID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

	IF @TransactionTypeID = 16 Or @IsConsignmentStock = 1
	BEGIN
		
		SELECT @H_Total_Cost = SUM(Quantity * Unit_Cost),
			   @H_Total_Discount_Amount = SUM(Discount_Amount),
			   @H_Amount = SUM(Extended_Amount - Tax_Amount),
			   @H_Total_Tax_Amount = SUM(Tax_Amount),
			   @H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
            Total_Discount_Amount = @H_Total_Discount_Amount,
            Amount = @H_Amount,
            Total_Tax_Amount = @H_Total_Tax_Amount,
            Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @DocumentID
		
	END

RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Details_Select
--Purpose       :Selects POS transaction details for POS TALLY
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Detail_Insert
--              :       MUST correspond to the INPUT PARAMETER NAMES BECAUSE
--              :       their values are ASSIGNED to each other after stripping the @
--              :       in POS TRANSACTION object's .Save()
--Parameters    :The order of fields determine the order in the POS Tally grid
--Date          :2002/01/03
--Authors       :TB
--Version       :1.0.0
--MODS          :15/02/04 - Replaced d.Item_Number with NEW d.AP_Promotion_Products_ID
--              :26/02/04 - Replaced [ItemsNumber] with [PromotionProductID] that
--              :           caused an 'Cannot find item in collection' error when
--              :           extracting the Detail parameters in SpSPOSTrans.CDocument
--              :28/02/04 - Added [PromotionPrice] parameter
--              :08/01/05 - Added [JobRefID] for new AS_Job_References_ID field
--2004.3.2      :08/10/06 - Added [SerialNo] for new Serial_No field
--2004.3.4      :21/03/07 - Added [Make] and [Customer] fields
--2004.3.7      :03/08/07 - Added [TaxRate] field
--              :05/08/07 - Changed ORDER of TALLY amount columns in SetGridWidths() to now
--              :           moved Unit Price ahead of Discount and Total
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017/04/21	:Added Back Order Qty to Qty For Sales Orders
--V6.3	RL	2017/05/03	:Inserted result set into a @table and select from there due to sum issue
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_POS_Transaction_Document_Details_Select]
    (
        @DocumentID int
    )

AS

SET NOCOUNT ON

	Declare @Tbl1 Table
	(
		[Description]			varchar(50),
		[Code]					varchar(20),
		[Qty]					decimal(9,3),		
		[Price]					money,
		[Discount]				money,
		[TotalAmount]			money,
		[Cost]					money,
		[OriginalPrice]			money,
		[Tax]					money,
		[Commission]			money,
		[PromotionProductID]	integer,
		[PromotionPrice]		money,
		[JobRefID]				integer,
		[SerialNo]				varchar(13),
		[Make]					varchar(6),
		[Customer]				varchar(20),
		[DateCaptured]			datetime,
		[UserID]				integer,
		[CompanyID]				integer,
		[DocumentDetailsID]		integer,
		[DocumentID]			integer,
		[ProductID]				integer,
		[TaxRate]				decimal(9,3),
		[TDHeader]				varchar(256),
		[TDDetail]				varchar(256),
		[ProductBinsID]			integer,
		[BackOrder]				decimal(9,3)
	)
	

	INSERT INTO @Tbl1
    SELECT 
    	p.Description as [Description],
    	p.Product_Code as [Code], 
    	--dbo.fn_AP_Get_Transaction_Qty_BO(AS_Transaction_Details_ID) AS [Qty],
    	--(d.Quantity + d.Back_Order) AS [Qty],
    	d.Quantity AS [Qty],
    	d.Unit_Price as [Price], 
    	d.Discount_Amount as [Discount], 
    	d.Extended_Amount as [TotalAmount], 
    	d.Unit_Cost as [Cost], 
    	d.Original_Price as [OriginalPrice], 
    	d.Tax_Amount as [Tax], 
    	d.Commission_Amount as [Commission], 
    	d.AP_Promotion_Products_ID as [PromotionProductID], 
    	d.Unit_Price as [PromotionPrice], 
    	d.AS_Job_References_ID as [JobRefID],
        d.Serial_No as [SerialNo],
        d.Make as [Make],
        d.Customer as [Customer],
    	d.Date_Captured as [DateCaptured], 
    	d.User_ID as [UserID], 
    	d.AW_User_Companies_ID as [CompanyID],
    	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
    	d.AS_Transactions_ID as [DocumentID], 
    	d.AP_Products_ID as [ProductID],
        t.Tax_Rate as [TaxRate],
        d.TDHeader as TDHeader,
        d.TDDetail as TDDetail,
        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
		d.Back_Order as [BackOrder]

    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p 
    		ON d.AP_Products_ID = p.AP_Products_ID
		LEFT JOIN Sys_AW_Tax_Codes t
            ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
    WHERE AS_Transactions_ID = @DocumentID
    
    SELECT * From @Tbl1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Details_Select_Absolute
--Purpose       :Loads RECALLed Transaction Details at POS
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Detail_Insert
--              :       MUST correspond to the INPUT PARAMETER NAMES BECAUSE
--              :       their values are ASSIGNED to each other after stripping the @
--              :       in POS TRANSACTION object's .Save()
--Peculiarity   :THE ORDER OF FIELDS DETERMINE THE ORDER IN THE POS TALLY GRID
--Date          :2002/01/05
--Authors       :TB
--MODS          :15/02/04 - Replaced d.Item_Number with NEW d.AP_Promotion_Products_ID
--              :26/02/04 - Replaced [ItemsNumber] with [PromotionProductID] that
--              :           caused an 'Cannot find item in collection' error when
--              :           extracting the Detail parameters in SpSPOSTrans.CDocument
--              :28/02/04 - Added [PromotionPrice] parameter
--              :22/05/04 - Added POS Document RECALL Product Re-Costing method
--              :08/01/05 - Added [JobRefID] for new AS_Job_References_ID field
--2004.3.2      :24/09/06 - Added @ActiveOnly to optionally recall ACTIVE products ONLY
--              :08/10/06 - Added [SerialNo] for new Serial_No field
--2004.3.4      :21/03/07 - Added [Make] and [Customer] fields
--2004.3.5      :13/05/07 - Added replace UNUSED (ABS(d.Commission_Amount) as [Commission])
--              :           on recalled Job Card and Sales Order transactions with
--              :           (ABS(d.Quantity) as [Commission]) using IMPLICIT CONVERSION
--              :           to enable identifying ITEMS as a RECALLED item in ExceedsOnHand()
--              :           using 'Include Qty Reserved on Job Cards in On Hand validation'
--2004.3.7      :03/08/07 - Added [TaxRate] field
--              :05/08/07 - Changed ORDER of TALLY amount columns in SetGridWidths() to now
--              :           moved Unit Price ahead of Discount and Total
--2004.4.0      :09/07/08 - Removed CONVERT numerics to ABS() if recalled document
--              :           is a JOBCARD or SALES ORDER (@ReserveTypeRecall = 1)
--              :14/08/08 - Commented CONVERT numerics to ABS() ONLY if recalled document
--              :           is a JOBCARD or SALES ORDER (@ReserveTypeRecall = 1)
--              :           This causes [Discount] in Tally to be NEGATIVE and the AMOUNT
--              :           value to be incorrect with DOUBLE the [Discount] amount
--              :03/09/08 - Added CONVERT [Discount] numerics to ABS() if recalled document
--              :           is a SALES ORDER (@ReserveTypeRecall = 1) to enable correct
--              :           recall of SALES ORDER VOLUME DISCOUNTS Tax amount
--2004.4.2      :30/11/08 - Removed @ReserveTypeRecall and replaced with @TranTypeID and added
--              :           seperate section for JOB CARD recalls and added assign QUANTITY
--              :           to the COMMISSION field as RESERVED !!!
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017-05-04  :Added Back Order Qty to Qty
--V6.3	RL	2017-09-10	:Return Back_Order
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_POS_Transaction_Document_Details_Select_Absolute]
    (
        @DocumentID int
    )

AS

SET NOCOUNT ON


    DECLARE @RecallCosting smallint,
            @CostingMethod smallint,
            @ActiveOnly varchar(10),
            @TranTypeID tinyint


    SET @RecallCosting = 0

    SELECT @RecallCosting = Control_Index
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSRecallCosting' AND
          Control_Value = 'True'


    SET @CostingMethod = 0

    SELECT @CostingMethod = Control_Index
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True'


    SET @ActiveOnly = ''

    SELECT @ActiveOnly = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = 'CheckBox' AND
          Control_Name = 'chkRecallActiveOnly' AND
          Control_Index = 0


    ---------------------------------------------------------------------
    --> Set the Transaction Type ID of the RECALLED document if ACTIVE
    ---------------------------------------------------------------------
    SET @TranTypeID = 0


    SELECT @TranTypeID = ISNULL(Sys_AW_Transaction_Types_ID, 0)
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @DocumentID AND
          Slu_AW_Active_ID = 1
    ---------------------------------------------------------------------


-------------------------------------------------------------------------------
-- IF Recalled document is a JOB CARD - Convert to ABS()
--    and assign its Quantity as [Commission]
-------------------------------------------------------------------------------
    IF @TranTypeID = 2        --JOB CARD
        BEGIN
            IF @ActiveOnly = '1'        --Recall only Products that are currently set as ACTIVE
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                END
            ELSE                        --Recall ALL Products (ignore Slu_AW_Active_ID)
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + (d.Back_Order + d.Back_Order) ) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price],
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                END
        END

-------------------------------------------------------------------------------
-- IF Recalled document is a SALES ORDER - DO NOT Convert to ABS()
--    and assign its Quantity as [Commission]
-------------------------------------------------------------------------------
    ELSE
    IF @TranTypeID = 16        --SALES ORDER
        BEGIN
            IF @ActiveOnly = '1'        --Recall only Products that are currently set as ACTIVE
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ISNULL(p.Average_Cost, 0)
                                     WHEN @CostingMethod = 1
                                         THEN ISNULL(p.Last_Cost, 0)
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN d.Unit_Cost = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ISNULL(p.Average_Cost, 0)
                                             WHEN @CostingMethod = 1
                                                 THEN ISNULL(p.Last_Cost, 0)
                                             ELSE d.Unit_Cost
                                        END
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                END
            ELSE                        --Recall ALL Products (ignore Slu_AW_Active_ID)
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
--                            	d.Discount_Amount as [Discount], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ISNULL(p.Average_Cost, 0)
                                     WHEN @CostingMethod = 1
                                         THEN ISNULL(p.Last_Cost, 0)
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN d.Unit_Cost = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ISNULL(p.Average_Cost, 0)
                                             WHEN @CostingMethod = 1
                                                 THEN ISNULL(p.Last_Cost, 0)
                                             ELSE d.Unit_Cost
                                        END
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	(d.Quantity + d.Back_Order) as [Qty], 
                            	d.Unit_Price as [Price],
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, (d.Quantity + d.Back_Order)) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                END
        END
-------------------------------------------------------------------------------
-- IF Recalled document is a Quote, Invoice, Refund, Pro-Forma - Convert ABS()
--    and assign Commission_Amount as [Commission]
-- This section was how ALL documents were recallled prior to 2004.4.0
-------------------------------------------------------------------------------
    ELSE
        BEGIN
            IF @ActiveOnly = '1'        --Recall only Products that are currently set as ACTIVE
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                END
            ELSE                        --Recall ALL Products (ignore Slu_AW_Active_ID)
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
                       			d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity + d.Back_Order) as [Qty], 
                            	ABS(d.Unit_Price) as [Price],
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                END
        END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Insert
--Purpose       :INSERTS (SAVES) POS TRANSACTIONS
--Tables        :AS_Transactions
--Parameters    :
--Date          :2002/01/02
--Authors       :TB
--Version       :1.0.0
--MODS          :24/01/02 - Made CASH SALE Payment Transaction Number same as its
--              :            originating transaction
--              :15/04/02 - Update AC_Customers Account Balance
--              :26/02/04 - Added SET @Total_Cost = -(@Total_Cost) for Refunds
--              :           (TranType = 4) to correctly update C.O.S. GL Account
--              :           with net cost of POS Invoices and Credit Notes
--2004.5.3      :11/09/11 - Replaced input variable @Transmitted with @SmallComment
--              :           to match CDocument.mrsdata definitions in SpSPOSTrans
--              :           loaded from: vw_AS_POS_Transaction_Headers_Select and
--              :                        vw_AS_POS_Transaction_Headers_Select_Absolute
--RL	V6.3	:2017/09/25 - Send through @CustomerReference and @SmallComment
--RL	V6.3	:2017/09/25 - Used @VersionNumber to handel sales orders
-------------------------------------------------------------------------------


CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Insert]
    (
    	@DocumentID int = NULL output ,
    	@CustomerID int = NULL ,
    	@AccountID int = NULL ,
    	@No varchar(19) = NULL , -- TransactionNumber
    	@Total_Cost money = NULL ,
    	@Total_SubTotal money = NULL ,
    	@Total_Tax money = NULL ,
    	@Total_Discount money = NULL ,
    	@Total_Total money = NULL ,
    	@Payment money = NULL ,
    	@Date datetime = NULL ,
    	@ExpiryDate datetime = NULL ,
    	@VersionNumber int = NULL ,
    	@CustomerReference varchar(15) = NULL ,
    	@Comment varchar(500) = NULL ,
    	@TransactionTypeID int = NULL ,
    	--@MarketingIndicatorsID int = NULL ,
    	@StoreID int = NULL ,
    	@WorkstationID int = NULL ,
    	@TillID int = NULL ,
    	@CashierID int = NULL ,
    	@RepID int = NULL ,
    	@CurrencyID int = NULL ,
    	@OldTransactionTypeID int = NULL ,
    	@CancelledUserID int = NULL ,
    	@CancelledDate Datetime = NULL ,
    	@CashedUp Datetime = NULL ,
    	@DayEnd Datetime = NULL ,
--    	@Transmitted Datetime = NULL ,
    	@SmallComment varchar(20) = NULL ,
    	@DateCaptured Datetime = NULL ,
    	@UserID int = NULL ,
    	@CompanyID int = NULL ,
    	@CommentID int = NULL
    )

AS

	DECLARE @TransNum varchar(15)
	SET @DocumentID = 0

	IF ISNULL(@VersionNumber,0) = 0
		SET @VersionNumber = 0

	--Normal Document Creation
	IF ((@VersionNumber = 0) Or (@TransactionTypeID <> 16))
	BEGIN

		--SET @VersionNumber = 1
		SET @TransNum = @No            -- Assign TransactionNumber to @TransNum

		If @TransNum = '' OR @TransNum Is Null
			EXEC sp_AW_Get_Next_Transaction_Number @TransactionTypeID, @CompanyID, @No OUTPUT

		EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Comment

		IF @TransactionTypeID = 4 
			BEGIN
				SET @Total_Cost = -(@Total_Cost)
				SET @Total_SubTotal = -@Total_SubTotal
				SET @Total_Tax = -@Total_Tax
				SET @Total_Discount = -@Total_Discount
				SET @Total_Total = -@Total_Total
			END

		INSERT AS_Transactions
			(
				AC_Customers_ID,
				AB_Accounts_ID,
				Transaction_Number,
				Total_Cost,
				Amount,
				Total_Tax_Amount,
				Total_Discount_Amount,
				Total_Amount,
				Payment_Amount,
				--Transaction_Date,
				Expiry_Date,
				Version_Number,
				Customer_Reference,
				--Comments,
				Sys_AW_Transaction_Types_ID,
				--Lup_AS_Marketing_Indicators_ID,
				Lup_AW_Stores_ID,
				Lup_AW_Workstations_ID,
				Lup_AS_Tills_ID,
				Lup_AS_Cashiers_ID,
				Lup_AS_Reps_ID,
				Slu_AW_Currencies_ID,
				Old_Sys_AW_Transaction_Types_ID,
				Cancelled_User_ID,
				Cancelled_DateTime,
				Cashed_Up,
				Day_End,
				--Transmitted,
				--Date_Captured,
				Comment,
				User_ID,
				AW_User_Companies_ID,
				AW_Comments_ID
			)
		VALUES
			(
				@CustomerID,
				@AccountID,
				@No, -- TransactionNumber
				@Total_Cost,
				@Total_SubTotal,
				@Total_Tax,
				-@Total_Discount,
				@Total_Total,
				-(@Payment),
				--@Date,
				@ExpiryDate,
				1,
				@CustomerReference,
				--@Comments,
				@TransactionTypeID,
				--@MarketingIndicatorsID,
				@StoreID,
				@WorkstationID,
				@TillID,
				@CashierID,
				@RepID,
				@CurrencyID,
				@OldTransactionTypeID,
				@CancelledUserID,
				@CancelledDate,
				@CashedUp,
				@DayEnd,
				--@Transmitted,
				--@Date,
				@SmallComment,
				@UserID,
				@CompanyID,
				@CommentID
			)

		SELECT @DocumentID = Scope_Identity()

	--> Update the Customer Account Balance
		IF @TransactionTypeID = 3 OR @TransactionTypeID = 4
    		BEGIN	
    			UPDATE AC_Customers
				SET Account_Balance = Account_Balance + (@Total_Total - @Payment)
				WHERE AC_Customers_ID = @CustomerID
    		END
	END

	--Update Existing Sales Order
	IF ( (@VersionNumber = -99) OR (@VersionNumber = -88) )
	BEGIN
		IF @TransactionTypeID = 16
		BEGIN
			SELECT @DocumentID = AS_Transactions_ID
			FROM AS_Transactions
			WHERE   AC_Customers_ID = @CustomerID AND
					Customer_Reference = @CustomerReference AND
					SLU_AW_Active_ID = 1 AND
					AW_User_Companies_ID = @CompanyID AND
					Sys_AW_Transaction_Types_ID = 16
			ORDER BY Transaction_Date Asc

			UPDATE AS_Transactions
			SET Transaction_Date = GETDATE()
			WHERE AS_Transactions_ID = @DocumentID
		END
		--IF @VersionNumber = -99
		--BEGIN
		--	UPDATE AO_Order_Candidates
		--	SET Qty = Qty - Back_Order
		--	FROM AO_Order_Candidates o
		--		INNER JOIN AS_Transaction_Details d
		--			On o.AP_Products_ID = d.AP_Products_ID
		--	WHERE d.AS_Transactions_ID = @DocumentID AND
		--		Back_Order <> 0

		--	DELETE FROM AO_Order_Candidates
		--	WHERE Qty <= 0
		--END
	END	
	
	--Update Current Recalled Sales Order
	IF @VersionNumber > 0
	BEGIN
		UPDATE AO_Order_Candidates
		SET Qty = Qty - Back_Order
		FROM AO_Order_Candidates o
			INNER JOIN AS_Transaction_Details d
				On o.AP_Products_ID = d.AP_Products_ID
		WHERE d.AS_Transactions_ID = @VersionNumber AND
			Back_Order <> 0

		DELETE FROM AO_Order_Candidates
		WHERE Qty <= 0

		DELETE FROM AS_Transaction_Details 
		WHERE AS_Transactions_ID = @VersionNumber

		UPDATE AS_Transactions
		SET Total_Cost = 0,
			Amount = 0,
			Total_Tax_Amount = 0,
			Total_Discount_Amount = 0,
			Total_Amount = 0,
			Transaction_Date = GETDATE()
		WHERE AS_Transactions_ID = @VersionNumber

		SET @DocumentID = @VersionNumber
	END

RETURN @DocumentID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-----------------------------------------------------------------------------
--Description   :The POS SELECT Transaction
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/01/05
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE      PROCEDURE sp_AS_POS_Transaction_Document_Select
    (
        @DocumentID int
    )

AS

SET NOCOUNT ON

    SELECT * 
    FROM vw_AS_POS_Transaction_Headers_Select
    WHERE DocumentID = @DocumentID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :The POS SELECT Transaction
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/01/05
--Authors       :TB
--Version       :1
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_POS_Transaction_Document_Select_Filtered
	(
    	@CustomerID int = 0,
    	@TransactionTypeID int = 0,
    	@TransactionNumber varchar(100) = '',
    	@DateFrom DateTime = NULL,
    	@DateTo DateTime = NULL
	)

AS

SET NOCOUNT ON

	IF NOT @CustomerID = 0
		BEGIN
			IF NOT @TransactionTypeID = 0
				BEGIN				
					IF NOT @TransactionNumber =  ''
						SELECT *
                        FROM vw_AS_POS_Transaction_Headers_Select_Absolute
						WHERE CustomerID = @CustomerID AND
                              TransactionTypeID = @TransactionTypeID AND
                              [No] LIKE '%' + @TransactionNumber + '%'
						ORDER BY DateCaptured DESC

					ELSE
						SELECT *
                        FROM vw_AS_POS_Transaction_Headers_Select_Absolute
						WHERE CustomerID = @CustomerID AND
                              TransactionTypeID = @TransactionTypeID 
						ORDER BY DateCaptured DESC
				END
			ELSE
			IF NOT @TransactionNumber = ''
				BEGIN
					SELECT *
                    FROM vw_AS_POS_Transaction_Headers_Select_Absolute
					WHERE CustomerID = @CustomerID AND
                          [No] like '%' + @TransactionNumber + '%'
					ORDER BY DateCaptured DESC
				END
			ELSE
				BEGIN
					SELECT *
                    FROM vw_AS_POS_Transaction_Headers_Select_Absolute
					WHERE CustomerID = @CustomerID
					ORDER BY DateCaptured DESC
				END
		END
	ELSE
	IF NOT @TransactionTypeID = 0
		BEGIN				
			IF NOT @TransactionNumber = ''
				SELECT *
                FROM vw_AS_POS_Transaction_Headers_Select_Absolute
				WHERE TransactionTypeID = @TransactionTypeID AND
                      [No] LIKE '%' + @TransactionNumber + '%'
				ORDER BY DateCaptured DESC

			ELSE
				SELECT *
                FROM vw_AS_POS_Transaction_Headers_Select_Absolute
				WHERE TransactionTypeID = @TransactionTypeID 
				ORDER BY DateCaptured DESC
		END
	ELSE
	IF NOT @TransactionNumber = ''
		SELECT *
        FROM vw_AS_POS_Transaction_Headers_Select_Absolute
		WHERE [No] LIKE '%' + @TransactionNumber + '%'
		ORDER BY DateCaptured DESC
	ELSE
		SELECT TOP 1000 *
        FROM vw_AS_POS_Transaction_Headers_Select_Absolute
		ORDER BY [Date] DESC


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Select_One
--Purpose       :Fetch ONE POS Transaction for a TransactionID
--Date          :2010/03/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_POS_Transaction_Document_Select_One
	(
    	@CustomerID int,
    	@TransactionID int
	)

AS

SET NOCOUNT ON

	IF NOT @CustomerID = 0
		BEGIN
        	IF NOT @TransactionID = 0
                BEGIN
            		SELECT *
                    FROM vw_AS_POS_Transaction_Headers_Select_Absolute
            		WHERE CustomerID = @CustomerID AND
                          DocumentID = @TransactionID
                END
		END


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-----------------------------------------------------------------------------
--Description   :The POS SELECT Transaction Number For E-Mail
--Date          :2018-04-09
--Authors       :RL
--Version       :6.4
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Number_Select]
    (
        @DocumentID int,
        @Transaction_Number	varchar(19) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Transaction_Number = Transaction_Number
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @DocumentID

	IF @Transaction_Number IS NULL 
        BEGIN	
    		SET @Transaction_Number = ''
        END
		
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   : sp_AS_POS_Transaction_Payment_Detail_Insert
--Purpose       : Inserts POS Payment Transaction Details (TranTypeID = 4)
--Functionality : Tables: AS_Transaction_Payments
--Parameters    : 
--Date          : 2002/01/29
--Authors       : TB
--Version       :
--V6.4	RL	2018-03-07	:Add IPay
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Detail_Insert]
	(					
		@Amount				money = NULL,	
		@PayorName			varchar(50) = NULL,
		@CardExpiryDate		varchar(6) = NULL,
		@CardNo				varchar(20) = NULL,
		@AuthorisationNo	varchar(20) = NULL,
		@MethodID			int = NULL,
		@InstitutionID		int = NULL,
		@UserID				int = NULL,
		@CompanyID			int = NULL,
		@PaymentDetailsID	int = NULL,
		@PaymentID			int = NULL,
		@Date				dateTime = NULL,
        @IPay_ID			varchar(50),
        @IPay_Tran_Ref		varchar(50),
        @IPay_Bank_Ref		varchar(50),
        @IPay_Status		int,
        @Cell_No			varchar(20),
        @Email				varchar(100)
	)

AS


    -- @PaymentDetailsID int = NULL,    -- Above input parameter not used ???

    SET NOCOUNT ON

	DECLARE @AS_Transaction_Payments_ID	int,
			@AS_Transactions_ID	int,
			@Transaction_Number varchar(19)
	
	INSERT AS_Transaction_Payments
    	(	
    		AS_Transactions_ID,
    		Sys_AW_Payment_Methods_ID, 
    		Slu_AS_Card_Institutions_ID,
    		Payor_Name,
    		Card_Expiry_Date,
    		Card_Number,
    		Authorisation_Number,
    		Amount,
    		[User_ID],
    		AW_User_Companies_ID,
    		Date_Captured
    	)
	VALUES
    	(
    		@PaymentID,
    		@MethodID,
    		@InstitutionID,
    		@PayorName,
    		@CardExpiryDate,
    		@CardNo,
    		@AuthorisationNo,
    		@Amount,
    		@UserID,
    		@CompanyID,
    		@Date
    	)
    	
    SELECT @AS_Transaction_Payments_ID = Scope_Identity()
    
	IF (ISNULL(@IPay_ID,'') <> '' And (@MethodID = 14))
	BEGIN
		--SELECT @Transaction_Number = Transaction_Number
		--FROM AS_Transactions
		--WHERE AS_Transactions_ID = @PaymentID 
	
		--SELECT @AS_Transactions_ID = AS_Transactions_ID
		--FROM AS_Transactions
		--WHERE Sys_AW_Transaction_Types_ID = 3
		--AND Transaction_Number = @Transaction_Number
	
		Update AS_Transaction_Payments_IPay
		Set --AS_Transactions_ID = @AS_Transactions_ID,
			AS_Transaction_Payments_ID = @AS_Transaction_Payments_ID,
			IPay_Status = 1
		Where IPay_ID = @IPay_ID
		AND IPay_Action IN ('PAY SUC' ,'PAYDONE', 'DAYEND_1')
		--AND IPay_Status <> 1
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Payment_Details_Select
--Purpose       :POS Payment Transaction Details
--Functionality :NB NB: The order of fields are determined by the order in the tally 
--Date          :2002/01/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
--V6.4	RL	2018-03-07	:Add IPay
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Details_Select]
    (
        @PaymentID int
    )

AS

SET NOCOUNT ON

    SELECT 
        m.Description AS [Method],
        i.Description AS [Institution],
        p.Amount AS [Amount], 
        p.Payor_Name AS [PayorName], 
        p.Card_Expiry_Date AS [CardExpiryDate], 
        p.Card_Number AS [CardNo], 
        p.Authorisation_Number AS [AuthorisationNo], 
        p.Sys_AW_Payment_Methods_ID AS [MethodID], 
        p.Slu_AS_Card_Institutions_ID AS [InstitutionID], 
        p.Date_Captured AS [Date], 
        p.[User_ID] AS [UserID], 
        p.AW_User_Companies_ID AS [CompanyID],
        p.AS_Transaction_Payments_ID AS [PaymentDetailsID],
        p.AS_Transactions_ID AS [PaymentID],
        p.Date_Captured AS [Date],
		y.IPay_ID as [IPay_ID],
		y.IPay_Tran_Ref As [IPay_Tran_Ref],
		y.IPay_Bank_Ref As [IPay_Bank_Ref],
        y.IPay_Status As [IPay_Status],
        y.Cell_No As [Cell_No],
        y.Email	As [Email]
        
    FROM AS_Transaction_Payments p
        LEFT JOIN Sys_AW_Payment_Methods m
            ON p.Sys_AW_Payment_Methods_ID = m.Sys_AW_Payment_Methods_ID
        LEFT JOIN Slu_AS_Card_Institutions i
            ON p.Slu_AS_Card_Institutions_ID = i.Slu_AS_Card_Institutions_ID
        LEFT JOIN AS_Transaction_Payments_IPay y
			ON p.AS_Transaction_Payments_ID = y.AS_Transaction_Payments_ID
    WHERE p.Slu_AW_Active_ID = 1 AND
          p.AS_Transactions_ID = @PaymentID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Payment_Insert
--Purpose       :Inserts POS Payment Transactions (TranTypeID = 4)
--SEE ALSO      :sp_AS_Transaction_Payment_Insert (Back Office Payment insert)
--Functionality :INSERTS: AS_Transactions, AS_Transactions_Transactions
--              :UPDATES: AC_Customers
--Date          :2002/01/23
--Authors       :TB
--MODS          :
--2004.3.8      :29/05/08 - Replaced errorneous ABS(@TotalAmount) insert into
--              :           AS_Transactions_Transactions with -@TotalAmount to insert
--              :           the SAME value as inserted in AS_Transactions for
--              :           TranType 7 (POS Payments). ABS(@TotalAmount) inserted
--              :           the SAME SIGNED value for POSITIVE AND NEGATIVE payments !!!
--V6.4	RL	2018-03-07	:Add IPay
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Insert]
	(
        @PaymentID int OUTPUT,
        @CustomerID int = NULL,
        @AccountID int = NULL,
        @TransactionNumber varchar(19) = NULL,
        @TotalAmount money = 0,
        @PaymentAmount money = 0,
        @CustomerReference varchar(15) = NULL,
        @TransactionTypeID int = NULL,
        @StoreID int = NULL,
        @WorkstationID int = NULL,
        @TillID int = NULL,
        @CashierID int = NULL,
        @RepID int = NULL,
        @CurrencyID int = NULL,
        @DateCaptured datetime = NULL,
        @UserID int = NULL,
        @CompanyID int = NULL,
        @SourceTransactionID int = NULL
 
	)
AS

SET NOCOUNT ON

	DECLARE
        @CommentID int,
        @SourceTransactionTypeID int,
        @TransNum varchar(19)
        
        
	SELECT @SourceTransactionTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @SourceTransactionID
        

    SET @TransNum = @TransactionNumber        

    --> Fetch only if no Transaction Number passed in
    IF @TransNum = '' OR @TransNum Is Null
        EXEC sp_AW_Get_Next_Transaction_Number
                        @TransactionTypeID,
                        @CompanyID,
                        @TransactionNumber OUTPUT
------------------------------------------------
        
	IF @SourceTransactionTypeID = 4    -- Refund
		BEGIN
			SET @TotalAmount = -@TotalAmount
			SET @PaymentAmount = -@PaymentAmount
		END

	--V6.4 RL
	--This is a dirty fix for i-Pay. Needs to be done properly in Elite
	--Not enough time to do it properly
	--There is a scenario were the user can allocate another payment to an i-Pay pay later transaction
	--In this case we don't want to allocate the payment to the invoice as it will over allocate it.
	--We just capture the payment and the user needs to go allocate it.
	 
	IF ISNULL(@CurrencyID,0) = 99
	BEGIN
		SET @PaymentAmount = 0
	END

	INSERT AS_Transactions
		(
			AC_Customers_ID,
			AB_Accounts_ID,
			Transaction_Number,
			Amount, 
			Total_Amount,
			Payment_Amount,
			Customer_Reference,
			Sys_AW_Transaction_Types_ID,
			Lup_AW_Stores_ID,
			Lup_AW_Workstations_ID,
			Lup_AS_Tills_ID,
			Lup_AS_Cashiers_ID,
			Lup_AS_Reps_ID,
			Slu_AW_Currencies_ID,
			[User_ID],
			AW_User_Companies_ID
		)
	VALUES
		(
			@CustomerID,
			@AccountID,
			@TransactionNumber,
			-(@TotalAmount),
			-(@TotalAmount),
			@PaymentAmount,
			@CustomerReference,
			7,
			@StoreID,
			@WorkstationID,
			@TillID,
			@CashierID,
			@RepID,
			NULL,--@CurrencyID,
			@UserID,
			@CompanyID
		)

	SELECT @PaymentID = Scope_Identity()

	IF ISNULL(@CurrencyID,0) <> 99
	BEGIN
		--> Update the ORIGINAL transaction's Payment Amount
		UPDATE AS_Transactions
		SET Payment_Amount = Payment_Amount - @PaymentAmount
		WHERE AS_Transactions_ID = @SourceTransactionID

		INSERT AS_Transactions_Transactions 
			(
				Source_AS_Transactions_ID,
				Destination_AS_Transactions_ID,
				Amount
			)
		VALUES
			(
				@SourceTransactionID,
				@PaymentID,
	--            ABS(@TotalAmount)
				-@TotalAmount
			)

		--> UPDATE Customer Account Balance
		UPDATE AC_Customers
		SET Account_Balance = Account_Balance - @TotalAmount
		WHERE AC_Customers_ID = @CustomerID
	END
	
    RETURN @PaymentID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Payment_Select
--Purpose       :POS Payment Transaction Header
--              :
--Date          :2002/01/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Select]
	(
        @DocumentID int
    )

AS

SET NOCOUNT ON

	SELECT 
		t.AS_Transactions_ID as PaymentID, 
		t.AC_Customers_ID as CustomerID, 
		t.AB_Accounts_ID as AccountID, 
		t.Transaction_Number as TransactionNumber, 
		--Total_Cost as Cost, 						--These fields are appended in a shape to be calculated
		--Amount as Amount, 
		--Total_Tax_Amount as Tax, 
		--Total_Discount_Amount as Discount, 
		--Total_Amount as TotalAmount, 
		--Payment_Amount as PaymentAmount, 
		t.Customer_Reference as CustomerReference, 
		--t.Comments, 
		t.Sys_AW_Transaction_Types_ID as TransactionTypeID, 
		t.Lup_AW_Stores_ID as StoreID, 
		t.Lup_AW_Workstations_ID as WorkstationID, 
		t.Lup_AS_Tills_ID as TillID, 
		t.Lup_AS_Cashiers_ID as CashierID, 
		t.Lup_AS_Reps_ID as RepID, 
		t.Slu_AW_Currencies_ID as CurrencyID, 
		t.Date_Captured as DateCaptured,  
		t.User_ID as UserID,  
		t.AW_User_Companies_ID as CompanyID,
		tt.Source_AS_Transactions_ID as SourceTransactionID
    FROM AS_Transactions t 
		INNER JOIN AS_Transactions_Transactions tt
			ON t.AS_Transactions_ID = tt.Source_AS_Transactions_ID
    WHERE t.AS_Transactions_ID = @DocumentID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description	:sp_AS_POS_Update_Delivery_Address
--Purpose       :UPDATE Customer Delivery Address from POS.frmDelAddr
--Date			:2011/07/22
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_POS_Update_Delivery_Address
	(
		@CustomerID int,
        @DelAddress varchar(40),
        @DelSuburb varchar(40),
        @DelCity varchar(30),
        @DelCode varchar(10)
	)

AS

SET NOCOUNT ON


    UPDATE AC_Customers
    SET Delivery_Address = @DelAddress,
        Delivery_Suburb = @DelSuburb,
        Delivery_City = @DelCity,
        Delivery_Post_Code = @DelCode
    WHERE AC_Customers_ID = @CustomerID



SET NOCOUNT OFF
	











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Payment_Unallocate
--Purpose       :CURSOR - Reverses Customer Payment Allocations for a specific Payment
--Date          :2018-03-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_Payment_Unallocate]
    (
        @PaymentTranID int,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

	--Transaction handled in code
    -----------------------------------------------------------
    --BEGIN TRAN Reverse_Payment
    -----------------------------------------------------------

	DECLARE @Linked_AS_Transactions_ID			Int,
			@Payment_Amount						Decimal(18,2),
			@Allocated_Amount					Decimal(18,2),
			@Amount								Decimal(18,2),
			@ReturnCode							Int,
			@AS_Transactions_Transactions_ID	Int,
			@Transactions_Type_ID				Int,
			@Rev_JRN							Int,
			@Run_Once							Int

	SELECT @ReturnCode = 0
	SELECT @Rev_JRN = 0
	SELECT @Run_Once = 0

	--Check if allocated amount is same as payment amount
	SELECT	@Payment_Amount = Payment_Amount,
			@Transactions_Type_ID = Sys_AW_Transaction_Types_ID
	FROM AS_Transactions
	WHERE AS_Transactions_ID = @PaymentTranID

	IF @Transactions_Type_ID = 4
	BEGIN
--Select 1
		--@PaymentTranID Is Always in the Source_AS_Transactions_ID
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
		AND ISNULL(Destination_AS_Transactions_ID,0) <> 0

		IF @Payment_Amount <> (@Allocated_Amount)
			SELECT @ReturnCode = 2			
	END
	ELSE 
	IF @Transactions_Type_ID = 5
	BEGIN
--Select 2
		SET @Allocated_Amount = 0

		--Destination_AS_Transactions_ID tested with positive and negative
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
		AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID

		IF ISNULL(@Allocated_Amount,0) = 0
		BEGIN
--Select 3		
			SELECT @Rev_JRN = 1
			
			--Source_AS_Transactions_ID tested with positive and negative
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0

			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2
		END
		ELSE
		BEGIN
--Select 4
			IF @Payment_Amount <> (@Allocated_Amount * -1)
				SELECT @ReturnCode = 2
		END
	END
	ELSE 
	IF @Transactions_Type_ID = 7
	BEGIN
--Select 5
		SET @Allocated_Amount = 0
		
		--Destination_AS_Transactions_ID tested with a positive and negative amount
		--Source_AS_Transactions_ID tested with a positive amount
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
		AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
		IF ISNULL(@Allocated_Amount,0) = 0
		BEGIN
--Select 6		
			SELECT @Rev_JRN = 1
			
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		
			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2
		END
		ELSE
		BEGIN
--Select 7				
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
		END
	END
	ELSE 
	IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
	BEGIN
--Select 8
		--Destination_AS_Transactions_ID tested with a negative amount. No Positive amount
		--Source_AS_Transactions_ID not found
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
		AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
	END
	ELSE
	BEGIN
--Select 9
		--Scenario not tested
		SELECT @ReturnCode = 2
	END

	IF @ReturnCode = 0
	BEGIN
--Select 10
		IF @Transactions_Type_ID = 4
		BEGIN
--Select 11
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Amount
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END
		ELSE 
		IF @Transactions_Type_ID = 5
		BEGIN
--Select 12
			IF @Rev_JRN = 0
			BEGIN
--Select 13
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
			END
			ELSE
			BEGIN
--Select 14
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID			
				AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
			END
		END
		ELSE 
		IF @Transactions_Type_ID = 7
		BEGIN
--Select 15
			IF @Rev_JRN = 0
			BEGIN
--Select 16
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
			END
			ELSE
			BEGIN
--Select 17
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
			END
		END
		ELSE 
		IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
		BEGIN
--Select 18
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		END
		ELSE
		BEGIN
--Select 19
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		END
		
		OPEN GetData

		FETCH NEXT FROM GetData INTO @AS_Transactions_Transactions_ID, @Linked_AS_Transactions_ID, @Amount
		WHILE @@Fetch_Status = 0
		BEGIN
--Select 20
			SELECT @ReturnCode = 1
			
			IF @Transactions_Type_ID = 4
			BEGIN
--Select 21
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE 
			IF @Transactions_Type_ID = 5
			BEGIN
--Select 22
				IF @Rev_JRN = 0
				BEGIN
--Select 23
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @PaymentTranID
				
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
				END
				ELSE
				BEGIN
--Select 24
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @PaymentTranID

					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
				END
			END
			ELSE 
			IF @Transactions_Type_ID = 7
			BEGIN
--Select 25
				IF @Rev_JRN = 0
				BEGIN
--Select 26
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @PaymentTranID
				
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
				END
				ELSE
				BEGIN
--Select 27
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @PaymentTranID
				
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID				
				END
			END
			ELSE 
			IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
			BEGIN
--Select 28
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE
			BEGIN
--Select 29
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
--Select 30
			DELETE AS_Transactions_Transactions			
			WHERE AS_Transactions_Transactions_ID = @AS_Transactions_Transactions_ID	

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) = 0
				
			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @Linked_AS_Transactions_ID
			AND ISNULL(Destination_AS_Transactions_ID,0) = 0

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @Linked_AS_Transactions_ID

--Select 31
		
		FETCH NEXT FROM GetData INTO @AS_Transactions_Transactions_ID, @Linked_AS_Transactions_ID, @Amount
		END
		CLOSE GetData
		DEALLOCATE GetData
	END
--Select 32
	--When an allocation is done via the Unallocated Payments screen it adds a record to 
	--AS_Transactions_Transactions with a NULL Source_AS_Transactions_ID. Fuck knows why !!!


--	Exec sp_AS_Payment_Unallocate @PaymentTranID, @UserID, @CompanyID


	IF @ReturnCode = 1
	BEGIN
		DELETE AS_Transactions_Transactions
		WHERE ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
	END

--Transaction handled in code		
--IF @ReturnCode = 1
--	COMMIT TRAN Reverse_Payment
--ELSE
--	ROLLBACK TRAN Reverse_Payment

--1 Success
--0 Error
--2 Allocation Amount not same as payment Amount
SET NOCOUNT OFF
RETURN @ReturnCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_AS_Reverse_Payment_Component_Count
--Purpose       :Select COUNT of Customer Payment Source Transactions components
--Funtionality  :
--Date          :2005/06/07
--Authors       :TB
--MODS          :
--RL	V6.1	:2015-03-13 - Removed the check to see if payment has been allocated
--				 Why would you not be bale to reverse a payment that has not been allocated????
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Reverse_Payment_Component_Count]
    (
        @TranID int,
        @CompanyID int,
        @TranCount int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TranCount = 1

    --SELECT @TranCount = count(*)
    --FROM AS_Transactions_Transactions st
    --    LEFT JOIN AS_Transactions t
    --        ON st.Destination_AS_Transactions_ID = t.AS_Transactions_ID
    --    LEFT JOIN AC_Customers c
    --        ON t.AC_Customers_ID = c.AC_Customers_ID
    --    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
    --        ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    
    --WHERE st.AW_User_Companies_ID = @CompanyID AND
    --      st.Destination_AS_Transactions_ID = @TranID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_SO_Products_Select
--Purpose       :NEW POS Product Search (Normal) Results for 3 ARGUMENTS max
--Functionality :Uses:    vw_AS_POS_Products    -- now REDUNDANT
--              :         vw_AS_POS_Products_Top_20_Perc
--              :         vw_AS_POS_Products_Gross_Contribution
--Date          :2002/02/16
--Authors       :TB
--MODS          :26/07/02 - Changed Previous search to WILDCARD(*) search and
--              :20/08/02 - Added new Search String ARGUMENTS: '+', '-', and '#'
--              :           '+' = by MARGIN DESCENDING     (GP Value: High to Low) 
--              :           '-' = by MARGIN ASCENDING      (GP Value: Low to High)
--              :           '#' = by Unit Price ASCENDING  (Price: Cheap to Expensive)
--              :           '%' = by GP% DESCENDING        (GP%: High to Low)
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :28/05/03 - Changed SORT ORDER for NORMAL search from [Description]
--              :           to [Qty on Hand] DESC, [Description]
--              :15/11/03 - Added KEYWORDS field as a search filter
--              :28/02/04 - Added [GrossProfit] SORT ORDER for MARGIN sorts (+ & -)
--              :19/03/04 - Top 20% by GP% now returned using '%' instead of nullstring
--              :19/03/04 - Modified Product Search to return ZERO rows if nullstring
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS in remaining views and
--              :           2. eliminated using vw_AS_POS_Products (the default search)
--              :           3. by moving its code to the top if this SP
--              :26/07/07 - Added p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID]
--              :29/07/07 - Added p.Standard_Cost as [Std Cost]
--              :09/08/07 - Removed unused [Job_Reserved] field
--              :26/08/07 - Added p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem]
--2004.3.8      :10/05/08 - Removed JOIN with Lup_AP_Product_Departments and its
--              :           Min_GP_Percentage field and renamed the alias of the
--              :           Max_Discount_Perc to [MinGPPerc] and the alias of the
--              :           Slu_AW_YesNo_Max_Discount_Perc to [UseMinGPPerc] (new Profit Protector)
--2004.3.9      :05/06/08 - Converted [Qty on Hand] to decimal(9, 3) (Sales Order formatting)
--              :05/06/08 - Added p.Pack_Mass AS [Pack Mass] (Sales Orders)
--              :16/06/08 - Removed unused [Price], [Date], [UserID], [Tax Code]
--              :16/06/08 - Rename [OpenOrderQty] to [On Order]
--2004.4.2      :24/10/08 - Added new field [Standard Margin]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.4.8      :28/03/10 - Added WILDCARD Pattern Matching using _ (underscore) character
--              :           in Normal Search (@SearchType = 0) for the 3 @Filter(n)
--        ****  :02/09/10 - Added validation in WILDCARD search string: AND ISNUMERIC(@Filter1) > 0
--        ****  :02/09/10 - REMOVED WILDCARD search
--2004.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
--V6.3		RL	:2017-09-19 - Used sp_AS_POS_Products_Select as a template for sales order product search
-------------------------------------------------------------------------------

-- Exec sp_AS_SO_Products_Select 1, '1547800', '', ''

CREATE PROCEDURE [sp_AS_SO_Products_Select]
    (    
        @CompanyID int,
        @Filter1 varchar(50) = '',
        @Filter2 varchar(50) = '',
        @Filter3 varchar(50) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @SearchType tinyint

	IF @Filter3 <> ''
		BEGIN
			SET @Filter3 = '%' +  @Filter3 + '%'
			SET @Filter2 = '%' +  @Filter2 + '%'
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
						CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID))) as [Stock],
						p.On_Hand AS [Qty On Hand], 
						CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID)) as [Reserved],
						CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
						 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Pack Size],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItemID],
						yn2.Description AS [Non Stock Item],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Profit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCostID],
						yn1.Description AS [Sell Below Cost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Stock],			
			
						pb.Description AS [Bin],
						b.On_Hand as [Bin On Hand],
						pb.Lup_AP_Product_Bins_ID AS [Bin ID]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
				LEFT OUTER JOIN Slu_AW_YesNo yn1
					ON yn1.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Sell_Below_Cost
				LEFT OUTER JOIN Slu_AW_YesNo yn2
					ON yn2.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Non_Stock_Item
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  p.Description like @Filter2 AND
                  p.Description like @Filter3 ) OR 
                 (p.Product_Code like @Filter1 AND
                  p.Product_Code like @Filter2 AND
                  p.Product_Code like @Filter3) OR
                 (p.SKU_Code like @Filter1 AND
                  p.SKU_Code like @Filter2 AND
                  p.SKU_Code like @Filter3) OR
                 (p.Supercession like @Filter1 AND
                  p.Supercession like @Filter2 AND
                  p.Supercession like @Filter3) OR
                 (p.Alternate_Code1 like @Filter1 AND
                  p.Alternate_Code1 like @Filter2 AND
                  p.Alternate_Code1 like @Filter3) OR
                 (p.Alternate_Code2 like @Filter1 AND
                  p.Alternate_Code2 like @Filter2 AND
                  p.Alternate_Code2 like @Filter3) OR
                 (p.Keywords like @Filter1 AND
                  p.Keywords like @Filter2 AND
                  p.Keywords like @Filter3))
			ORDER By 4 Desc, b.On_Hand Desc
	END
	ELSE
	IF @Filter2 <> ''
		BEGIN
			SET @Filter2 = '%' +  @Filter2 + '%'
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
						CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Stock],
						p.On_Hand AS [Qty On Hand], 
						CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID)) as [Reserved],
						CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
						 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Pack Size],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItemID],
						yn2.Description AS [Non Stock Item],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Profit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCostID],
						yn1.Description AS [Sell Below Cost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Stock],			
			
						pb.Description AS [Bin],
						b.On_Hand as [Bin On Hand],
						pb.Lup_AP_Product_Bins_ID AS [Bin ID]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
				LEFT OUTER JOIN Slu_AW_YesNo yn1
					ON yn1.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Sell_Below_Cost
				LEFT OUTER JOIN Slu_AW_YesNo yn2
					ON yn2.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Non_Stock_Item
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  p.Description like @Filter2) OR 
                 (p.Product_Code like @Filter1 AND
                  p.Product_Code like @Filter2) OR
                 (p.SKU_Code like @Filter1 AND
                  p.SKU_Code like @Filter2) OR
                 (p.Supercession like @Filter1 AND
                  p.Supercession like @Filter2) OR
                 (p.Alternate_Code1 like @Filter1 AND
                  p.Alternate_Code1 like @Filter2) OR
                 (p.Alternate_Code2 like @Filter1 AND
                  p.Alternate_Code2 like @Filter2) OR
                 (p.Keywords like @Filter1 AND
                  p.Keywords like @Filter2))
			ORDER By 4 Desc, b.On_Hand Desc
	END
	ELSE

		IF @Filter1 <> ''
		BEGIN
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
						CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Stock],
						p.On_Hand AS [Qty On Hand], 
						CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID)) as [Reserved],
						CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
						 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Pack Size],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItemID],
						yn2.Description AS [Non Stock Item],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Profit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCostID],
						yn1.Description AS [Sell Below Cost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Stock],			
			
						pb.Description AS [Bin],
						b.On_Hand as [Bin On Hand],
						pb.Lup_AP_Product_Bins_ID AS [Bin ID]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
				LEFT OUTER JOIN Slu_AW_YesNo yn1
					ON yn1.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Sell_Below_Cost
				LEFT OUTER JOIN Slu_AW_YesNo yn2
					ON yn2.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Non_Stock_Item
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1) OR 
                 (p.Product_Code like @Filter1) OR
                 (p.SKU_Code like @Filter1) OR
                 (p.Supercession like @Filter1) OR
                 (p.Alternate_Code1 like @Filter1) OR
                 (p.Alternate_Code2 like @Filter1) OR
                 (p.Keywords like @Filter1))
			ORDER By 4 Desc, b.On_Hand Desc
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-----------------------------------------------------------------------------
--Description   : sp_AS_Sales_Analyst_TranDetails
--Purpose       : Retrieves selected Category Grid Data
--              : for whole Category from AS_Transactions
--              :     for SalesAnalyst
--Parameters    :
--Date          : 28 MAY 2002
--Authors       : TB
--Version       : 1.0.0
-----------------------------------------------------------------------------
CREATE    PROCEDURE  sp_AS_Sales_Analyst_TranDetails
	(
		@ASTransactionsID int
	)

AS

SET NOCOUNT ON

    SELECT
        ISNULL(p.[Description], '') AS [Product], 
        ISNULL(p.Product_Code, '') AS [Code], 
        ISNULL(d.Quantity, 0) AS [Qty], 
        ISNULL(d.Unit_Cost, 0) AS [Cost], 
        ISNULL(d.Unit_Price, 0) AS [Price], 
        ISNULL(d.Original_Price, 0) AS [Original Price], 
        ISNULL(d.Original_Discount, 0) AS [Original Discount], 
        ISNULL(d.Discount_Amount, 0) AS [Discount], 
        ISNULL(d.Tax_Amount, 0) AS [Tax], 
        ISNULL(d.Extended_Amount, 0) AS [Amount], 
--        ISNULL(d.Commission_Amount, 0) AS [Commission], 
--        d.AP_Products_ID AS [ProductID], 
--        d.AS_Transactions_ID AS [TransactionID], 
        d.AS_Transaction_Details_ID AS [ID]
    FROM AS_Transaction_Details d
        LEFT OUTER JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AS_Transactions_ID = @ASTransactionsID

SET NOCOUNT ON








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--*** NOT USED ***
-----------------------------------------------------------------------------
--Description   : sp_AS_Sales_Analyst_TranHeaders
--Purpose       : Retrieves selected Category Grid Data
--              : for whole Category from AS_Transactions
--              :     for SalesAnalyst
--Parameters    :
--Date          : 28 MAY 2002
--Authors       : TB
--Version       : 1.0.0
-----------------------------------------------------------------------------

CREATE         PROCEDURE sp_AS_Sales_Analyst_TranHeaders
	(
		@CompanyID int
	)

AS

SET NOCOUNT ON

	SELECT     
		h.Transaction_Date as [Date],
		ISNULL(h.Amount, 0) as [Amount], 
		ISNULL(h.Total_Cost, 0) as [Cost], 
        ISNULL(h.Total_Tax_Amount, 0) as [Tax], 
		ISNULL(h.Total_Discount_Amount, 0) as [Discount], 
		ISNULL(h.Total_Amount, 0) as [Total], 
		ISNULL(h.Payment_Amount, 0) as [Payment], 
		ISNULL(h.Transaction_Number,'') as [No], 
--		tt.[Description] AS [Type],
-- 		tills.[Description] AS [Till], 
-- 		cashiers.[Description] AS [Cashier], 
-- 		reps.[Description] AS [Rep], 
 		ISNULL(c.Surname, '') + isnull(', ' + c.Firstnames, '') as [Customer],		
-- 		h.Cashed_Up as [CashUp], 
-- 		h.Day_End as [DayEnd], 
-- 		h.Customer_Reference as [Ref], 
--      h.Expiry_Date as [Expires],
-- 		com.Comment as [Comment],
        u.UserName as [User],
--The following are not displayed
		h.AW_User_Companies_ID as [CompanyID],
--      h.Lup_AS_Cashiers_ID as [CashierID], 
        h.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
-- 		h.Lup_AS_Tills_ID AS [TillID], 
-- 		h.Lup_AS_Reps_ID as [RepID], 
-- 		c.AC_Customers_ID as [CustomerID],
		h.AS_Transactions_ID AS [ID]
	FROM         
		AS_Transactions h
			LEFT JOIN AC_Customers c
                ON h.AC_Customers_ID = c.AC_Customers_ID 
-- 			LEFT JOIN fn_AW_Comments(-7) com
--                 ON h.AW_Comments_ID = com.ID
-- 			LEFT JOIN Sys_AW_Transaction_Types tt
--                 ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
-- 			LEFT JOIN Lup_AS_Tills tills
--                 ON h.Lup_AS_Tills_ID = tills.Lup_AS_Tills_ID 
-- 			LEFT JOIN Lup_AS_Cashiers cashiers
--                 ON h.Lup_AS_Cashiers_ID = cashiers.Lup_AS_Cashiers_ID 
-- 			LEFT JOIN Lup_AS_Reps reps
--                 ON h.Lup_AS_Reps_ID = reps.Lup_AS_Reps_ID
			LEFT JOIN AW_Users u
                ON h.[User_ID] = u.AW_Users_ID
	WHERE h.AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Sales_Order_No_CHK
--Purpose       :Check to see if Sales Order Number already exists in Sales Order basket
--				 or on an open Sales Order document (SYS_AW_Transaction_Types = 16)
--Date          :2017/04/20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Sales_Order_No_CHK]
    (
        @CustomerID int,
        @Customer_Reference	varchar(15),
        @AP_Products_ID	int,
		@Lup_AP_Product_Bins_ID int,
        @Sales_Basket int, --1 Sales basket, 2 Sales Order
       	@CompanyID int,
       	@CHK_Message	varchar(200) OUTPUT,
       	@ExistingTransID	int OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE @Count			int
    
    SET @Count = 0
    SET @CHK_Message = ''
    
    IF @Sales_Basket = 1
    BEGIN
		SELECT @Count = COUNT(*)
		FROM AS_Sales_Order_Details
		WHERE AC_Customers_ID = @CustomerID AND
			Customer_Reference = @Customer_Reference AND
			AP_Products_ID = @AP_Products_ID AND
			AW_User_Companies_ID = @CompanyID AND
			Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID

		IF @Count > 0
			SELECT @CHK_Message = 'Sales order number exists in sales basket for THIS PRODUCT.
Item will be added to existing item in the basket.
Do you want to continue?'

		SET @Count = 0

		IF @CHK_Message = ''
		BEGIN
			SELECT @Count = COUNT(*)
			FROM AS_Sales_Order_Details
			WHERE AC_Customers_ID = @CustomerID AND
				Customer_Reference = @Customer_Reference AND
				AW_User_Companies_ID = @CompanyID AND
				Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID
			
			IF @Count > 0
				SELECT @CHK_Message = 'Sales order number exists in sales basket.
Items will be combined with the same order number.
Do you want to continue?'			
		END
	END	
	
	IF @Sales_Basket = 2
	BEGIN
		SET @ExistingTransID = 0

		SELECT @ExistingTransID = AS_Transactions_ID
		FROM AS_Transactions
		WHERE AC_Customers_ID = @CustomerID
		AND Customer_Reference = @Customer_Reference
		AND Slu_AW_Active_ID = 1
		AND AW_User_Companies_ID = @CompanyID
		
		IF @ExistingTransID > 0
			SELECT @CHK_Message = 'An active sales order exists for this customer.
Items will be combined with the existing sales order.
Do you want to continue?'			

	END
SELECT @CHK_Message As '@CHK_Message', @ExistingTransID As '@ExistingTransID'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Sales_Order_No_Stock_CHK
--Purpose       :Check to see if there is stock available on a product before createing sales order
--Date          :2017/09/20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Sales_Order_No_Stock_CHK]
    (
        @AP_Products_ID	int,
		@Basket_ID	int,
		@Lup_AP_Product_Bins_ID int,
       	@Qty_Available	decimal(18,3) OUTPUT
    )
AS

SET NOCOUNT ON

	DECLARE @Count			int,
			@BO_Qty			decimal(18,3),
			@SO_Qty			decimal(18,3)
   
   
--	SELECT @Qty_Available = CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)))
--  FROM AP_Products p
--	WHERE AP_Products_ID = @AP_Products_ID

	SELECT @Qty_Available = CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved_Bin(p.AP_Products_ID,p.Lup_AP_Product_Bins_ID)))
	FROM AP_Products_Bins p
	WHERE AP_Products_ID = @AP_Products_ID AND
		Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID

	IF @Qty_Available > 0
	BEGIN
		SELECT  @BO_Qty = Back_Order,
				@SO_Qty = Quantity
		FROM AS_Sales_Order_Details
		WHERE AS_Sales_Order_Details_ID = @Basket_ID

		IF (@Qty_Available - @SO_Qty) >= @BO_Qty
		BEGIN
			UPDATE AS_Sales_Order_Details
				SET Quantity = Quantity + @BO_Qty,
					Back_Order = 0
			WHERE AS_Sales_Order_Details_ID = @Basket_ID
		END
		ELSE
		BEGIN

			UPDATE AS_Sales_Order_Details
				SET Quantity = Quantity + (@Qty_Available - @SO_Qty),
					Back_Order = @BO_Qty - (@Qty_Available - @SO_Qty)
			WHERE AS_Sales_Order_Details_ID = @Basket_ID
		END
	END


	SELECT @Qty_Available As '@Qty_Available'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Customer_Asset_Hist
--Purpose       :Get Distinct Customer Asset Details
--Parameters    :
--Date          :2014-10-29
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Customer_Asset_Hist]
(
	@AC_Customers_ID	Int
)
AS

SET NOCOUNT ON

	SELECT DISTINCT               
                Make,
                Model,
                Model_Year,                
                t.[Description] AS [Asset_Type],
                Reg_No,
                Engine_No,
                Chassis_No,
                VIN_No,
                --Mileage,
                --Mileage_Date,
                Tyre_Size,
                --Tyre_Qty,
                a.Lup_AC_Asset_Types_ID
	FROM AC_Assets a
		LEFT JOIN Lup_AC_Asset_Types t
			ON a.Lup_AC_Asset_Types_ID = t.Lup_AC_Asset_Types_ID               
	WHERE AC_Customers_ID = @AC_Customers_ID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AS_Select_Sales_Order_Details
--Purpose       :
--Date          :07 JUN 2008
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Customer_Sales_Order_Details]
    (
        @CustomerID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

   SELECT 
        s.AS_Sales_Order_Details_ID AS [ID],
        s.AC_Customers_ID AS [CustomerID],
        s.AP_Products_ID AS [ProductID],
        s.[Description] AS [Product],
        s.Product_Code AS [Code],
        s.Customer_Reference As [Order No],
		b.[Description] AS [Bin],
        s.Unit_Price AS [Unit Price],
        s.Quantity AS [Qty],
        s.Back_Order AS [B/O],
        s.Discount_Amount AS [Discount],
        s.Amount AS [Amount],
        s.Shipping_Cost AS [Shipping],
        s.Tax_Amount AS [Tax],
        s.Extended_Amount AS [Total],
        s.Tax_Rate AS [Tax Rate],
        s.Original_Price AS [Orig Price],
        s.Unit_Cost AS [UnitCost],
        s.AP_Promotion_Products_ID AS [PromoProdID],
        s.Promo_Price AS [Promo Price],
        s.Date_Captured AS [Captured],
        s.User_ID AS [UserID],
        s.AW_User_Companies_ID AS [CompanyID],
		s.Lup_AP_Product_Bins_ID AS [Bins_ID]

	FROM AS_Sales_Order_Details s
		INNER JOIN Lup_AP_Product_Bins b
			ON s.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
	WHERE s.AW_User_Companies_ID = @CompanyID AND
          s.AC_Customers_ID = @CustomerID
    ORDER BY s.Date_Captured DESC 

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Delivery_Address_Hist
--Purpose       :Select address details used by customer
--Functionality :Select address details used by customer
--Date          :2013-01-02
--Authors       :RL
--V6.3	RL	2017-03-07	:Select Record per transaction
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Select_Delivery_Address_Hist]
    (    	    	
    	@AC_Customers_ID int
    )
AS 

	DECLARE @sql varchar(8000)
		
	SET @sql = ' ' 
	SET @sql = @sql + ' DECLARE @WhichAddress tinyint, '
	SET @sql = @sql + ' @WhichName tinyint '

	SET @sql = @sql + ' SET @WhichAddress = 0 '

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SET @sql = @sql + ' SELECT @WhichAddress = ISNULL(Control_Index, 0) '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Type = ''OptionButton'' AND '
	SET @sql = @sql + ' Control_Name = ''optPOSPrintAddress'' AND '
	SET @sql = @sql + ' Control_Value = ''True'' '

	SET @sql = @sql + ' SELECT TOP 1 @WhichName = ISNULL(Control_Value, ''0'') '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Index = 0 AND '
	SET @sql = @sql + ' Control_Type = ''CheckBox'' AND '
	SET @sql = @sql + ' Control_Name = ''chkPOSPrintTradeName'' '


	SET @sql = @sql + ' SELECT '
	SET @sql = @sql + ' 	ISNULL(ad.Customer_Name,'''') AS [Customer_Name], '
	SET @sql = @sql + ' 	tt.[Description] As [Tran_Type], '
	SET @sql = @sql + ' 	th.Transaction_Date AS [Transaction_Date], '
	SET @sql = @sql + ' 	th.Transaction_Number As [Transaction_Number], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_Address1,'''') AS [Inv_Address1], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_Address2,'''') AS [Inv_Address2], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_City,'''') AS [Inv_City], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_Code,'''') AS [Inv_Code], '
	SET @sql = @sql + ' 	ISNULL(ad.Tax_Number,'''') AS [Tax_Number], '
	--V6.4 Added Cell no and email
	SET @sql = @sql + '		ISNULL(ad.Cell_No,'''') AS [Cell_No], '
	SET @sql = @sql + '		ISNULL(ad.Email,'''') AS [Email], '	
	
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_Address,'''') AS [Delivery_Address], '
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_Suburb,'''') AS [Delivery_Suburb], '
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_City,'''') AS [Delivery_City], '
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_Post_Code,'''') AS [Delivery_Post_Code], '
	SET @sql = @sql + ' 	ad.AS_Transactions_Address_Detail_ID As [ID], '
	SET @sql = @sql + ' 	th.AS_Transactions_ID As [AS_Transactions_ID] '	
	SET @sql = @sql + ' FROM AS_Transactions_Address_Detail	ad '
	SET @sql = @sql + ' 	INNER JOIN AS_Transactions_Address ah '
	SET @sql = @sql + ' 		ON ad.AS_Transactions_Address_Detail_ID = ah.AS_Transactions_Address_Detail_ID '
	SET @sql = @sql + ' 	INNER JOIN AS_Transactions th '
	SET @sql = @sql + ' 		ON ah.AS_Transactions_ID = th.AS_Transactions_ID '
	SET @sql = @sql + ' 	INNER JOIN Sys_AW_Transaction_Types tt '
	SET @sql = @sql + ' 		on th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' WHERE ad.AC_Customers_ID = ' + CONVERT(varchar(20), @AC_Customers_ID)
	SET @sql = @sql + ' AND th.Sys_AW_Transaction_Types_ID IN (1, 2, 3, 4, 7, 13, 16, 17, 21, 22, 33, 34, 35) '
	SET @sql = @sql + ' UNION '
	SET @sql = @sql + ' SELECT '
		
	SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + ' 	CASE WHEN ISNULL(cc.Initials,'''') = '''' '
	SET @sql = @sql + ' 	THEN '
	SET @sql = @sql + ' 		CASE WHEN ISNULL(cc.Firstnames,'''') = '''' '
	SET @sql = @sql + ' 		THEN LTRIM(RTRIM(cc.Surname)) '
	SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(cc.Surname)) + '' / '' + LTRIM(RTRIM(cc.Firstnames)) '
	SET @sql = @sql + ' 		END '
	SET @sql = @sql + ' 	ELSE '
	SET @sql = @sql + ' 		CASE WHEN ISNULL(cc.Firstnames,'''') = '''' '
	SET @sql = @sql + ' 		THEN LTRIM(RTRIM(cc.Surname)) + '', '' + LTRIM(RTRIM(cc.Initials)) '
	SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(cc.Surname)) + '', '' + LTRIM(RTRIM(cc.Initials)) + '' / '' + LTRIM(RTRIM(cc.Firstnames)) '
	SET @sql = @sql + ' 		END '
	SET @sql = @sql + ' 	END '
	SET @sql = @sql + ' ELSE '
	SET @sql = @sql + ' 	CASE WHEN ISNULL(cc.Initials,'''') = '''' '
	SET @sql = @sql + ' 		THEN LTRIM(RTRIM(cc.Surname)) '
	SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(cc.Surname)) + '', '' + LTRIM(RTRIM(cc.Initials)) '
	SET @sql = @sql + ' 	END '
	SET @sql = @sql + ' END AS [Customer_Name], '
		
	SET @sql = @sql + '		tt.[Description] As [Tran_Type], '
	SET @sql = @sql + '		th.Transaction_Date AS [Transaction_Date], '
	SET @sql = @sql + '		th.Transaction_Number As [Transaction_Number], '
	
	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.Post_Box, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.Street_Address, '''') '
	SET @sql = @sql + ' END AS [Inv_Address1], '

	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.Post_Office, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.Suburb, '''') '
	SET @sql = @sql + ' END AS [Inv_Address2], '

	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.City, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.City, '''') '
	SET @sql = @sql + ' END AS [Inv_City], '

	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.Post_Code, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.Street_Post_Code, '''') '
	SET @sql = @sql + ' END AS [Inv_Code], '
		
	SET @sql = @sql + '		ISNULL(cc.Tax_Number,'''') AS [Tax_Number], '
	--V6.4 Added Cell no and email
	SET @sql = @sql + '		ISNULL(cc.Cell_No,'''') AS [Cell_No], '
	SET @sql = @sql + '		ISNULL(cc.Orders_URL,'''') AS [Email], '	
	
	SET @sql = @sql + '		ISNULL(cc.Delivery_Address,'''') AS [Delivery_Address], '
	SET @sql = @sql + '		ISNULL(cc.Delivery_Suburb,'''') AS [Delivery_Suburb], '
	SET @sql = @sql + '		ISNULL(cc.Delivery_City,'''') AS [Delivery_City], '
	SET @sql = @sql + '		ISNULL(cc.Delivery_Post_Code,'''') AS [Delivery_Post_Code], '
	SET @sql = @sql + '		0 As [ID], '
	SET @sql = @sql + ' 	th.AS_Transactions_ID As [AS_Transactions_ID] '		
	SET @sql = @sql + ' FROM AS_Transactions th '
	SET @sql = @sql + ' 	INNER JOIN AC_Customers cc '
	SET @sql = @sql + ' 		ON th.AC_Customers_ID = cc.AC_Customers_ID '
	SET @sql = @sql + ' 	INNER JOIN Sys_AW_Transaction_Types tt '
	SET @sql = @sql + ' 		on th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' WHERE th.AC_Customers_ID = ' + CONVERT(varchar(20), @AC_Customers_ID)
	SET @sql = @sql + ' AND th.Sys_AW_Transaction_Types_ID IN (1, 2, 3, 4, 7, 13, 16, 17, 21, 22, 33, 34, 35) '
	SET @sql = @sql + ' AND th.AS_Transactions_ID NOT IN '
	SET @sql = @sql + ' 							( '
	SET @sql = @sql + ' 								SELECT AS_Transactions_ID '
	SET @sql = @sql + ' 								FROM AS_Transactions_Address '
	SET @sql = @sql + ' 							) '
	SET @sql = @sql + ' ORDER BY Transaction_Date DESC, Transaction_Number '

EXEC (@sql)
--Select @sql

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Email_Marketing_Customers
--Purpose       :Retrieves Search Filter Customers
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2004/07/05
--Authors       :TB
--MODS          :
--2004.2.7      :19/03/06 - Added option 14 - Account Status
--              :29/03/06 - Added option 15 - Customer with sales between dates
--V6.4	RL	2018-03-27	:Link to AS_Transactions_Address_Detail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Email_Marketing_Customers]
    (
        @CompanyID int, 
        @Option int,
        @FetchChoice int,
        @Value int,
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON

-- Exec sp_AS_Select_Email_Marketing_Customers 1, 16, 1, 500, '2017-01-01', '2018-03-31'

TRUNCATE TABLE [AS_Email_Marketing];

-->ALL Customers
    IF @Option = 0
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
	END
    ELSE
-->All Customers with Sales
    IF @Option = 1
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID IN
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AS_Transactions
										WHERE Transaction_Date >= @StartDate AND
												Transaction_Date <= @EndDate AND
												(Sys_AW_Transaction_Types_ID = 3 OR
												 Sys_AW_Transaction_Types_ID = 4)
									)                                    

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->All Customers with No Sales
    IF @Option = 2
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])    
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID NOT IN
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID NOT IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AS_Transactions
										WHERE Transaction_Date >= @StartDate AND
												Transaction_Date <= @EndDate AND
												(Sys_AW_Transaction_Types_ID = 3 OR
												 Sys_AW_Transaction_Types_ID = 4)
									)                                                  

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
	END        
    ELSE
-->TOP 20%
    IF @Option = 3
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT  a.[CustomerID],
                a.[Send E-Mail],
                a.[Customer],
                a.[Number],
                a.[Contact E-mail],
                a.[Contact Cell],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code]
        FROM dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	Distinct
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT a.[CustomerID]
										FROM dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
									)                              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->NEXT 30%
    IF @Option = 4
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT  a.[CustomerID],
                a.[Send E-Mail],
                a.[Customer],
                a.[Number],
                a.[Contact E-mail],
                a.[Contact Cell],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code]
        FROM dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.CustomerID = b.CustomerID
        WHERE b.CustomerID IS NULL

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT a.[CustomerID]
										FROM dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
											LEFT JOIN dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
												ON a.CustomerID = b.CustomerID
										WHERE b.CustomerID IS NULL
									)                              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->LAST 50%
    IF @Option = 5
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT  a.[CustomerID],
                a.[Send E-Mail],
                a.[Customer],
                a.[Number],
                a.[Contact E-mail],
                a.[Contact Cell],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code]
        FROM dbo.fn_AS_Top100Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.CustomerID = b.CustomerID
        WHERE b.CustomerID IS NULL

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT a.[CustomerID]
										FROM dbo.fn_AS_Top100Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
											LEFT JOIN dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
												ON a.CustomerID = b.CustomerID
										WHERE b.CustomerID IS NULL
									)                      

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Salesperson
    IF @Option = 6
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AS_Reps_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AS_Reps_ID = @Value
									)              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Sales Area
    IF @Option = 7
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Sales_Areas_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Sales_Areas_ID = @Value 
									)

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Language
    IF @Option = 8
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Languages_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Slu_AW_Languages_ID = @Value 
									)                                                                                    

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Customer Type
    IF @Option = 9
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Customer_Types_ID = @Value 
									)                                                                      

		SELECT	DISTINCT	
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Credit Terms
    IF @Option = 10
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Credit_Terms_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Slu_AW_Credit_Terms_ID = @Value 
									)                                                        

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Discount Category
    IF @Option = 11
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Discount_Categories_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Discount_Categories_ID = @Value
									)                                          

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Customer Group
    IF @Option = 12
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Groups_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Customer_Groups_ID = @Value 
									)                            

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Account Type
    IF @Option = 13
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Sys_AC_Account_Types_ID = @Value
									)              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Account Status
    IF @Option = 14
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Status_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Sys_AC_Account_Status_ID = @Value 
									)

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->New Customers (Start Date)
    IF @Option = 15
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Start_Date >= @StartDate AND
              c.Start_Date <= @EndDate AND
              c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Start_Date >= @StartDate AND
												Start_Date <= @EndDate
									)

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Customer Sales
    IF @Option = 16
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       Sys_AW_Transaction_Types_ID = 3) 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AS_Transactions
										WHERE Transaction_Date >= @StartDate AND
											  Transaction_Date <= @EndDate AND
											  Sys_AW_Transaction_Types_ID = 3
									)
    
		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
	END
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--------------------------------------------------------------------------------
--Description   :sp_AS_Select_Email_Marketing_Lups
--Purpose       :E-Mail Marketing Lookups
--Date          :2004/07/05
--Authors       :TB
--MODS          :19/03/06 - Added @Option 11 - SMS Messages
--2004.2.7      :29/03/06 - Added @Option 12 - Account Status
--------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AS_Select_Email_Marketing_Lups
    (
       	@Option int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    IF @Option = 1	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],
               [Description] AS [Yes_No]  	
        FROM Slu_AW_YesNo

    ELSE
    IF @Option = 2	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID],
               [Description] AS [Active] 
        FROM Slu_AW_Active 

    ELSE
    IF @Option = 3 --'Language'
        SELECT Slu_AW_Languages_ID AS [ID], Description AS [Language]
        FROM Slu_AW_Languages

    ELSE
    IF @Option = 4 --'Type'
        SELECT Lup_AC_Customer_Types_ID AS [ID], Description AS [Customer Type]
        FROM Lup_AC_Customer_Types
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 5 --'Discount Category'
        SELECT Lup_AC_Discount_Categories_ID AS [ID], Description AS [Discount Category]
        FROM Lup_AC_Discount_Categories
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 6 --'Credit Terms'
        SELECT Slu_AW_Credit_Terms_ID AS [ID], Description AS [Credit Terms]
        FROM Slu_AW_Credit_Terms

    ELSE
    IF @Option = 7 --'Salesperson'
        SELECT Lup_AS_Reps_ID AS [ID], Description AS [Salesperson]
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 8 --'Sales Area'
        SELECT Lup_AC_Sales_Areas_ID AS [ID], Description AS [Sales Area]
        FROM Lup_AC_Sales_Areas
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 9 --'Customer Group'
        SELECT Lup_AC_Customer_Groups_ID AS [ID], Description AS [Customer Group]
        FROM Lup_AC_Customer_Groups
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 10 --'Account Type'
        SELECT Sys_AC_Account_Types_ID AS [ID], Description AS [Account Type]
        FROM Sys_AC_Account_Types

    ELSE
    IF @Option = 11 --'SMS Messages
        SELECT Slu_AW_SMS_Messages_ID AS [ID],
              [English] AS [English],
              [Afrikaans] as [Afrikaans]
        FROM Slu_AW_SMS_Messages

    ELSE
    IF @Option = 12 --'Account Status'
        SELECT Sys_AC_Account_Status_ID AS [ID], Description AS [Account Status]
        FROM Sys_AC_Account_Status


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-----------------------------------------------------------------------------------
--Description   :sp_AS_Select_Email_Marketing_Product_Customers
--Purpose       :Retrieves the Customers of a Product
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2004/07/06
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Select_Email_Marketing_Product_Customers
    (
        @ProductID int,
        @StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

    SELECT DISTINCT c.AC_Customers_ID AS [CustomerID], 
                    c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
                    LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                             THEN ISNULL(Surname, '')
                             ELSE ISNULL(Surname, '') + ', ' + 
                                  LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                        ISNULL(t.Description, '') + ' ' +
                                        ISNULL(Initials, ''))
                        END, 50) AS [Customer],
                    c.Customer_Number AS [Number],
                    c.Home_Email AS [Contact E-mail],
                    c.Cell_No AS [Contact Cell], 
                    c.Post_Box AS [Post Box],
                    c.Post_Office AS [Post Office],
                    c.Post_Code AS [Post Code]
    FROM AS_Transaction_Details d
        INNER JOIN AS_Transactions h
            ON h.AS_Transactions_ID = d.AS_Transactions_ID
        INNER JOIN AC_Customers c
            ON h.AC_Customers_ID = c.AC_Customers_ID
        INNER JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
    WHERE c.AC_Customers_ID in
            (SELECT distinct AC_Customers_ID
             FROM AS_Transactions
             WHERE d.AP_Products_ID = @ProductID AND
                   h.Transaction_Date >= @StartDate AND
                   h.Transaction_Date <= @EndDate AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4))
    ORDER BY [Customer]


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















----------------------------------------------------------------------------
--Description   :sp_AS_Select_Email_Marketing_Products
--Functionality :Returns products matching search criteria in E-mail Marketing
--Date          :2004/07/06
--Authors       :TB
--MODS          :16/03/06 - Added @Startdate and @EndDate input parameters
--              :           and filter Products.Last_Sale_Date between dates
--2004.4.3      :17/03/09 - Removed AP_Products.Last_Sale_Date validation
--              :           Last_Sale_Date gets REPLACED with THE LATEST Invoice date which
--              :           causes Product Search with OLDER From/To dates returning NOTHING
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Select_Email_Marketing_Products
    (
        @CompanyID int,
        @Criteria1 varchar(100) = '',
        @Criteria2 varchar(100) = '',
        @Criteria3 varchar(100) = '',
        @Startdate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

   DECLARE
        @Criteria varchar(8000), 
        @SQL varchar(8000)

   SET @Criteria = ''
	
   IF @CompanyID > -1   
      BEGIN
         IF @Criteria = '' 
            SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
         ELSE
            SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
      END

   IF @Criteria3 <> '' and @criteria2 <> '' and @criteria1 <> ''
      BEGIN
        IF @Criteria = '' 
           SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                   (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
        ELSE
            SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                              (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria2 <> '' and @criteria1 <> '' 
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
										(p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                                   (p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria1 <> ''   
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END


--     SET @Criteria = @Criteria + ' AND p.Last_Sale_Date >= ''' + CONVERT(varchar(30), @Startdate) + ''''
--     SET @Criteria = @Criteria + ' AND p.Last_Sale_Date <= ''' + CONVERT(varchar(30), @Enddate) + ''''


    SET @SQL = ' SELECT '
    SET @SQL = @SQL + '    p.AP_Products_ID as [ProductID], '
    SET @SQL = @SQL + '    p.Description as [Product], ' 
    SET @SQL = @SQL + '    p.Product_Code as [Code], '  
    SET @SQL = @SQL + '    p.On_Hand as [On Hand], '
    SET @SQL = @SQL + '    p.Pack_Size AS [Pack], '
    SET @SQL = @SQL + '    pt.Description AS [Type], '
    SET @SQL = @SQL + '    pg.Description AS [Group], '
    SET @SQL = @SQL + '    pd.Description AS [Department] '
--    SET @SQL = @SQL + '    p.Last_Sale_Date AS [Last Sale]  '
    SET @SQL = @SQL + ' FROM AP_Products p   '
    SET @SQL = @SQL + '     LEFT OUTER JOIN Lup_AP_Product_Departments pd '
    SET @SQL = @SQL + '         ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID  '
    SET @SQL = @SQL + '     LEFT OUTER JOIN Lup_AP_Product_Types pt '
    SET @SQL = @SQL + '         ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID  '
    SET @SQL = @SQL + '     LEFT OUTER JOIN Lup_AP_Product_Groups pg '
    SET @SQL = @SQL + '         ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID  '


    SET @SQL = @SQL + @Criteria + ' '

    SET @SQL = @SQL + ' ORDER BY p.Description '


    EXEC (@SQL)



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Email_Marketing_Prospects
--Purpose       :Retrieves Search Filter Prospects
--Date          :2006/03/29
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Select_Email_Marketing_Prospects
    (
        @CompanyID int, 
        @Option int,
        @FetchChoice int,
        @Value int,
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON

-->ALL Prospects
    IF @Option = 0
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]


    ELSE
-->Salesperson
    IF @Option = 6
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AS_Reps_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Sales Area
    IF @Option = 7
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Sales_Areas_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Language
    IF @Option = 8
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Languages_ID = @Value  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Type
    IF @Option = 9        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Credit Terms
    IF @Option = 10
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Credit_Terms_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Discount Category
    IF @Option = 11
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Discount_Categories_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Group
    IF @Option = 12        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Groups_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Account Type
    IF @Option = 13        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Types_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]


    ELSE
-->Account Status
    IF @Option = 14        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Status_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->New Customers (Start Date)
    IF @Option = 15        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Start_Date >= @StartDate AND
              c.Start_Date <= @EndDate AND
              c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]





SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Select_FirstLast_CBilling_Transaction_Date
--Purpose       :Select FIRST or LAST CBilling Transaction Date
--Functionality :
--Date          :2006/03/07
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Select_FirstLast_CBilling_Transaction_Date
	(
    	@CompanyID int,
        @Option tinyint,
        @TranDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

--> Get the FIRST CBilling Transaction Date
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions_CBilling
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Transaction_Date ASC
        END

    ELSE

--> Get the LAST CBilling Transaction Date
    IF @Option = 1
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions_CBilling
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Transaction_Date DESC
        END

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AS_Select_FirstLast_Transaction_Date
--Purpose       :Select FIRST or LAST Customer Sale Date
--Functionality :Fetch First/Last Invoice/Credit date
--Date          :2007/01/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Select_FirstLast_Sale_Date
	(
    	@CompanyID int,
        @Option tinyint,
        @TranDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

--> Get the FIRST Sale Date
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund
            ORDER BY Transaction_Date ASC
        END

    ELSE

--> Get the LAST Sale Date
    IF @Option = 1
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund
            ORDER BY Transaction_Date DESC
        END

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Select_FirstLast_Transaction_Date
--Purpose       :Select FIRST or LAST Customer Transaction Date
--Date          :2003/11/22
--Authors       :TB
--MODS          :
--2004.3.2      :15/09/06 - Added filter FINANCIAL transactions only
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Select_FirstLast_Transaction_Date
	(
    	@CompanyID int,
        @Option tinyint,
        @TranDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

--> Get the FIRST Customer Transaction Date
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
            ORDER BY Transaction_Date ASC
        END

    ELSE

--> Get the LAST Customer Transaction Date
    IF @Option = 1
        BEGIN
            SELECT TOP 1 @TranDate = Transaction_Date
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
            ORDER BY Transaction_Date DESC
        END

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Select_IsLevyController
--Purpose       :Select if User is a Levy Controller
--Date          :2016-12-19
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Select_IsLevyController]
    (
        @UserID int,
        @IsLevyController tinyint OUTPUT
    )

AS

SET NOCOUNT ON

    SET @IsLevyController = 0

    SELECT @IsLevyController = IsLevyController
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @IsLevyController IS NULL 
        BEGIN	
    		SET @IsLevyController = 0 
        END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AS_Select_IsRecordsManager
--Purpose       :Select if User is a Records Manager
--Date          :2013-07-14
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Select_IsRecordsManager]
    (
        @UserID int,
        @IsRecordsManager tinyint OUTPUT
    )

AS

SET NOCOUNT ON


    SET @IsRecordsManager = 0

    SELECT @IsRecordsManager = IsRecordsManager
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @IsRecordsManager IS NULL 
        BEGIN	
    		SET @IsRecordsManager = 0 
        END

SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Mail_Merge_Customers
--Purpose       :Retrieves Search Filter Customers
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2007/12/05
--Authors       :TB
--MODS          :
--2004.4.5      :10/07/09 - Added Delivery Address and Head Office fields
-------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AS_Select_Mail_Merge_Customers
    (
        @CompanyID int, 
        @Option int,
        @FetchChoice int,
        @Value int,
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON

    DECLARE @Midnight datetime,
            @Now datetime,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime


    SET @Now = getdate()
    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Now), 0, 1)))


    EXEC sp_AW_Period_Procedures_Select
            @Now,
            @D1 OUTPUT,
            @D2 OUTPUT,
            @D3 OUTPUT,
            @D4 OUTPUT,
            @D5 OUTPUT,
            @D6 OUTPUT,
            @D7 OUTPUT,
            1,
            @CompanyID


-->ALL Customers
    IF @Option = 0
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->All Customers with Sales
    IF @Option = 1
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.AC_Customers_ID IN
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->All Customers with No Sales
    IF @Option = 2
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.AC_Customers_ID NOT IN
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->TOP 20%
    IF @Option = 3
        SELECT  a.[CustomerID],
                a.[Selected],
                a.[Customer],
                a.[Number],
                a.[Fax Number],
                a.[Contact E-mail],
                a.[Contact],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code],
                a.[Street Address],
                a.[Suburb],
                a.[City],
                a.[Street Code],
                a.[Delivery Address],
                a.[Delivery Suburb],
                a.[Delivery City],
                a.[Delivery Code],
                a.[Head Office]
        FROM dbo.fn_AS_Top20Perc_Customers_GP_Mail_Merge(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
        ORDER BY a.[Customer]

    ELSE
-->NEXT 30%
    IF @Option = 4
        SELECT  a.[CustomerID],
                a.[Selected],
                a.[Customer],
                a.[Number],
                a.[Fax Number],
                a.[Contact E-mail],
                a.[Contact],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code],
                a.[Street Address],
                a.[Suburb],
                a.[City],
                a.[Street Code],
                a.[Delivery Address],
                a.[Delivery Suburb],
                a.[Delivery City],
                a.[Delivery Code],
                a.[Head Office]
        FROM dbo.fn_AS_Top50Perc_Customers_GP_Mail_Merge(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.CustomerID = b.CustomerID
        WHERE b.CustomerID IS NULL
        ORDER BY a.[Customer]

    ELSE
-->LAST 50%
    IF @Option = 5        SELECT  a.[CustomerID],
                a.[Selected],
                a.[Customer],
                a.[Number],
                a.[Fax Number],
                a.[Contact E-mail],
                a.[Contact],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code],
                a.[Street Address],
                a.[Suburb],
                a.[City],
                a.[Street Code],
                a.[Delivery Address],
                a.[Delivery Suburb],
                a.[Delivery City],
                a.[Delivery Code],
                a.[Head Office]
        FROM dbo.fn_AS_Top100Perc_Customers_GP_Mail_Merge(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.CustomerID = b.CustomerID
        WHERE b.CustomerID IS NULL
        ORDER BY a.[Customer]

    ELSE
-->Salesperson
    IF @Option = 6
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Lup_AS_Reps_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Sales Area
    IF @Option = 7
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Lup_AC_Sales_Areas_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Language
    IF @Option = 8
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Slu_AW_Languages_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Type
    IF @Option = 9
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Lup_AC_Customer_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Credit Terms
    IF @Option = 10
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Slu_AW_Credit_Terms_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Discount Category
    IF @Option = 11
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Lup_AC_Discount_Categories_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Group
    IF @Option = 12
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Lup_AC_Customer_Groups_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Account Type
    IF @Option = 13
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Sys_AC_Account_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Account Status
    IF @Option = 14
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Sys_AC_Account_Status_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]


    ELSE
-->New Customers (Start Date)
    IF @Option = 15
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.Start_Date >= @StartDate AND
              c.Start_Date <= @EndDate AND
              c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Sales
    IF @Option = 16
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               CASE WHEN c.Firstnames IS NULL
                    THEN ISNULL(c.Surname, '')
                    ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                    END AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
               CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                (c.Sys_AC_Credit_Term_Types_ID,
                                 b.Terms_Value,
                                 c.AC_Customers_ID,
                                 @Midnight,
                                 @D1,
                                 @D2,
                                 @D3,
                                 @D4,
                                 @D5,
                                 @D6,
                                 @D7), 0)) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t
                ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            LEFT JOIN Slu_AW_Credit_Terms b
                ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
        WHERE c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       Sys_AW_Transaction_Types_ID = 3) 
                AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]




SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















--------------------------------------------------------------------------------
--Description   :sp_AS_Select_Mail_Merge_Lups
--Purpose       :Word Mail Merge Lookups
--Date          :2007/12/05
--Authors       :TB
--MODS          :
--------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AS_Select_Mail_Merge_Lups
    (
       	@Option int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    IF @Option = 1	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],
               [Description] AS [Yes_No]  	
        FROM Slu_AW_YesNo

    ELSE
    IF @Option = 2	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID],
               [Description] AS [Active] 
        FROM Slu_AW_Active 

    ELSE
    IF @Option = 3 --'Language'
        SELECT Slu_AW_Languages_ID AS [ID], Description AS [Language]
        FROM Slu_AW_Languages

    ELSE
    IF @Option = 4 --'Type'
        SELECT Lup_AC_Customer_Types_ID AS [ID], Description AS [Customer Type]
        FROM Lup_AC_Customer_Types
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 5 --'Discount Category'
        SELECT Lup_AC_Discount_Categories_ID AS [ID], Description AS [Discount Category]
        FROM Lup_AC_Discount_Categories
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 6 --'Credit Terms'
        SELECT Slu_AW_Credit_Terms_ID AS [ID], Description AS [Credit Terms]
        FROM Slu_AW_Credit_Terms

    ELSE
    IF @Option = 7 --'Salesperson'
        SELECT Lup_AS_Reps_ID AS [ID], Description AS [Salesperson]
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 8 --'Sales Area'
        SELECT Lup_AC_Sales_Areas_ID AS [ID], Description AS [Sales Area]
        FROM Lup_AC_Sales_Areas
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 9 --'Customer Group'
        SELECT Lup_AC_Customer_Groups_ID AS [ID], Description AS [Customer Group]
        FROM Lup_AC_Customer_Groups
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @Option = 10 --'Account Type'
        SELECT Sys_AC_Account_Types_ID AS [ID], Description AS [Account Type]
        FROM Sys_AC_Account_Types

    ELSE
    IF @Option = 11 --'SMS Messages
        SELECT Slu_AW_SMS_Messages_ID AS [ID],
              [English] AS [English],
              [Afrikaans] as [Afrikaans]
        FROM Slu_AW_SMS_Messages

    ELSE
    IF @Option = 12 --'Account Status'
        SELECT Sys_AC_Account_Status_ID AS [ID], Description AS [Account Status]
        FROM Sys_AC_Account_Status


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






















-----------------------------------------------------------------------------------
--Description   :sp_AS_Select_Mail_Merge_Product_Customers
--Purpose       :Retrieves the Customers of a Product
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2007/12/05
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_AS_Select_Mail_Merge_Product_Customers
    (
        @ProductID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @Midnight datetime,
            @Now datetime,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime


    SET @Now = getdate()
    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Now), 0, 1)))


    EXEC sp_AW_Period_Procedures_Select
            @Now,
            @D1 OUTPUT,
            @D2 OUTPUT,
            @D3 OUTPUT,
            @D4 OUTPUT,
            @D5 OUTPUT,
            @D6 OUTPUT,
            @D7 OUTPUT,
            1,
            @CompanyID


    SELECT DISTINCT c.AC_Customers_ID AS [CustomerID], 
                   c.AW_YesNo_Send_Email_ID AS [Selected],
                   CASE WHEN c.Firstnames IS NULL
                        THEN ISNULL(c.Surname, '')
                        ELSE ISNULL(c.Surname, '') + ', ' + LTRIM(ISNULL(c.Firstnames, ''))
                        END AS [Customer],
                   c.Customer_Number AS [Number],
                   c.Fax_No AS [Fax Number],
                   CONVERT(money, dbo.fn_AC_Customer_Balance(c.AC_Customers_ID)) AS [Balance],
                   CONVERT(money, ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                                            (c.Sys_AC_Credit_Term_Types_ID,
                                             b.Terms_Value,
                                             c.AC_Customers_ID,
                                             @Midnight,
                                             @D1,
                                             @D2,
                                             @D3,
                                             @D4,
                                             @D5,
                                             @D6,
                                             @D7), 0)) AS [Overdue],
                   c.Home_Email AS [Contact E-mail],
                   LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                             THEN ISNULL(c.Principal_Name, '')
                             ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                                  RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                        END, 50) AS [Principal],
                   c.Contact_Name AS [Contact], 
                   c.Post_Box AS [Post Box],
                   c.Post_Office AS [Post Office],
                   c.Post_Code AS [Post Code],
                   c.Street_Address AS [Street Address], 
                   c.Suburb AS [Suburb],
                   c.City AS [City],
                   c.Street_Post_Code AS [Street Code]
    FROM AS_Transaction_Details d
        INNER JOIN AS_Transactions h
            ON h.AS_Transactions_ID = d.AS_Transactions_ID
        INNER JOIN AC_Customers c
            ON h.AC_Customers_ID = c.AC_Customers_ID
        INNER JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Credit_Terms b
            ON b.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
    WHERE c.AC_Customers_ID in
            (SELECT distinct AC_Customers_ID
             FROM AS_Transactions
             WHERE d.AP_Products_ID = @ProductID AND
                   h.Transaction_Date >= @StartDate AND
                   h.Transaction_Date <= @EndDate AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4))
    ORDER BY [Customer]


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















----------------------------------------------------------------------------
--Description   :sp_AS_Select_Mail_Merge_Products
--Functionality :Returns products matching search criteria in Mail Merge
--Date          :2007/12/05
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE               PROCEDURE sp_AS_Select_Mail_Merge_Products
    (
        @CompanyID int,
        @Criteria1 varchar(100) = '',
        @Criteria2 varchar(100) = '',
        @Criteria3 varchar(100) = '',
        @Startdate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

   DECLARE
        @Criteria varchar(8000), 
        @sql varchar(8000)

   SET @Criteria = ''
	
   IF @CompanyID > -1   
      BEGIN
         IF @Criteria = '' 
            SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
         ELSE
            SET @Criteria = @Criteria + ' AND p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID)
      END

   IF @Criteria3 <> '' and @criteria2 <> '' and @criteria1 <> ''
      BEGIN
        IF @Criteria = '' 
           SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                   (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
        ELSE
            SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria3 + '%'' AND p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                              (p.Product_Code Like ''%' + @Criteria3 + '%'' AND p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria2 <> '' and @criteria1 <> '' 
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
										(p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria2 + '%'' AND p.Description Like ''%' + @Criteria1 + '%'') OR
                                                   (p.Product_Code Like ''%' + @Criteria2 + '%'' AND p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END

    ELSE
    IF @Criteria1 <> ''   
        BEGIN
            IF @Criteria = '' 
                SET @Criteria = ' WHERE (p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%'')'
            ELSE
                SET @Criteria = @Criteria + ' AND ((p.Description Like ''%' + @Criteria1 + '%'') OR (p.Product_Code Like ''%' + @Criteria1 + '%''))'
        END


    SET @Criteria = @Criteria + ' AND p.Last_Sale_Date >= ''' + CONVERT(varchar(30), @Startdate) + ''''
    SET @Criteria = @Criteria + ' AND p.Last_Sale_Date <= ''' + CONVERT(varchar(30), @Enddate) + ''''


    SET @sql = ' SELECT '
    SET @sql = @sql + '    p.AP_Products_ID as [ProductID], '
    SET @sql = @sql + '    p.Description as [Product], ' 
    SET @sql = @sql + '    p.Product_Code as [Code], '  
    SET @sql = @sql + '    p.On_Hand as [On Hand], '
    SET @sql = @sql + '    p.Pack_Size AS [Pack], '
    SET @sql = @sql + '    pt.Description AS [Type],  '
    SET @sql = @sql + '    pg.Description AS [Group],  '
    SET @sql = @sql + '    pd.Description AS [Department],  '
    SET @sql = @sql + '    p.Last_Sale_Date AS [Last Sale]  '
    SET @sql = @sql + ' FROM AP_Products p   '
    SET @sql = @sql + '     LEFT OUTER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID  '
    SET @sql = @sql + '     LEFT OUTER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID  '
    SET @sql = @sql + '     LEFT OUTER JOIN Lup_AP_Product_Groups pg '
    SET @sql = @sql + '         ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID  '


    SET @sql = @sql + @Criteria + ' '

    SET @sql = @sql + ' ORDER BY p.Description '


    EXEC (@sql)



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Mail_Merge_Prospects
--Purpose       :Retrieves Search Filter Prospects
--Date          :2007/12/05
--Authors       :TB
--MODS          :
--2004.4.5      :10/07/09 - Added Delivery Address and Head Office fields
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_Select_Mail_Merge_Prospects
    (
        @CompanyID int, 
        @Option int,
        @FetchChoice int,
        @Value int,
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON

-->ALL Prospects
    IF @Option = 0
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]


    ELSE
-->Salesperson
    IF @Option = 6
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AS_Reps_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Sales Area
    IF @Option = 7
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Sales_Areas_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Language
    IF @Option = 8
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Languages_ID = @Value  
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Type
    IF @Option = 9        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Credit Terms
    IF @Option = 10
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Credit_Terms_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Discount Category
    IF @Option = 11
        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Discount_Categories_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Customer Group
    IF @Option = 12        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Groups_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->Account Type
    IF @Option = 13        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Types_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]


    ELSE
-->Account Status
    IF @Option = 14        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Customers c
                INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Status_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]

    ELSE
-->New Customers (Start Date)
    IF @Option = 15        SELECT c.AC_Prospects_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Selected],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(c.Surname, '')
                         ELSE ISNULL(c.Surname, '') + ', ' + 
                              LTRIM(ISNULL(c.Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(c.Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               CONVERT(money, 0) AS [Balance],
               CONVERT(money, 0) AS [Overdue],
               c.Fax_No AS [Fax Number],
               c.Home_Email AS [Contact E-mail],
               LEFT(CASE WHEN c.Principal_Firstname IS NULL or RTRIM(LTRIM(c.Principal_Firstname)) = ''
                         THEN ISNULL(c.Principal_Name, '')
                         ELSE ISNULL(c.Principal_Firstname, '') + ' ' + 
                              RTRIM(LTRIM(ISNULL(c.Principal_Name, '')))
                    END, 50) AS [Principal],
               c.Contact_Name AS [Contact], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code],
               c.Street_Address AS [Street Address], 
               c.Suburb AS [Suburb],
               c.City AS [City],
               c.Street_Post_Code AS [Street Code],
               c.Delivery_Address AS [Delivery Address], 
               c.Delivery_Suburb AS [Delivery Suburb],
               c.Delivery_City AS [Delivery City],
               c.Delivery_Post_Code AS [Delivery Code],
               c.Head_Office AS [Head Office]
        FROM AC_Prospects c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Start_Date >= @StartDate AND
              c.Start_Date <= @EndDate AND
              c.AW_User_Companies_ID = @CompanyID
        ORDER BY [Customer]





SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--------------------------------------------------------------------------------
--Description   :sp_AS_Select_Sales_Lups
--Purpose       :Returns Sales module Lookups
--Functionality :
--Parameters    :
--Date          :2003/01/11
--Authors       :TB
--MODS          :11/07/04 - Added Options 6 and 7 - Transaction Cost Editor
--2004.4.6      :10/08/09 - Modified @Choice = 0 to fetch Day-Ends from AS_Day_Ends
--------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Select_Sales_Lups
    (
    	@Choice tinyint
    )

AS

SET NOCOUNT ON


	--> DISTINCT Day-End dates
    IF @Choice = 0
--         SELECT DISTINCT Day_End AS [DayEndDate]
--         FROM AS_Transactions
--         WHERE Day_End IS NOT NULL
--         ORDER BY Day_End DESC
		SELECT Day_End AS [DayEndDate]
        FROM AS_Day_Ends
        ORDER BY Day_End DESC

	--> Active
	ELSE 
	IF @Choice = 1
		SELECT Slu_AW_Active_ID AS [ID],
			[Description] AS [Active]
		FROM Slu_AW_Active

	--> Transaction Types
	ELSE 
	IF @Choice = 2
		SELECT Sys_AW_Transaction_Types_ID AS [ID],
			[Description] AS [Type]
		FROM Sys_AW_Transaction_Types

    --> Years
    ELSE
    IF @Choice = 3
    	SELECT Slu_AW_Years_ID AS [ID], 
        	[Description] AS [Year] 
    	FROM Slu_AW_Years

    --> Months (Long Description)
    ELSE 
    IF @Choice = 4
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Long_Description] AS [Month] 
    	FROM Slu_AW_Months

    --> Months (Short Description)
    ELSE 
    IF @Choice = 5
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Description] AS [Month] 
    	FROM Slu_AW_Months

    --> Transaction Types - with DETAIL ONLY
    ELSE
    IF @Choice = 6
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or 
              Sys_AW_Transaction_Types_ID = 3 or
              Sys_AW_Transaction_Types_ID = 4 or
              Sys_AW_Transaction_Types_ID = 16 or
              Sys_AW_Transaction_Types_ID = 17

    --> Users
    ELSE
    IF @Choice = 7
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [User]
        FROM AW_Users 
        ORDER BY [User]


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_AS_Select_Sales_Order_Details
--Purpose       :
--Date          :21 JUN 2008
--Authors       :TB
--MODS          :
--2004.3.9      :05/07/08 - Added @OrderType input parameter to separate open
--              :           Back Orders (Type = 0) from Sales Orders (Type = 1)
--2016.6.2	RL	2016-11-01	:Changed sales order search to AS_Transaction tables
--V6.3		RL	:2017/09/19 - Changed column headers
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Sales_Order_Back_Orders]
    (
    	@CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @OrderType tinyint = 0,
        @SortOption tinyint = 0
    )

AS

SET NOCOUNT ON


    IF @OrderType = 0        --Back Orders
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]						
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
					SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Product], h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], h.Date_Captured
                END
        END

    ELSE                    
    IF @OrderType = 1        --Sales Orders
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
					SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Product], h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], h.Date_Captured
                END
        END
		ELSE    
        BEGIN
            IF @SortOption = 0
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1 AND
						  h.SYS_AW_Transaction_Types_ID = 16
                    ORDER BY h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1 AND
						  h.SYS_AW_Transaction_Types_ID = 16
                    ORDER BY [Product], h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1 AND
						  h.SYS_AW_Transaction_Types_ID = 16
                    ORDER BY [Customer], h.Date_Captured
                END
        END



SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Sales_Order_Lups
--Date          :2008/06/17
--Authors       :TB
--MODS          :
--20004.4.0     :10/07/08 - Added Volume Discount
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_Select_Sales_Order_Lups
    (
       	@Choice int,
       	@CustomerID int,
    	@CompanyID int
    )

AS

        IF @Choice = 1    --'Reps  **'
          	SELECT Lup_AS_Reps_ID AS [ID], Description 
            FROM Lup_AS_Reps
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]

        ELSE
        IF @Choice = 2    --'Active'
          	SELECT Slu_AW_Active_ID AS [ID],
                   [Description] AS [Description] 
            FROM Slu_AW_Active 
            ORDER BY [Description]

        ELSE
        IF @Choice = 3    --'Active' for Deactivate Transactions
          	SELECT Slu_AW_Active_ID AS [ID],
                   [Description] AS [Active] 
            FROM Slu_AW_Active 

        ELSE
        IF @Choice = 4    --Transaction Types
            SELECT Sys_AW_Transaction_Types_ID as [ID],
                   [Description]
            FROM Sys_AW_Transaction_Types
            WHERE Sys_AW_Transaction_Types_ID = 3 or 
                  Sys_AW_Transaction_Types_ID = 4 or 
                  Sys_AW_Transaction_Types_ID = 16
            ORDER BY Description

        ELSE
        IF @Choice = 5    --Customer E-Mail addresses
            BEGIN
                SELECT Orders_URL as [EMail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CustomerID

                UNION

                SELECT Home_Email as [EMail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CustomerID

                UNION

                SELECT Work_Email as [EMail]
                FROM AC_Customers
                WHERE AC_Customers_ID = @CustomerID
            END   

        ELSE
        IF @Choice = 6    --Volume Discount
        	SELECT Slu_AS_Volume_Discounts_ID as [ID],
                   ISNULL(Sales_Qty, 0) as [SalesQty],
                   ISNULL(Discount_Perc, 0) as [DiscPerc]
        	FROM Slu_AS_Volume_Discounts
            WHERE Slu_AW_Active_ID = 1
            ORDER BY [SalesQty]











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Zero_Cost_Transactions
--Purpose       :Zero Cost (100% GP) Sales Transactions
--Date          :2004/07/11
--Authors       :TB
--MODS:         :05/03/06 - Added filter for Product Non-Stock items
--2004.4.2      :13/11/08 - Replaced [Cost] with [Unit Cost] to prevent confusion
--2004.4.4      :10/04/09 - Added [Day End], [TypeID], [Type] and [NonStockID]
--              :           fields to enable new GL Journal Posting
--2004.5.0      :15/11/10 - Renamed tt.[Description] alias from [Type] to [Transaction Type]
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AS_Select_Zero_Cost_Transactions
    (
        @CompanyID int,
        @TranType tinyint,
        @StartDate datetime,
        @EndDate datetime,
        @NonStock tinyint
    )

AS

SET NOCOUNT ON

    IF @TranType > 0    --> Specific Transaction Type
        BEGIN
            IF @NonStock = 0
                BEGIN
                    SELECT  h.AW_User_Companies_ID AS [CompanyID],
                            h.AC_Customers_ID AS [CustID],
                            d.AS_Transaction_Details_ID AS [DetailID],
                            h.AS_Transactions_ID AS [TranID],
                            h.Transaction_Date AS [Date],
                            tt.[Description] AS [Transaction Type],
                            h.Transaction_Number AS [Number],
                            ISNULL(c.Surname,'') + ISNULL(c.Firstnames,'') + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) +')' AS [Customer],
                            p.[Description] AS [Product],
                            p.Product_Code AS [Code],
                            d.Quantity AS [Qty],
                            d.Unit_Cost AS [Unit Cost],
                            d.Unit_Price AS [Unit Price],
                            CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
                            CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                                 THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100))
                                 ELSE 0.00
                                 END AS [Act GP%],
                            u.UserName AS [User],
                            h.Day_End AS [Day End],
                            p.Lup_AP_Product_Types_ID AS [TypeID],
                            p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockID],
                            ISNULL(pt.Description, '') AS [Type]
                    FROM AS_Transaction_Details d
                         INNER JOIN AS_Transactions h
                             ON h.AS_Transactions_ID = d.AS_Transactions_ID
                         INNER JOIN AP_Products p
                             ON d.AP_Products_ID = p.AP_Products_ID
                         INNER JOIN AC_Customers c
                             ON c.AC_Customers_ID = h.AC_Customers_ID
                         LEFT JOIN Sys_AW_Transaction_Types tt
                             ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                         LEFT JOIN Lup_AP_Product_Types pt
                             ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
                         LEFT JOIN AW_Users u
                             ON h.User_ID = u.AW_Users_ID
                    WHERE d.AW_User_Companies_ID = CONVERT(varchar(10), @CompanyID) AND
                          h.Transaction_Date >= CONVERT(varchar(30), @StartDate) AND
                          h.Transaction_Date <= CONVERT(varchar(30), @EndDate) AND
                          d.Unit_Cost = 0 and
                          h.Sys_AW_Transaction_Types_ID = + CONVERT(varchar(10), @TranType)
                    ORDER BY h.Transaction_Date ASC
                END

            ELSE        --> Ignore Non-Stock items
                BEGIN
                    SELECT  h.AW_User_Companies_ID AS [CompanyID],
                            h.AC_Customers_ID AS [CustID],
                            d.AS_Transaction_Details_ID AS [DetailID],
                            h.AS_Transactions_ID AS [TranID],
                            h.Transaction_Date AS [Date],
                            tt.[Description] AS [Transaction Type],
                            h.Transaction_Number AS [Number],
                            ISNULL(c.Surname,'') + ISNULL(c.Firstnames,'') + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) +')' AS [Customer],
                            p.[Description] AS [Product],
                            p.Product_Code AS [Code],
                            d.Quantity AS [Qty],
                            d.Unit_Cost AS [Unit Cost],
                            d.Unit_Price AS [Unit Price],
                            CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
                            CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                                 THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100))
                                 ELSE 0.00
                                 END AS [Act GP%],
                            u.UserName AS [User],
                            h.Day_End AS [Day End],
                            p.Lup_AP_Product_Types_ID AS [TypeID],
                            p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockID],
                            ISNULL(pt.Description, '') AS [Type]
                    FROM AS_Transaction_Details d
                         INNER JOIN AS_Transactions h
                             ON h.AS_Transactions_ID = d.AS_Transactions_ID
                         INNER JOIN AP_Products p
                             ON d.AP_Products_ID = p.AP_Products_ID
                         INNER JOIN AC_Customers c
                             ON c.AC_Customers_ID = h.AC_Customers_ID
                         LEFT JOIN Sys_AW_Transaction_Types tt
                             ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                         LEFT JOIN Lup_AP_Product_Types pt
                             ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
                         LEFT JOIN AW_Users u
                             ON h.User_ID = u.AW_Users_ID
                    WHERE d.AW_User_Companies_ID = CONVERT(varchar(10), @CompanyID) AND
                          h.Transaction_Date >= CONVERT(varchar(30), @StartDate) AND
                          h.Transaction_Date <= CONVERT(varchar(30), @EndDate) AND
                          d.Unit_Cost = 0 AND
                          h.Sys_AW_Transaction_Types_ID = + CONVERT(varchar(10), @TranType) AND
                          p.Slu_AW_YesNo_Non_Stock_Item = 0
                    ORDER BY h.Transaction_Date ASC
                END
        END

    ELSE                --> ALL Transaction Types
        BEGIN
            IF @NonStock = 0
                BEGIN
                    SELECT  h.AW_User_Companies_ID AS [CompanyID],
                            h.AC_Customers_ID AS [CustID],
                            d.AS_Transaction_Details_ID AS [DetailID],
                            h.AS_Transactions_ID AS [TranID],
                            h.Transaction_Date AS [Date],
                            tt.[Description] AS [Transaction Type],
                            h.Transaction_Number AS [Number],
                            ISNULL(c.Surname,'') + ISNULL(c.Firstnames,'') + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) +')' AS [Customer],
                            p.[Description] AS [Product],
                            p.Product_Code AS [Code],
                            d.Quantity AS [Qty],
                            d.Unit_Cost AS [Unit Cost],
                            d.Unit_Price AS [Unit Price],
                            CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
                            CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                                 THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100))
                                 ELSE 0.00
                                 END AS [Act GP%],
                            u.UserName AS [User],
                            h.Day_End AS [Day End],
                            p.Lup_AP_Product_Types_ID AS [TypeID],
                            p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockID],
                            ISNULL(pt.Description, '') AS [Type]
                    FROM AS_Transaction_Details d
                         INNER JOIN AS_Transactions h
                             ON h.AS_Transactions_ID = d.AS_Transactions_ID
                         INNER JOIN AP_Products p
                             ON d.AP_Products_ID = p.AP_Products_ID
                         INNER JOIN AC_Customers c
                             ON c.AC_Customers_ID = h.AC_Customers_ID
                         LEFT JOIN Sys_AW_Transaction_Types tt
                             ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                         LEFT JOIN Lup_AP_Product_Types pt
                             ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
                         LEFT JOIN AW_Users u
                             ON h.User_ID = u.AW_Users_ID
                    WHERE d.AW_User_Companies_ID = CONVERT(varchar(10), @CompanyID) AND
                          h.Transaction_Date >= CONVERT(varchar(30), @StartDate) AND
                          h.Transaction_Date <= CONVERT(varchar(30), @EndDate) AND
                          d.Unit_Cost = 0 AND
                         (h.Sys_AW_Transaction_Types_ID = 3 OR
                          h.Sys_AW_Transaction_Types_ID = 4 OR
                          h.Sys_AW_Transaction_Types_ID = 1 OR
                          h.Sys_AW_Transaction_Types_ID = 2 OR
                          h.Sys_AW_Transaction_Types_ID = 13)
                    ORDER BY h.Transaction_Date ASC
                END

            ELSE        --> Ignore Non-Stock items
                BEGIN
                    SELECT  h.AW_User_Companies_ID AS [CompanyID],
                            h.AC_Customers_ID AS [CustID],
                            d.AS_Transaction_Details_ID AS [DetailID],
                            h.AS_Transactions_ID AS [TranID],
                            h.Transaction_Date AS [Date],
                            tt.[Description] AS [Transaction Type],
                            h.Transaction_Number AS [Number],
                            ISNULL(c.Surname,'') + ISNULL(c.Firstnames,'') + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) +')' AS [Customer],
                            p.[Description] AS [Product],
                            p.Product_Code AS [Code],
                            d.Quantity AS [Qty],
                            d.Unit_Cost AS [Unit Cost],
                            d.Unit_Price AS [Unit Price],
                            CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
                            CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                                 THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100))
                                 ELSE 0.00
                                 END AS [Act GP%],
                            u.UserName AS [User],
                            h.Day_End AS [Day End],
                            p.Lup_AP_Product_Types_ID AS [TypeID],
                            p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockID],
                            ISNULL(pt.Description, '') AS [Type]
                    FROM AS_Transaction_Details d
                         INNER JOIN AS_Transactions h
                             ON h.AS_Transactions_ID = d.AS_Transactions_ID
                         INNER JOIN AP_Products p
                             ON d.AP_Products_ID = p.AP_Products_ID
                         INNER JOIN AC_Customers c
                             ON c.AC_Customers_ID = h.AC_Customers_ID
                         LEFT JOIN Sys_AW_Transaction_Types tt
                             ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                         LEFT JOIN Lup_AP_Product_Types pt
                             ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID
                         LEFT JOIN AW_Users u
                             ON h.User_ID = u.AW_Users_ID
                    WHERE d.AW_User_Companies_ID = CONVERT(varchar(10), @CompanyID) AND
                          h.Transaction_Date >= CONVERT(varchar(30), @StartDate) AND
                          h.Transaction_Date <= CONVERT(varchar(30), @EndDate) AND
                          d.Unit_Cost = 0 AND
                         (h.Sys_AW_Transaction_Types_ID = 3 OR
                          h.Sys_AW_Transaction_Types_ID = 4 OR
                          h.Sys_AW_Transaction_Types_ID = 1 OR
                          h.Sys_AW_Transaction_Types_ID = 2 OR
                          h.Sys_AW_Transaction_Types_ID = 13) AND
                          p.Slu_AW_YesNo_Non_Stock_Item = 0
                    ORDER BY h.Transaction_Date ASC
                END
        END


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Account_Balance_Detail
--Purpose       :CUSTOMER CATALOG: Unallocated Ageing Transactions Detail (Account Balances tab)
--Date          :2004/12/08
--Authors       :TB
--MODS          :
--2004.5.3      :29/08/11 - Added [Promotion Sale], [Job No], [Serial No], [Make] fields
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Shape_Account_Balance_Detail 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID], 
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           CONVERT(money,(d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
           CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100))
                ELSE 0.00
                END AS [Act GP%],
           CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) * 100))
                ELSE 0.00
                END AS [Std GP%],
           d.Quantity AS [Qty],
           d.Unit_Price AS [Unit Price], 
           d.Discount_Amount AS [Sales Disc],
           d.Tax_Amount AS [VAT],
           d.Extended_Amount AS [Amount],
           d.Unit_Cost AS [Unit Cost], 
           CONVERT(money,(d.Quantity * d.Unit_Cost)) AS [Total Cost],
           CONVERT(money,(d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Disc],
           d.Original_Price AS [Orig Price],
           pp.[Description] AS [Promotion Sale], 
           d.AS_Job_References_ID AS [Job No],
           d.Serial_No AS [Serial No],
           d.Make AS [Make]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AP_Products pp
            ON d.AP_Promotion_Products_ID = pp.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Account_Balance_Header
--Purpose       :CUSTOMER CATALOG: Unallocated Ageing Transactions (Account Balances tab)
--Date          :2004/12/08
--Authors       :TB
--Version       :1.0
--MODS          :10/03/06 - Added [TypeID] field - What happened to it before !!!!
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Account_Balance_Header]
	(
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime

    --> MIDNITE tonight
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))

    EXEC sp_AW_Period_Procedures_Select
             @Now,
             @D1 OUTPUT,
             @D2 OUTPUT,
             @D3 OUTPUT,
             @D4 OUTPUT,
             @D5 OUTPUT,
             @D6 OUTPUT,
             @D7 OUTPUT,
             1,
             @CompanyID


    SELECT
    	t.AS_Transactions_ID AS [ID], 
    	t.AC_Customers_ID AS [CustomerID],
    	ISNULL(tt.[Description], '') AS [Type],
    	t.Transaction_Date AS [Date], 
    	ISNULL(t.Transaction_Number, '') AS [No], 
    	ISNULL(t.Total_Amount, 0) AS [Amount], 
    	ISNULL(t.Payment_Amount, 0) AS [Payment], 
--     		t.Total_Amount AS [Balance],
--     		t.Total_Amount + t.Payment_Amount AS [Old Balance],
		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Old Balance],
    	ISNULL(t.Comment, '') AS [Comment],
    --NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
    	a.[Current] ,
    	a.[30 Days],
    	a.[60 Days],
    	a.[90 Days],
    	a.[120 Days],
    	a.[150 Days],
    	a.[180+ Days],
        a.[User],
        t.Sys_AW_Transaction_Types_ID AS [TypeID]
    FROM AS_Transactions t 
        LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
            ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
            ON t.AS_Transactions_ID = a.[ID]
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.AC_Customers_ID = @CustomerID AND
          ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
         (t.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
          t.Sys_AW_Transaction_Types_ID = 4 OR   --Refund
          t.Sys_AW_Transaction_Types_ID = 5 OR   --Journal
          t.Sys_AW_Transaction_Types_ID = 7 OR   --Payment
          t.Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
          t.Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
          t.Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
          t.Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
    ORDER BY t.Transaction_Date         --DESC



SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Day_End_Details
--Purpose       :Day End sales DETAIL extract from AS_Transactions
--              :was sp_RPT_AS_Transaction_Details before
--Date          :2006/10/01
--Authors		:TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE  sp_AS_Shape_Day_End_Details
	(
		@TransactionID int
	)

AS

SET NOCOUNT ON

    SELECT     
        ISNULL(p.[Description],'') AS [Product], 
        ISNULL(p.Product_Code,'') AS [Code], 
        ISNULL(td.Quantity,0) AS [Qty], 
        ISNULL(td.Unit_Cost,0) AS [Cost], 
        ISNULL(td.Unit_Price,0) AS [Price], 
        ISNULL(td.Original_Price,0) AS [Original Price], 
        ISNULL(td.Original_Discount,0) AS [Original Discount], 
        ISNULL(td.Discount_Amount,0) AS [Discount], 
        ISNULL(td.Tax_Amount,0) AS [Tax], 
        ISNULL(td.Extended_Amount,0) AS [Amount], 
        ISNULL(td.Commission_Amount,0) AS [Commission], 
        td.AP_Products_ID AS [ProductID], 
        td.AS_Transactions_ID AS [TransactionID], 
        td.AS_Transaction_Details_ID AS [ID]
    FROM AS_Transaction_Details td 
        LEFT OUTER JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
    WHERE td.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Day_End_Headers
--Purpose       :Day End sales HEADERS extract from AS_Transactions
--              :was vw_RPT_AS_Transaction_Headers before
--Date          :2006/10/01
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Shape_Day_End_Headers

AS

    SELECT  
        ISNULL(c.Surname, '') + isnull(', ' + c.Firstnames, '') AS Customer,
        ISNULL(c.Credit_Limit,0) AS [Credit Limit], 
        ISNULL(c.Account_Balance,0) AS [Account Balance], 
        ISNULL(t.Transaction_Number,'') AS [No], 
        ISNULL(t.Total_Cost,0) AS [Cost], 
        ISNULL(t.Amount,0) AS [Amount], 
        ISNULL(t.Total_Tax_Amount,0) AS [Tax], 
        ISNULL(t.Total_Discount_Amount,0) AS [Discount], 
        ISNULL(t.Total_Amount,0) AS [Total], 
        ISNULL(t.Payment_Amount,0) AS [Payment], 
        t.Transaction_Date, 
        tt.[Description] AS [TransactionType], 
--        tills.[Description] AS [Till], 
--        u.UserName AS [Cashier],
--        cashiers.[Description] AS [Cashier], 
--        reps.[Description] AS [Rep], 
--        t.Cashed_Up, 
        t.Day_End, 
--         t.Customer_Reference, 
--         t.Expiry_Date,
--         com.Comment, 
        uc.Company_Name,
        t.AW_User_Companies_ID AS [CompanyID], 
--         t.Lup_AS_Cashiers_ID AS [CashierID], 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
--         t.Lup_AS_Tills_ID AS [TillID], 
--         t.Lup_AS_Reps_ID AS [RepID], 
        c.AC_Customers_ID AS [CustomerID],
        t.AS_Transactions_ID AS [ID]

--UNFINISHED 22 SEP 02 include ALL UNINVOICED Job Cards)
--        t.Slu_AW_Active_ID AS [Active] 
---------------
	FROM AS_Transactions t 
			LEFT JOIN AC_Customers c
                ON t.AC_Customers_ID = c.AC_Customers_ID 
			LEFT JOIN fn_AW_Comments(-7) com
                ON t.AW_Comments_ID = com.ID
			LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
			LEFT JOIN Lup_AS_Tills tills
                ON t.Lup_AS_Tills_ID = tills.Lup_AS_Tills_ID 
			LEFT JOIN Lup_AS_Cashiers cashiers
                ON t.Lup_AS_Cashiers_ID = cashiers.Lup_AS_Cashiers_ID
-- 			LEFT JOIN AW_Users u
--                 ON t.Lup_AS_Cashiers_ID = u.AW_Users_ID
			LEFT JOIN Lup_AS_Reps reps
                ON t.Lup_AS_Reps_ID = reps.Lup_AS_Reps_ID
			LEFT JOIN AW_User_Companies uc
                ON t.AW_User_Companies_ID = uc.AW_User_Companies_ID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Sales_Order_Detail
--Purpose       :Selects Customer Sales Orders Detail Shaped
--Date          :2008/06/17
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Sales_Order_Detail] 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON


    SELECT d.AS_Transaction_Details_ID AS [ID],
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product],
           p.Product_Code AS [Code],
		   b.Description AS [Bin],
           d.Unit_Price AS [Unit Price],
           d.Quantity AS [Qty],
           d.Back_Order AS [B/O],
           d.Discount_Amount AS [Discount],
           CONVERT(money, (d.Extended_Amount - d.Tax_Amount)) AS [Amount],
           d.Tax_Amount AS [Tax],
           d.Extended_Amount AS [Total],
           d.Original_Price AS [Orig Price],
           CASE WHEN (d.Extended_Amount - d.Tax_Amount) <> 0
                THEN CONVERT(decimal(9, 3), ROUND((d.Tax_Amount / (d.Extended_Amount - d.Tax_Amount)) * 100, 2))
                ELSE 0.00
           END AS [Tax Rate],
           d.Unit_Cost AS [Unit Cost]		   
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
		LEFT JOIN Lup_AP_Product_Bins b
			ON d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
    WHERE d.AS_Transactions_ID = @TransactionID
    ORDER BY [ID]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Sales_Order_Header
--Purpose       :Selects Customer Sales Orders Header Shaped
--Date          :2008/06/17
--Authors       :TB
--MODS          :
--2004.3.9      :06/07/08 - Added LEFT JOIN of AS_Transactions_Xref* tables to show
--              :           REVERSE SOURCE Invoice/Refund the Sales Order was charged
--              :           out on if it exists. Returns NULL is not exists
--V6.3	RL	2017-05-03	:Added Active Description
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Sales_Order_Header]
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @Option tinyint = 0
	)

AS

SET NOCOUNT ON


    IF @Option = 0        --> All Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                CASE WHEN ai.[Description] IS NULL
                     THEN 'Recall XREF'
                     ELSE ai.[Description]
                END AS [Active]
                
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END
    ELSE
    IF @Option = 1        --> Uninvoiced Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                ai.Description As [Active]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID                    
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID = 1 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 2        --> Invoiced Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                ai.Description As [Active]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID                    
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID = 0 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 3        --> Cancelled Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                ai.Description As [Active]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID                    
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID > 1 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Chrono_Detail
--Purpose       :Selects POS Transaction Detail Shaped
--Date          :2003/08/09
--Authors       :TB
--Version       :1.0
--Mods          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Shape_Transaction_Chrono_Detail 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID], 
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           CONVERT(money,(d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
           CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100))
                ELSE 0.00
                END AS [Act GP%],
           CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) * 100))
                ELSE 0.00
                END AS [Std GP%],
           d.Quantity AS [Qty],
           d.Unit_Price AS [Unit Price], 
           d.Discount_Amount AS [Sales Disc],
           d.Tax_Amount AS [VAT],
           d.Extended_Amount AS [Amount],
           d.Unit_Cost AS [Unit Cost], 
           CONVERT(money,(d.Quantity * d.Unit_Cost)) AS [Total Cost],
           CONVERT(money,(d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Disc],
           d.Original_Price AS [Orig Price]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Chrono_Header
--Purpose       :Selects POS Transaction Header Shaped
--Date          :2003/08/09
--Authors       :TB
--Version       :1.0
--MODS          :18/12/03 - Added [TypeID] field for Customer Transaction Search
--              :06/12/04 - Reversed [Customer] field as (Surnames, Firstnames)
--              :06/12/04 - Added @CompanyID filter in WHERE clauses
--              :06/12/04 - Added CASE statement to not calculate GP on PAYMENTS
--V6.4	RL	2018-04-23	:Add GP%
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Chrono_Header]
	(
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

--> Specific Transaction Type
    IF @TransactionTypeID <> 0
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
--                RTRIM(LTRIM(ISNULL(c.Firstnames, '') + ISNULL(' ' + c.Surname, ''))) AS [Customer],
                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                t.Total_Cost AS [Total Cost],


           CASE WHEN (t.Total_Amount - t.Total_Tax_Amount) <> 0
                THEN CONVERT(    money, (   ((t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost)) / (t.Total_Amount - t.Total_Tax_Amount)  * 100 )  )
                ELSE 0.00
                END AS [GP%],

                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                          t.Sys_AW_Transaction_Types_ID <> 22
                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                     ELSE 0
                END AS [GP],

                t.Comment AS [Comment],
                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                a.[Description] AS [Active],
               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
                INNER JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                INNER JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
            ORDER BY t.Transaction_Date DESC
        END

--> ALL Transaction Types
    ELSE
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
--                RTRIM(LTRIM(ISNULL(c.Firstnames, '') + ISNULL(' ' + c.Surname, ''))) AS [Customer],
                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                t.Total_Cost AS [Total Cost],

           CASE WHEN (t.Total_Amount - t.Total_Tax_Amount) <> 0
                THEN CONVERT(    money, (   ((t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost)) / (t.Total_Amount - t.Total_Tax_Amount)  * 100 )  )
                ELSE 0.00
                END AS [GP%],
                
                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                          t.Sys_AW_Transaction_Types_ID <> 22
                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                     ELSE 0
                END AS [GP],

                t.Comment AS [Comment],
                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                a.[Description] AS [Active],
               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
                INNER JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                INNER JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (t.Sys_AW_Transaction_Types_ID = 1 or
                  t.Sys_AW_Transaction_Types_ID = 2 or 
                  t.Sys_AW_Transaction_Types_ID = 3 or 
                  t.Sys_AW_Transaction_Types_ID = 4 or 
                  t.Sys_AW_Transaction_Types_ID = 5 or 
                  t.Sys_AW_Transaction_Types_ID = 7 or 
                  t.Sys_AW_Transaction_Types_ID = 15 or 
                  t.Sys_AW_Transaction_Types_ID = 18 or
                  t.Sys_AW_Transaction_Types_ID = 21 or 
            	  t.Sys_AW_Transaction_Types_ID = 22) AND
                  DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
            ORDER BY Transaction_Date DESC
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Detail
--Purpose       :Selects POS Transaction Detail Shaped
--Date          :2003/08/09
--Authors       :TB
--Version       :1.0
--Mods          :26/01/04 - Added [ProductID] to delete RESERVED from Product
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Shape_Transaction_Detail 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           d.Quantity AS [Qty],
           d.Unit_Cost AS [Cost], 
           d.Unit_Price AS [Price], 
           d.Original_Price AS [Orig Price], 
           d.Discount_Amount AS [Discount], 
           d.Tax_Amount AS [Tax], 
           d.Extended_Amount AS [Total] 
--           d.Commission_Amount AS [Commission]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Header
--Purpose       :Selects POS Transaction Header Shaped
--Date          :2003/08/09
--Authors       :TB
--MODS          :
--2004.3.7      :09/08/07 - Added OPTIONAL @Option input parameter
--              :17/11/07 - Added @Option = 2 - Expired Transactions
--2004.3.9      :05/07/08 - Added new Select Sales Order TranType = 16 where required
--2004.4.0      :28/07/08 - Changed Slu_AW_Active_ID > 1 in Option 2 (Disabled per Customer)
--              :           because previous Slu_AW_Active_ID = 2 has limited scope
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AS_Shape_Transaction_Header
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @Option tinyint = 0
	)

AS

--sp_AS_Shape_Transaction_Header 1, 0, '2008/07/01 12:00:01 AM', '2008/07/28 11:59:59 PM', 2

SET NOCOUNT ON


    IF @Option = 0
        BEGIN
        --> Specific Transaction Type
            IF @TransactionTypeID <> 0
                BEGIN
                    SELECT
                        AS_Transactions_ID AS [ID],
                        AC_Customers_ID AS [CustomerID],
                        Sys_AW_Transaction_Types_ID AS [Transaction Type],
                        Transaction_Date AS [Date],
                        Transaction_Number AS [Ref No],
                        Amount AS [Amount],
                        Total_Discount_Amount AS [Discount],
                        Total_Tax_Amount AS [VAT],
                        Total_Amount AS [Total],
                        Payment_Amount AS [Payment],
                        Comment AS [Comment],
                        [User_ID] AS [User],
                        Slu_AW_Active_ID AS [Active]
                    FROM AS_Transactions
                    WHERE AC_Customers_ID = @CustomerID AND
                          Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                          Slu_AW_Active_ID = 1 AND
                         (DATEDIFF(d, Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, Transaction_Date, @EndDate) >= 0)
                    ORDER BY Transaction_Date DESC
                END
        
        --> ALL Transaction Types
            ELSE
                BEGIN
                    SELECT
                        AS_Transactions_ID AS [ID],
                        AC_Customers_ID AS [CustomerID],
                        Sys_AW_Transaction_Types_ID AS [Transaction Type],
                        Transaction_Date AS [Date],
                        Transaction_Number AS [Ref No],
                        Amount AS [Amount],
                        Total_Discount_Amount AS [Discount],
                        Total_Tax_Amount AS [VAT],
                        Total_Amount AS [Total],
                        Payment_Amount AS [Payment],
                        Comment AS [Comment],
                        [User_ID] AS [User],
                        Slu_AW_Active_ID AS [Active]
                    FROM AS_Transactions
                    WHERE AC_Customers_ID = @CustomerID AND
                         (Sys_AW_Transaction_Types_ID = 1 OR
                          Sys_AW_Transaction_Types_ID = 2 OR
                          Sys_AW_Transaction_Types_ID = 13 OR
                          Sys_AW_Transaction_Types_ID = 16) AND
                          Slu_AW_Active_ID = 1 AND
                         (DATEDIFF(d, Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, Transaction_Date, @EndDate) >= 0)
                    ORDER BY Transaction_Date DESC
                END
        END

    ELSE
    IF @Option = 1
        BEGIN
        --> Specific Transaction Type
            IF @TransactionTypeID <> 0
                BEGIN
                    SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        h.Sys_AW_Transaction_Types_ID AS [Transaction Type],
                        c.Surname AS [Customer],
                        h.Transaction_Date AS [Date],
                        h.Transaction_Number AS [Ref No],
                        h.Amount AS [Amount],
                        h.Total_Discount_Amount AS [Discount],
                        h.Total_Tax_Amount AS [VAT],
                        h.Total_Amount AS [Total],
                        h.Payment_Amount AS [Payment],
                        h.Comment AS [Comment],
                        h.[User_ID] AS [User],
                        h.Slu_AW_Active_ID AS [Active]
                    FROM AS_Transactions h
                        LEFT JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
                    WHERE h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                          h.Slu_AW_Active_ID = 1 AND
                         (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
                    ORDER BY h.Transaction_Date DESC
                END
        
        --> ALL Transaction Types
            ELSE
                BEGIN
                    SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        h.Sys_AW_Transaction_Types_ID AS [Transaction Type],
                        c.Surname AS [Customer],
                        h.Transaction_Date AS [Date],
                        h.Transaction_Number AS [Ref No],
                        h.Amount AS [Amount],
                        h.Total_Discount_Amount AS [Discount],
                        h.Total_Tax_Amount AS [VAT],
                        h.Total_Amount AS [Total],
                        h.Payment_Amount AS [Payment],
                        h.Comment AS [Comment],
                        h.[User_ID] AS [User],
                        h.Slu_AW_Active_ID AS [Active]
                    FROM AS_Transactions h
                        LEFT JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
                    WHERE (h.Sys_AW_Transaction_Types_ID = 1 OR
                           h.Sys_AW_Transaction_Types_ID = 2 OR
                           h.Sys_AW_Transaction_Types_ID = 13 OR
                           h.Sys_AW_Transaction_Types_ID = 16) AND
                           h.Slu_AW_Active_ID = 1 AND
                          (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                           DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
                    ORDER BY h.Transaction_Date DESC
                END
        END

    ELSE
    IF @Option = 2
        BEGIN
        --> Specific Transaction Type
            IF @TransactionTypeID <> 0
                BEGIN
                    SELECT
                        AS_Transactions_ID AS [ID],
                        AC_Customers_ID AS [CustomerID],
                        Sys_AW_Transaction_Types_ID AS [Transaction Type],
                        Transaction_Date AS [Date],
                        Transaction_Number AS [Ref No],
                        Amount AS [Amount],
                        Total_Discount_Amount AS [Discount],
                        Total_Tax_Amount AS [VAT],
                        Total_Amount AS [Total],
                        Payment_Amount AS [Payment],
                        Comment AS [Comment],
                        [User_ID] AS [User],
                        Slu_AW_Active_ID AS [Active]
                    FROM AS_Transactions
                    WHERE AC_Customers_ID = @CustomerID AND
                          Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                          Slu_AW_Active_ID > 1 AND
                         (DATEDIFF(d, Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, Transaction_Date, @EndDate) >= 0)
                    ORDER BY Transaction_Date DESC
                END
        
        --> ALL Transaction Types
            ELSE
                BEGIN
                    SELECT
                        AS_Transactions_ID AS [ID],
                        AC_Customers_ID AS [CustomerID],
                        Sys_AW_Transaction_Types_ID AS [Transaction Type],
                        Transaction_Date AS [Date],
                        Transaction_Number AS [Ref No],
                        Amount AS [Amount],
                        Total_Discount_Amount AS [Discount],
                        Total_Tax_Amount AS [VAT],
                        Total_Amount AS [Total],
                        Payment_Amount AS [Payment],
                        Comment AS [Comment],
                        [User_ID] AS [User],
                        Slu_AW_Active_ID AS [Active]
                    FROM AS_Transactions
                    WHERE AC_Customers_ID = @CustomerID AND
                         (Sys_AW_Transaction_Types_ID = 1 OR
                          Sys_AW_Transaction_Types_ID = 2 OR
                          Sys_AW_Transaction_Types_ID = 13 OR
                          Sys_AW_Transaction_Types_ID = 16) AND
                          Slu_AW_Active_ID > 1 AND
                         (DATEDIFF(d, Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, Transaction_Date, @EndDate) >= 0)
                    ORDER BY Transaction_Date DESC
                END
        END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_History_Detail
--Purpose       :Selects Customer Transaction Detail Shaped
--Date          :2004/12/06
--Authors       :TB
--MODS          :
--2004.5.3      :29/08/11 - Added [Promotion Sale], [Job No], [Serial No], [Make] fields
--V6.3	RL	2017/04/21	:Added Back Order Qty to Qty For Sales Orders
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_History_Detail] 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID], 
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           CONVERT(money,(d.Extended_Amount - d.Tax_Amount) - ((d.Quantity + d.Back_Order) * d.Unit_Cost)) AS [GP],
           CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, (d.Quantity + d.Back_Order), d.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100))
                ELSE 0.00
                END AS [Act GP%],
           CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, (d.Quantity + d.Back_Order)) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, (d.Quantity + d.Back_Order)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, (d.Quantity + d.Back_Order))) * 100))
                ELSE 0.00
                END AS [Std GP%],
           (d.Quantity + d.Back_Order) AS [Qty],
           d.Unit_Price AS [Unit Price], 
           d.Discount_Amount AS [Sales Disc],
           d.Tax_Amount AS [VAT],
           d.Extended_Amount AS [Amount],
           d.Unit_Cost AS [Unit Cost], 
           CONVERT(money,((d.Quantity + d.Back_Order) * d.Unit_Cost)) AS [Total Cost],
           CONVERT(money,(d.Unit_Price - d.Original_Price) * (d.Quantity + d.Back_Order)) AS [Price Disc],
           d.Original_Price AS [Orig Price],
           pp.[Description] AS [Promotion Sale], 
           d.AS_Job_References_ID AS [Job No],
           d.Serial_No AS [Serial No],
           d.Make AS [Make]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AP_Products pp
            ON d.AP_Promotion_Products_ID = pp.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_History_Header
--Purpose       :Catalog History Transaction Header Shaped
--Date          :2004/12/08
--Authors       :TB
--MODS          :08/06/05 - Moved [Comment] field forward ahead of [Amount]
--2004.3.9      :05/07/08 - Added new Select Sales Order TranType = 16 where required
--2004.4.7      :22/08/09 - Added new Select Stock Transfer TranType = 23 where required
--2004.4.8      :29/04/10 - Added [Day-End] field
--              :22/05/10 - Added CASE to [Active] field to get 'Recall XREF' Quotes and Jobs
--              :22/05/10 - Added NEW [Source No] field to show XREF Quotes and Jobs numbers
--V6.0	RL	2014-09-09	: - Added new Select Proforma TranType = 13 where required
--V6.2	RL	2015-06-11	: - Added new Select Consignment TranType = 33, 34, 35 where required
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_History_Header]
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

--> Specific Transaction Type
    IF @TransactionTypeID <> 0
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Comment AS [Comment],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
                t.Total_Cost AS [Total Cost],

                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                          t.Sys_AW_Transaction_Types_ID <> 22
                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                     ELSE 0
                END AS [GP],

                t.Day_End AS [Day-End],

                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                ISNULL(ts.Transaction_Numbers, '') AS [Source No],

                CASE WHEN a.[Description] IS NULL
                     THEN 'Recall XREF'
                     ELSE a.[Description]
                END AS [Active],

               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
                INNER JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                LEFT JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
                LEFT JOIN AS_Transaction_Sources ts
                    ON t.AS_Transactions_ID = ts.AS_Transactions_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.AC_Customers_ID = @CustomerID AND
                  t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
            ORDER BY t.Transaction_Date DESC
        END

--> ALL Transaction Types
    ELSE
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Comment AS [Comment],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
                t.Total_Cost AS [Total Cost],

                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                          t.Sys_AW_Transaction_Types_ID <> 22
                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                     ELSE 0
                END AS [GP],

                t.Day_End AS [Day-End],

                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                ISNULL(ts.Transaction_Numbers, '') AS [Source No],

                CASE WHEN a.[Description] IS NULL
                     THEN 'Recall XREF'
                     ELSE a.[Description]
                END AS [Active],

               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
                INNER JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
                LEFT JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                LEFT JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
                LEFT JOIN AS_Transaction_Sources ts
                    ON t.AS_Transactions_ID = ts.AS_Transactions_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.AC_Customers_ID = @CustomerID AND
                 (t.Sys_AW_Transaction_Types_ID = 1 or
                  t.Sys_AW_Transaction_Types_ID = 2 or 
                  t.Sys_AW_Transaction_Types_ID = 3 or 
                  t.Sys_AW_Transaction_Types_ID = 4 or 
                  t.Sys_AW_Transaction_Types_ID = 5 or 
                  t.Sys_AW_Transaction_Types_ID = 7 or 
                  t.Sys_AW_Transaction_Types_ID = 13 or 
                  t.Sys_AW_Transaction_Types_ID = 15 or 
                  t.Sys_AW_Transaction_Types_ID = 16 or 
                  t.Sys_AW_Transaction_Types_ID = 18 or
                  t.Sys_AW_Transaction_Types_ID = 21 or 
            	  t.Sys_AW_Transaction_Types_ID = 22 or
            	  t.Sys_AW_Transaction_Types_ID = 23 or
            	  t.Sys_AW_Transaction_Types_ID = 33 or
            	  --t.Sys_AW_Transaction_Types_ID = 34 or
                  t.Sys_AW_Transaction_Types_ID = 35) AND
                  DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
            ORDER BY Transaction_Date DESC
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Detail
--Purpose       :Selects POS Transaction Detail Shaped
--Date          :2003/12/18
--Authors       :TB
--MODS          :
--2004.5.3      :29/08/11 - Added [Promotion Sale], [Job No], [Serial No], [Make] fields
--V6.3	RL	2017/04/21	:Added Back Order Qty to Qty For Sales Orders
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Detail] 
    (
        @TransactionID int
    )
AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID], 
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           CONVERT(money,(d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
           CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100))
                ELSE 0.00
                END AS [Act GP%],
           CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) * 100))
                ELSE 0.00
                END AS [Std GP%],
           (d.Quantity + d.Back_Order) AS [Qty],
           d.Unit_Price AS [Unit Price], 
           d.Discount_Amount AS [Sales Disc],
           d.Tax_Amount AS [VAT],
           d.Extended_Amount AS [Amount],
           d.Unit_Cost AS [Unit Cost], 
           CONVERT(money,(d.Quantity * d.Unit_Cost)) AS [Total Cost],
           CONVERT(money,(d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Disc],
           d.Original_Price AS [Orig Price],
           pp.[Description] AS [Promotion Sale], 
           d.AS_Job_References_ID AS [Job No],
           d.Serial_No AS [Serial No],
           d.Make AS [Make]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AP_Products pp
            ON d.AP_Promotion_Products_ID = pp.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Header
--Purpose       :Selects POS Transaction Header Shaped for Document Reprint
--Date          :2003/12/18
--Authors       :TB
--MODS          :18/12/03 - Added [TypeID] field for Customer Transaction Search
--              :06/12/04 - Reversed [Customer] field as (Surnames, Firstnames)
--              :06/12/04 - Added @CompanyID filter in WHERE clause IF @CustomerID <> 0
--              :06/12/04 - Added CASE statement to not calculate GP on PAYMENTS
--2004.3.7      :11/07/07 - Added AW_Comments as [Notes]
--2004.4.0      :11/07/08 - Added Sales Order transaction type = 16
--2004.4.2      :26/10/08 - Replaced [Ref No] (Transaction_Number) field with [No] and
--              :           added [Ref No] (Customer_Reference) field
--2004.4.7      :13/09/09 - Added new Stock Transfer transaction type = 23
--2004.5.8      :2013-02-20 - Added search for AS_Job_References_ID and Serial_No
--V6.0	RL	2014-09-09	: - Added new Select Proforma TranType = 13 where required
--V6.2	RL	2015-06-11	: - Added new Select Consignment TranType = 33, 34, 35 where required
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header]
	(
        @CustomerID int,
        @SearchString varchar(50),
        @Filter1 varchar(50) = NULL,
        @Filter2 varchar(50) = NULL,
        @Filter3 varchar(50) = NULL,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

-------------------------------------------------------------------------------
    IF @CustomerID <> 0
        BEGIN
        --> Specific Transaction Type
            IF @TransactionTypeID <> 0
                BEGIN
                    SELECT DISTINCT
                        t.AS_Transactions_ID AS [ID],
                        t.AC_Customers_ID AS [CustomerID],
                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                        tt.[Description] AS [Type],
                        t.Transaction_Date AS [Date],
                        t.Transaction_Number AS [No],
                        t.Customer_Reference AS [Ref No],
                        t.Amount AS [Amount],
                        t.Total_Discount_Amount AS [Discount],
                        t.Total_Tax_Amount AS [VAT],
                        t.Total_Amount AS [Total],
                        t.Payment_Amount AS [Payment],
                        t.Total_Cost AS [Total Cost],

                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                  t.Sys_AW_Transaction_Types_ID <> 22
                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                             ELSE 0
                        END AS [GP],

                        t.Comment AS [Comment],
                        com.Comment AS [Notes],
                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                        act.[Description] AS [Active],
                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AW_Users u
                            ON t.[User_ID] = u.AW_Users_ID
                        INNER JOIN Slu_AW_Active act
                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                        LEFT JOIN AW_Comments com
                            ON t.AW_Comments_ID = com.AW_Comments_ID
                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                          t.AC_Customers_ID = @CustomerID AND
                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                         (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
                    ORDER BY t.Transaction_Date DESC
                END
-----------------------------------------
        --> ALL Transaction Types
            ELSE
                BEGIN
                    SELECT DISTINCT
                        t.AS_Transactions_ID AS [ID],
                        t.AC_Customers_ID AS [CustomerID],
                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],

                        tt.[Description] AS [Type],
                        t.Transaction_Date AS [Date],
                        t.Transaction_Number AS [No],
                        t.Customer_Reference AS [Ref No],
                        t.Amount AS [Amount],
                        t.Total_Discount_Amount AS [Discount],
                        t.Total_Tax_Amount AS [VAT],
                        t.Total_Amount AS [Total],
                        t.Payment_Amount AS [Payment],
                        t.Total_Cost AS [Total Cost],

                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                  t.Sys_AW_Transaction_Types_ID <> 22
                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                             ELSE 0
                        END AS [GP],

                        t.Comment AS [Comment],
                        com.Comment AS [Notes],
                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                        act.[Description] AS [Active],
                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AW_Users u
                            ON t.[User_ID] = u.AW_Users_ID
                        INNER JOIN Slu_AW_Active act
                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                        LEFT JOIN AW_Comments com
                            ON t.AW_Comments_ID = com.AW_Comments_ID
                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                          t.AC_Customers_ID = @CustomerID AND
                          (t.Sys_AW_Transaction_Types_ID = 1 or
                           t.Sys_AW_Transaction_Types_ID = 2 or 
                           t.Sys_AW_Transaction_Types_ID = 3 or 
                           t.Sys_AW_Transaction_Types_ID = 4 or 
                           t.Sys_AW_Transaction_Types_ID = 5 or 
                           t.Sys_AW_Transaction_Types_ID = 7 or
                           t.Sys_AW_Transaction_Types_ID = 13 or 
                           t.Sys_AW_Transaction_Types_ID = 15 or 
                           t.Sys_AW_Transaction_Types_ID = 16 or 
                    	   t.Sys_AW_Transaction_Types_ID = 18 or
                           t.Sys_AW_Transaction_Types_ID = 21 or 
                           t.Sys_AW_Transaction_Types_ID = 22 or 
                           t.Sys_AW_Transaction_Types_ID = 23 or 
                           t.Sys_AW_Transaction_Types_ID = 33 or 
                           t.Sys_AW_Transaction_Types_ID = 34 or 
                    	   t.Sys_AW_Transaction_Types_ID = 35) AND
                           DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                           DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                    ORDER BY t.Transaction_Date DESC
                END
        END
-------------------------------------------------------------------------------
    ELSE    --(IF @CustomerID = 0)
        BEGIN
        --> Specific Transaction Type
            IF @TransactionTypeID <> 0
                BEGIN
----------------------------------------->>>>>>>
                    IF @SearchString <> ''
                        BEGIN
----------------------------------------->>>>>>>
                			IF @Filter3 <> ''
                				BEGIN
                					SET @Filter3 = '%' +  @Filter3 + '%'
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference AS [Ref No],
                                        t.Amount AS [Amount],
                                        t.Total_Discount_Amount AS [Discount],
                                        t.Total_Tax_Amount AS [VAT],
                                        t.Total_Amount AS [Total],
                                        t.Payment_Amount AS [Payment],
                                        t.Total_Cost AS [Total Cost],

                                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 22
                                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                             ELSE 0
                                        END AS [GP],

                                        t.Comment AS [Comment],
                                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        INNER JOIN AC_Customers c
                                            ON t.AC_Customers_ID = c.AC_Customers_ID
                                        INNER JOIN Sys_AW_Transaction_Types tt
                                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
        
                                         ((c.Surname like @Filter1 AND
                                           c.Surname like @Filter2 AND
                                           c.Surname like @Filter3 ) OR 
                                          (c.Firstnames like @Filter1 AND
                                           c.Firstnames like @Filter2 AND
                                           c.Firstnames like @Filter3) OR 
                                          (c.Cell_No like @Filter1 AND
                                           c.Cell_No like @Filter2 AND
                                           c.Cell_No like @Filter3) OR 
                                          (c.Work_Tel_No like @Filter1 AND
                                           c.Work_Tel_No like @Filter2 AND
                                           c.Work_Tel_No like @Filter3) OR 
                                          (c.Home_Tel_No like @Filter1 AND
                                           c.Home_Tel_No like @Filter2 AND
                                           c.Home_Tel_No like @Filter3) OR 
                                          (t.Transaction_Number like @Filter1 AND
                                           t.Transaction_Number like @Filter2 AND
                                           t.Transaction_Number like @Filter3) OR
                                          (t.Customer_Reference like @Filter1 AND
                                           t.Customer_Reference like @Filter2 AND
                                           t.Customer_Reference like @Filter3) OR
                                          (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter2 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter3) OR
                                          (t.Comment like @Filter1 AND
                                           t.Comment like @Filter2 AND
                                           t.Comment like @Filter3) OR
                                          (com.Comment like @Filter1 AND
                                           com.Comment like @Filter2 AND
                                           com.Comment like @Filter3) OR
--2004.5.8                                          
                                          (d.AS_Job_References_ID like @Filter1 AND
                                           d.AS_Job_References_ID like @Filter2 AND
                                           d.AS_Job_References_ID like @Filter3) OR                                        
                                          (d.Serial_No like @Filter1 AND
                                           d.Serial_No like @Filter2 AND
                                           d.Serial_No like @Filter3) OR
--2004.5.8                                                                                                                               
                                          (a.Reg_No like @Filter1 AND
                                           a.Reg_No like @Filter2 AND
                                           a.Reg_No like @Filter3)) AND
                
                                          (t.Sys_AW_Transaction_Types_ID = 1 or
                                           t.Sys_AW_Transaction_Types_ID = 2 or 
                                           t.Sys_AW_Transaction_Types_ID = 3 or 
                                           t.Sys_AW_Transaction_Types_ID = 4 or 
                                           t.Sys_AW_Transaction_Types_ID = 5 or 
                                           t.Sys_AW_Transaction_Types_ID = 7 or
                                           t.Sys_AW_Transaction_Types_ID = 13 or 
                                           t.Sys_AW_Transaction_Types_ID = 15 or 
                                    	   t.Sys_AW_Transaction_Types_ID = 18 or
                                           t.Sys_AW_Transaction_Types_ID = 21 or 
                                           t.Sys_AW_Transaction_Types_ID = 22 or 
                                           t.Sys_AW_Transaction_Types_ID = 23 or 
                                           t.Sys_AW_Transaction_Types_ID = 33 or 
                                           t.Sys_AW_Transaction_Types_ID = 34 or 
                    	                   t.Sys_AW_Transaction_Types_ID = 35) AND
                                           DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                           DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter2 <> ''
                				BEGIN
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference AS [Ref No],
                                        t.Amount AS [Amount],
                                        t.Total_Discount_Amount AS [Discount],
                                        t.Total_Tax_Amount AS [VAT],
                                        t.Total_Amount AS [Total],
                                        t.Payment_Amount AS [Payment],
                                        t.Total_Cost AS [Total Cost],

                                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 22
                                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                             ELSE 0
                                        END AS [GP],

                                        t.Comment AS [Comment],
                                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        INNER JOIN AC_Customers c
                                            ON t.AC_Customers_ID = c.AC_Customers_ID
                                        INNER JOIN Sys_AW_Transaction_Types tt
                                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
        
                                        ((c.Surname like @Filter1 AND
                                          c.Surname like @Filter2) OR
                                         (c.Firstnames like @Filter1 AND
                                          c.Firstnames like @Filter2) OR
                                         (c.Cell_No like @Filter1 AND
                                          c.Cell_No like @Filter2) OR
                                         (c.Work_Tel_No like @Filter1 AND
                                          c.Work_Tel_No like @Filter2) OR
                                         (c.Home_Tel_No like @Filter1 AND
                                          c.Home_Tel_No like @Filter2) OR
                                         (t.Transaction_Number like @Filter1 AND
                                          t.Transaction_Number like @Filter2) OR
                                         (t.Customer_Reference like @Filter1 AND
                                          t.Customer_Reference like @Filter2) OR
                                         (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter2) OR
                                         (t.Comment like @Filter1 AND
                                          t.Comment like @Filter2) OR
                                         (com.Comment like @Filter1 AND
                                          com.Comment like @Filter2) OR
--2004.5.8                                          
                                          (d.AS_Job_References_ID like @Filter1 AND
                                           d.AS_Job_References_ID like @Filter2) OR                                        
                                          (d.Serial_No like @Filter1 AND
                                           d.Serial_No like @Filter2) OR
--2004.5.8                                                                                    
                                         (a.Reg_No like @Filter1 AND
                                          a.Reg_No like @Filter2)) AND
                
                                         (t.Sys_AW_Transaction_Types_ID = 1 or
                                          t.Sys_AW_Transaction_Types_ID = 2 or 
                                          t.Sys_AW_Transaction_Types_ID = 3 or 
                                          t.Sys_AW_Transaction_Types_ID = 4 or 
                                          t.Sys_AW_Transaction_Types_ID = 5 or 
                                          t.Sys_AW_Transaction_Types_ID = 7 or
                                          t.Sys_AW_Transaction_Types_ID = 13 or  
                                          t.Sys_AW_Transaction_Types_ID = 15 or 
                                          t.Sys_AW_Transaction_Types_ID = 18 or
                                          t.Sys_AW_Transaction_Types_ID = 21 or 
                                          t.Sys_AW_Transaction_Types_ID = 22 or 
                                          t.Sys_AW_Transaction_Types_ID = 23 or 
                                          t.Sys_AW_Transaction_Types_ID = 33 or 
                                          t.Sys_AW_Transaction_Types_ID = 34 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 35) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter1 <> ''
                				BEGIN
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference AS [Ref No],
                                        t.Amount AS [Amount],
                                        t.Total_Discount_Amount AS [Discount],
                                        t.Total_Tax_Amount AS [VAT],
                                        t.Total_Amount AS [Total],
                                        t.Payment_Amount AS [Payment],
                                        t.Total_Cost AS [Total Cost],

                                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 22
                                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                             ELSE 0
                                        END AS [GP],

                                        t.Comment AS [Comment],
                                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        INNER JOIN AC_Customers c
                                            ON t.AC_Customers_ID = c.AC_Customers_ID
                                        INNER JOIN Sys_AW_Transaction_Types tt
                                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
        
                                         (c.Surname like @Filter1 OR
                                          c.Firstnames like @Filter1 OR
                                          c.Cell_No like @Filter1 OR
                                          c.Work_Tel_No like @Filter1 OR
                                          c.Home_Tel_No like @Filter1 OR
                                          t.Transaction_Number like @Filter1 OR
                                          t.Customer_Reference like @Filter1 OR
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter1 OR
                                          t.Comment like @Filter1 OR
                                          com.Comment like @Filter1 OR
--2004.5.8                                          
                                          d.AS_Job_References_ID like @Filter1 OR                                        
                                          d.Serial_No like @Filter1 OR
--2004.5.8                                          
                                          a.Reg_No like @Filter1) AND
        
                                         (t.Sys_AW_Transaction_Types_ID = 1 or
                                          t.Sys_AW_Transaction_Types_ID = 2 or 
                                          t.Sys_AW_Transaction_Types_ID = 3 or 
                                          t.Sys_AW_Transaction_Types_ID = 4 or 
                                          t.Sys_AW_Transaction_Types_ID = 5 or 
                                          t.Sys_AW_Transaction_Types_ID = 7 or
                                          t.Sys_AW_Transaction_Types_ID = 13 or  
                                          t.Sys_AW_Transaction_Types_ID = 15 or 
                                          t.Sys_AW_Transaction_Types_ID = 18 or
                                          t.Sys_AW_Transaction_Types_ID = 21 or 
                                          t.Sys_AW_Transaction_Types_ID = 22 or 
                                          t.Sys_AW_Transaction_Types_ID = 23 or 
                                          t.Sys_AW_Transaction_Types_ID = 33 or 
                                          t.Sys_AW_Transaction_Types_ID = 34 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 35) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
                        END
----------------------------------------->>>>>>>
                    ELSE
                        BEGIN
                            SELECT DISTINCT
                                t.AS_Transactions_ID AS [ID],
                                t.AC_Customers_ID AS [CustomerID],
                                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                tt.[Description] AS [Type],
                                t.Transaction_Date AS [Date],
                                t.Transaction_Number AS [No],
                                t.Customer_Reference AS [Ref No],
                                t.Amount AS [Amount],
                                t.Total_Discount_Amount AS [Discount],
                                t.Total_Tax_Amount AS [VAT],
                                t.Total_Amount AS [Total],
                                t.Payment_Amount AS [Payment],
                                t.Total_Cost AS [Total Cost],

                                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                                          t.Sys_AW_Transaction_Types_ID <> 22
                                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                     ELSE 0
                                END AS [GP],

                                t.Comment AS [Comment],
                                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                act.[Description] AS [Active],
                               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                            FROM AS_Transactions t
                                INNER JOIN AC_Customers c
                                    ON t.AC_Customers_ID = c.AC_Customers_ID
                                INNER JOIN Sys_AW_Transaction_Types tt
                                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                INNER JOIN AW_Users u
                                    ON t.[User_ID] = u.AW_Users_ID
                                INNER JOIN Slu_AW_Active act
                                    ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                            WHERE t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                                 (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
                            ORDER BY t.Transaction_Date DESC
                        END
----------------------------------------->>>>>>>
                END
-----------------------------------------
        --> ALL Transaction Types
            ELSE
                BEGIN
----------------------------------------->>>>>>>
                    IF @SearchString <> ''
                        BEGIN
----------------------------------------->>>>>>>
                			IF @Filter3 <> ''
                				BEGIN
                					SET @Filter3 = '%' +  @Filter3 + '%'
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference AS [Ref No],
                                        t.Amount AS [Amount],
                                        t.Total_Discount_Amount AS [Discount],
                                        t.Total_Tax_Amount AS [VAT],
                                        t.Total_Amount AS [Total],
                                        t.Payment_Amount AS [Payment],
                                        t.Total_Cost AS [Total Cost],

                                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 22
                                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                             ELSE 0
                                        END AS [GP],

                                        t.Comment AS [Comment],
                                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        INNER JOIN AC_Customers c
                                            ON t.AC_Customers_ID = c.AC_Customers_ID
                                        INNER JOIN Sys_AW_Transaction_Types tt
                                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
        
                                         ((c.Surname like @Filter1 AND
                                           c.Surname like @Filter2 AND
                                           c.Surname like @Filter3 ) OR 
                                          (c.Firstnames like @Filter1 AND
                                           c.Firstnames like @Filter2 AND
                                           c.Firstnames like @Filter3) OR 
                                          (c.Cell_No like @Filter1 AND
                                           c.Cell_No like @Filter2 AND
                                           c.Cell_No like @Filter3) OR 
                                          (c.Work_Tel_No like @Filter1 AND
                                           c.Work_Tel_No like @Filter2 AND
                                           c.Work_Tel_No like @Filter3) OR 
                                          (c.Home_Tel_No like @Filter1 AND
                                           c.Home_Tel_No like @Filter2 AND
                                           c.Home_Tel_No like @Filter3) OR 
                                          (t.Transaction_Number like @Filter1 AND
                                           t.Transaction_Number like @Filter2 AND
                                           t.Transaction_Number like @Filter3) OR
                                          (t.Customer_Reference like @Filter1 AND
                                           t.Customer_Reference like @Filter2 AND
                                           t.Customer_Reference like @Filter3) OR
                                          (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter2 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter3) OR
                                          (t.Comment like @Filter1 AND
                                           t.Comment like @Filter2 AND
                                           t.Comment like @Filter3) OR
                                          (com.Comment like @Filter1 AND
                                           com.Comment like @Filter2 AND
                                           com.Comment like @Filter3) OR
--2004.5.8                                          
                                         (d.AS_Job_References_ID like @Filter1 AND
                                          d.AS_Job_References_ID like @Filter2 AND
                                          d.AS_Job_References_ID like @Filter3) OR
                                         (d.Serial_No like @Filter1 AND
                                          d.Serial_No like @Filter2 AND
                                          d.Serial_No like @Filter3) OR                                          
--2004.5.8                                                                                     
                                          (a.Reg_No like @Filter1 AND
                                           a.Reg_No like @Filter2 AND
                                           a.Reg_No like @Filter3)) AND
                
                                          (t.Sys_AW_Transaction_Types_ID = 1 or
                                           t.Sys_AW_Transaction_Types_ID = 2 or 
                                           t.Sys_AW_Transaction_Types_ID = 3 or 
                                           t.Sys_AW_Transaction_Types_ID = 4 or 
                                           t.Sys_AW_Transaction_Types_ID = 5 or 
                                           t.Sys_AW_Transaction_Types_ID = 7 or
                                           t.Sys_AW_Transaction_Types_ID = 13 or  
                                           t.Sys_AW_Transaction_Types_ID = 15 or 
                                    	   t.Sys_AW_Transaction_Types_ID = 18 or
                                           t.Sys_AW_Transaction_Types_ID = 21 or 
                                           t.Sys_AW_Transaction_Types_ID = 22 or 
                                           t.Sys_AW_Transaction_Types_ID = 23 or 
                                           t.Sys_AW_Transaction_Types_ID = 33 or 
                                           t.Sys_AW_Transaction_Types_ID = 34 or 
                    	                   t.Sys_AW_Transaction_Types_ID = 35) AND
                                           DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                           DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter2 <> ''
                				BEGIN
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference AS [Ref No],
                                        t.Amount AS [Amount],
                                        t.Total_Discount_Amount AS [Discount],
                                        t.Total_Tax_Amount AS [VAT],
                                        t.Total_Amount AS [Total],
                                        t.Payment_Amount AS [Payment],
                                        t.Total_Cost AS [Total Cost],

                                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 22
                                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                             ELSE 0
                                        END AS [GP],

                                        t.Comment AS [Comment],
                                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											
                                        INNER JOIN AC_Customers c
                                            ON t.AC_Customers_ID = c.AC_Customers_ID
                                        INNER JOIN Sys_AW_Transaction_Types tt
                                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
        
                                        ((c.Surname like @Filter1 AND
                                          c.Surname like @Filter2) OR
                                         (c.Firstnames like @Filter1 AND
                                          c.Firstnames like @Filter2) OR
                                         (c.Cell_No like @Filter1 AND
                                          c.Cell_No like @Filter2) OR
                                         (c.Work_Tel_No like @Filter1 AND
                                          c.Work_Tel_No like @Filter2) OR
                                         (c.Home_Tel_No like @Filter1 AND
                                          c.Home_Tel_No like @Filter2) OR
                                         (t.Transaction_Number like @Filter1 AND
                                          t.Transaction_Number like @Filter2) OR
                                         (t.Customer_Reference like @Filter1 AND
                                          t.Customer_Reference like @Filter2) OR
                                         (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter2) OR
                                         (t.Comment like @Filter1 AND
                                          t.Comment like @Filter2) OR
                                         (com.Comment like @Filter1 AND
                                          com.Comment like @Filter2) OR
--2004.5.8                                          
                                         (d.AS_Job_References_ID like @Filter1 AND
                                          d.AS_Job_References_ID like @Filter2) OR
                                         (d.Serial_No like @Filter1 AND
                                          d.Serial_No like @Filter2) OR                                          
--2004.5.8                                          
                                         (a.Reg_No like @Filter1 AND
                                          a.Reg_No like @Filter2)) AND
                
                                         (t.Sys_AW_Transaction_Types_ID = 1 or
                                          t.Sys_AW_Transaction_Types_ID = 2 or 
                                          t.Sys_AW_Transaction_Types_ID = 3 or 
                                          t.Sys_AW_Transaction_Types_ID = 4 or 
                                          t.Sys_AW_Transaction_Types_ID = 5 or 
                                          t.Sys_AW_Transaction_Types_ID = 7 or
                                          t.Sys_AW_Transaction_Types_ID = 13 or  
                                          t.Sys_AW_Transaction_Types_ID = 15 or 
                                          t.Sys_AW_Transaction_Types_ID = 16 or 
                                          t.Sys_AW_Transaction_Types_ID = 18 or
                                          t.Sys_AW_Transaction_Types_ID = 21 or 
                                          t.Sys_AW_Transaction_Types_ID = 22 or 
                                          t.Sys_AW_Transaction_Types_ID = 23 or 
                                          t.Sys_AW_Transaction_Types_ID = 33 or 
                                          t.Sys_AW_Transaction_Types_ID = 34 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 35) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter1 <> ''
                				BEGIN
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference AS [Ref No],
                                        t.Amount AS [Amount],
                                        t.Total_Discount_Amount AS [Discount],
                                        t.Total_Tax_Amount AS [VAT],
                                        t.Total_Amount AS [Total],
                                        t.Payment_Amount AS [Payment],
                                        t.Total_Cost AS [Total Cost],

                                        CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 18 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 21 AND
                                                  t.Sys_AW_Transaction_Types_ID <> 22
                                             THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                             ELSE 0
                                        END AS [GP],

                                        t.Comment AS [Comment],
                                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        INNER JOIN AC_Customers c
                                            ON t.AC_Customers_ID = c.AC_Customers_ID
                                        INNER JOIN Sys_AW_Transaction_Types tt
                                            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
        
                                         (c.Surname like @Filter1 OR
                                          c.Firstnames like @Filter1 OR
                                          c.Cell_No like @Filter1 OR
                                          c.Work_Tel_No like @Filter1 OR
                                          c.Home_Tel_No like @Filter1 OR
                                          t.Transaction_Number like @Filter1 OR
                                          t.Customer_Reference like @Filter1 OR
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter1 OR
                                          t.Comment like @Filter1 OR
                                          com.Comment like @Filter1 OR
--2004.5.8                                          
                                          d.AS_Job_References_ID like @Filter1 OR
                                          d.Serial_No like @Filter1 OR                                          
--2004.5.8                                                                                    
                                          a.Reg_No like @Filter1) AND
        
                                         (t.Sys_AW_Transaction_Types_ID = 1 or
                                          t.Sys_AW_Transaction_Types_ID = 2 or 
                                          t.Sys_AW_Transaction_Types_ID = 3 or 
                                          t.Sys_AW_Transaction_Types_ID = 4 or 
                                          t.Sys_AW_Transaction_Types_ID = 5 or 
                                          t.Sys_AW_Transaction_Types_ID = 7 or
                                          t.Sys_AW_Transaction_Types_ID = 13 or  
                                          t.Sys_AW_Transaction_Types_ID = 15 or 
                                          t.Sys_AW_Transaction_Types_ID = 16 or 
                                          t.Sys_AW_Transaction_Types_ID = 18 or
                                          t.Sys_AW_Transaction_Types_ID = 21 or 
                                          t.Sys_AW_Transaction_Types_ID = 22 or 
                                          t.Sys_AW_Transaction_Types_ID = 23 or 
                                          t.Sys_AW_Transaction_Types_ID = 33 or 
                                          t.Sys_AW_Transaction_Types_ID = 34 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 35) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
                        END
----------------------------------------->>>>>>>
                    ELSE
                        BEGIN
                            SELECT DISTINCT
                                t.AS_Transactions_ID AS [ID],
                                t.AC_Customers_ID AS [CustomerID],
                                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                tt.[Description] AS [Type],
                                t.Transaction_Date AS [Date],
                                t.Transaction_Number AS [No],
                                t.Customer_Reference AS [Ref No],
                                t.Amount AS [Amount],
                                t.Total_Discount_Amount AS [Discount],
                                t.Total_Tax_Amount AS [VAT],
                                t.Total_Amount AS [Total],
                                t.Payment_Amount AS [Payment],
                                t.Total_Cost AS [Total Cost],

                                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                                          t.Sys_AW_Transaction_Types_ID <> 22
                                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                                     ELSE 0
                                END AS [GP],

                                t.Comment AS [Comment],
                                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                                act.[Description] AS [Active],
                               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                            FROM AS_Transactions t
                                INNER JOIN AC_Customers c
                                    ON t.AC_Customers_ID = c.AC_Customers_ID
                                INNER JOIN Sys_AW_Transaction_Types tt
                                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                                INNER JOIN AW_Users u
                                    ON t.[User_ID] = u.AW_Users_ID
                                INNER JOIN Slu_AW_Active act
                                    ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                            WHERE (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                   DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
                            ORDER BY t.Transaction_Date DESC
                        END
----------------------------------------->>>>>>>
                END
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Header_Consignment
--Purpose       :Selects POS Transaction Header Shaped for Customer Consignment Stock
--Date          :2015/05/18
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment]
	(
        @CustomerID int,
        @SearchString varchar(50),
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

-------------------------------------------------------------------------------
 IF @CustomerID <> 0
 BEGIN --@CustomerID <> 0
	
	IF @TransactionTypeID <> 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	IF @TransactionTypeID = 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				 DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
			     DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		
			
END --@CustomerID <> 0


IF @CustomerID = 0
 BEGIN --@CustomerID <> 0
	
	IF @TransactionTypeID <> 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	IF @TransactionTypeID = 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				 DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				t.AC_Customers_ID AS [CustomerID],
				RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
				tt.[Description] AS [Type],
				t.Transaction_Date AS [Date],
				t.Transaction_Number AS [No],
				t.Customer_Reference AS [Ref No],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
			     DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		
			
END --@CustomerID = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Header_Consignment2
--Purpose       :Selects POS Transaction Header Shaped for Customer Consignment Stock
--Date          :2015/05/18
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment2]
	(
        @CustomerID int,
        @SearchString varchar(50),
        @Filter1 varchar(50) = NULL,
        @Filter2 varchar(50) = NULL,
        @Filter3 varchar(50) = NULL,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

-------------------------------------------------------------------------------
               
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
			IF @Filter3 <> ''
			BEGIN --@Filter3 <> ''
				SET @Filter3 = '%' +  @Filter3 + '%'
				SET @Filter2 = '%' +  @Filter2 + '%'
				SET @Filter1 = '%' +  @Filter1 + '%'
                
                SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					t.AC_Customers_ID AS [CustomerID],
					RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
					tt.[Description] AS [Type],
					t.Transaction_Date AS [Date],
					t.Transaction_Number AS [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.[Description] AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
				FROM AS_Transactions t
					INNER JOIN AC_Customers c
						ON t.AC_Customers_ID = c.AC_Customers_ID
					INNER JOIN Sys_AW_Transaction_Types tt
						ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
					INNER JOIN AW_Users u
						ON t.[User_ID] = u.AW_Users_ID
					INNER JOIN Slu_AW_Active act
						ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
					LEFT JOIN AW_Comments com
						ON t.AW_Comments_ID = com.AW_Comments_ID
					INNER JOIN AS_Transaction_Details td
						ON t.AS_Transactions_ID = td.AS_Transactions_ID
					INNER JOIN AP_Products p
						ON p.AP_Products_ID = td.AP_Products_ID
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
				WHERE t.AW_User_Companies_ID = @CompanyID AND
					t.AC_Customers_ID = @CustomerID AND
					t.Sys_AW_Transaction_Types_ID = 33 AND
					(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
					DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND
					(
						(t.Transaction_Number like @Filter1 AND
						 t.Transaction_Number like @Filter2 AND
						 t.Transaction_Number like @Filter3) OR
						 
						(p.Product_Code like @Filter1 AND
                         p.Product_Code like @Filter2 AND
                         p.Product_Code like @Filter3) OR

						(p.Description like @Filter1 AND
						 p.Description like @Filter2 AND
						 p.Description like @Filter3) OR

						(ISNULL(t.Customer_Reference,'') like @Filter1 AND
						 ISNULL(t.Customer_Reference,'') like @Filter2 AND
						 ISNULL(t.Customer_Reference,'') like @Filter3)
					) 						 
				ORDER BY t.Transaction_Date DESC
			END --@Filter3 <> ''	 
			
			IF @Filter2 <> ''
			BEGIN --@Filter2 <> ''				
				SET @Filter2 = '%' +  @Filter2 + '%'
				SET @Filter1 = '%' +  @Filter1 + '%'
                
                SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					t.AC_Customers_ID AS [CustomerID],
					RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
					tt.[Description] AS [Type],
					t.Transaction_Date AS [Date],
					t.Transaction_Number AS [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.Description AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Amount],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
				FROM AS_Transactions t
					INNER JOIN AC_Customers c
						ON t.AC_Customers_ID = c.AC_Customers_ID
					INNER JOIN Sys_AW_Transaction_Types tt
						ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
					INNER JOIN AW_Users u
						ON t.[User_ID] = u.AW_Users_ID
					INNER JOIN Slu_AW_Active act
						ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
					LEFT JOIN AW_Comments com
						ON t.AW_Comments_ID = com.AW_Comments_ID
					INNER JOIN AS_Transaction_Details td
						ON t.AS_Transactions_ID = td.AS_Transactions_ID
					INNER JOIN AP_Products p
						ON p.AP_Products_ID = td.AP_Products_ID	    
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
				WHERE t.AW_User_Companies_ID = @CompanyID AND
					t.AC_Customers_ID = @CustomerID AND
					t.Sys_AW_Transaction_Types_ID = 33 AND
					(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
					DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND					
					(
						(t.Transaction_Number like @Filter1 AND
						 t.Transaction_Number like @Filter2) OR
						 
						(p.Product_Code like @Filter1 AND
                         p.Product_Code like @Filter2) OR

						(p.Description like @Filter1 AND
						 p.Description like @Filter2) OR

						(ISNULL(t.Customer_Reference,'') like @Filter1 AND
						 ISNULL(t.Customer_Reference,'') like @Filter2)
					) 						 
				ORDER BY t.Transaction_Date DESC
			END --@Filter2 <> ''	 
	
			IF @Filter1 <> ''
			BEGIN --@Filter1 <> ''				
				SET @Filter1 = '%' +  @Filter1 + '%'
                
                SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					t.AC_Customers_ID AS [CustomerID],
					RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
					tt.[Description] AS [Type],
					t.Transaction_Date AS [Date],
					t.Transaction_Number AS [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.Description AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Amount],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
				FROM AS_Transactions t
					INNER JOIN AC_Customers c
						ON t.AC_Customers_ID = c.AC_Customers_ID
					INNER JOIN Sys_AW_Transaction_Types tt
						ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
					INNER JOIN AW_Users u
						ON t.[User_ID] = u.AW_Users_ID
					INNER JOIN Slu_AW_Active act
						ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
					LEFT JOIN AW_Comments com
						ON t.AW_Comments_ID = com.AW_Comments_ID
					INNER JOIN AS_Transaction_Details td
						ON t.AS_Transactions_ID = td.AS_Transactions_ID
					INNER JOIN AP_Products p
						ON p.AP_Products_ID = td.AP_Products_ID	    
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
				WHERE t.AW_User_Companies_ID = @CompanyID AND
					t.AC_Customers_ID = @CustomerID AND
					t.Sys_AW_Transaction_Types_ID = 33 AND
					(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
					DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND					
					(
						(t.Transaction_Number like @Filter1) OR
						 
						(p.Product_Code like @Filter1) OR

						(p.Description like @Filter1) OR

						(ISNULL(t.Customer_Reference,'') like @Filter1)
					) 						 
				ORDER BY t.Transaction_Date DESC
			END --@Filter1 <> ''	 
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					t.AC_Customers_ID AS [CustomerID],
					RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
					tt.[Description] AS [Type],
					t.Transaction_Date AS [Date],
					t.Transaction_Number AS [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.Description AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Amount],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
			FROM AS_Transactions t
				INNER JOIN AC_Customers c
					ON t.AC_Customers_ID = c.AC_Customers_ID
				INNER JOIN Sys_AW_Transaction_Types tt
					ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
				INNER JOIN AW_Users u
					ON t.[User_ID] = u.AW_Users_ID
				INNER JOIN Slu_AW_Active act
					ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
				LEFT JOIN AW_Comments com
					ON t.AW_Comments_ID = com.AW_Comments_ID
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				t.Sys_AW_Transaction_Types_ID = 33 AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND				
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Detail
--Purpose       :Selects Uninvoiced Sales Orders Detail Shaped
--Date          :2008/07/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Detail] 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product], 
           p.Product_Code AS [Code],
		   b.Description AS [Bin], 
           d.Quantity AS [Qty],
           d.Unit_Cost AS [Cost], 
           d.Unit_Price AS [Price], 
           d.Original_Price AS [Orig Price], 
           d.Discount_Amount AS [Discount], 
           d.Tax_Amount AS [Tax], 
           d.Extended_Amount AS [Total] 
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
		LEFT JOIN Lup_AP_Product_Bins b
			ON d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
    WHERE d.AS_Transactions_ID = @TransactionID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Uninvoiced_Sales_Orders_Header
--Purpose       :Selects Uninvoiced Sales Orders Shaped
--Date          :2008/07/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AS_Shape_Uninvoiced_Sales_Orders_Header
	(
        @Option tinyint,
        @TransactionTypeID tinyint,
        @StartDate datetime,
        @EndDate datetime
	)

AS

SET NOCOUNT ON


    IF @Option = 0
        BEGIN
            IF @TransactionTypeID <> 0
                BEGIN
                    SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        tt.[Description] AS [Transaction Type],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Firstnames, '')AS [Customer],
                        h.Transaction_Date AS [Date],
                        h.Transaction_Number AS [Ref No],
                        h.Amount AS [Amount],
                        h.Total_Discount_Amount AS [Discount],
                        h.Total_Tax_Amount AS [VAT],
                        h.Total_Amount AS [Total],
                        h.Payment_Amount AS [Payment],
                        h.Comment AS [Comment],
                        u.UserName AS [User],
                        a.[Description] AS [Active],
                        h.Sys_AW_Transaction_Types_ID AS [TypeID]
                    FROM AS_Transactions h
                        LEFT JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AW_Users u
                            ON h.[User_ID] = u.AW_Users_ID
                        INNER JOIN Slu_AW_Active a
                            ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID
                    WHERE h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                          h.Slu_AW_Active_ID = 1 AND
                         (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
                    ORDER BY h.Transaction_Date DESC
                END
        END

    ELSE
    IF @Option = 1
        BEGIN
            IF @TransactionTypeID <> 0
                BEGIN
                    SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        tt.[Description] AS [Transaction Type],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Firstnames, '')AS [Customer],
                        h.Transaction_Date AS [Date],
                        h.Transaction_Number AS [Ref No],
                        h.Amount AS [Amount],
                        h.Total_Discount_Amount AS [Discount],
                        h.Total_Tax_Amount AS [VAT],
                        h.Total_Amount AS [Total],
                        h.Payment_Amount AS [Payment],
                        h.Comment AS [Comment],
                        u.UserName AS [User],
                        a.[Description] AS [Active],
                        h.Sys_AW_Transaction_Types_ID AS [TypeID]
                    FROM AS_Transactions h
                        LEFT JOIN AC_Customers c
                            ON h.AC_Customers_ID = c.AC_Customers_ID
                        INNER JOIN Sys_AW_Transaction_Types tt
                            ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                        INNER JOIN AW_Users u
                            ON h.[User_ID] = u.AW_Users_ID
                        INNER JOIN Slu_AW_Active a
                            ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID
                    WHERE h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                          h.Slu_AW_Active_ID > 1 AND
                         (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
                    ORDER BY h.Transaction_Date DESC
                END
        END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Products_Select
--Purpose       :NEW POS Product Search (Normal) Results for 3 ARGUMENTS max
--Date          :2008/06/21
--Authors       :TB
--MODS          :
--2004.4.2      :26/10/08 - Added new Standard Cost Inventory Valuation method
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Shipping_Product_Select
    (    
        @ProductID int
    )

AS

SET NOCOUNT ON


	SELECT 
		p.AP_Products_ID as [ID],
		p.Description,
		ISNULL(p.Product_Code, '') as [Code],
		p.Last_Cost AS [Last Cost],
		p.Average_Cost AS [Avg Cost],
		p.Standard_Cost AS [Std Cost],
		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
		tc.Tax_Rate as [Tax Rate]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
	WHERE p.AP_Products_ID = @ProductID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Consignment
--Purpose       :Checks to see if product sold was consignment stock
--Functionality :SELECT 
--Parameters    :@AS_Transaction_Details_ID, @UserID, @CompanyID
--Date          :2015/04/10
--Version		:V6.2
--Authors       :RL
--MODS          :
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Transaction_Detail_Consignment]
    (
    	@ProductID				int,
    	@SoldQty				decimal(9,3),
    	@UserID					int,
		@CompanyID				int,
		@IsConsignmentStock		int Output    	
    )

AS
	DECLARE @ConsignmentStockQty		decimal(9,3),
			@Current_OnHandQty			decimal(9,3),
			@ConsignmentGRVQty			decimal(9,3),
			@OnHand						decimal(9,3),
			@AO_GRV_ID					int,
			@AO_GRV_Details_ID			int,
			@Con_AO_GRV_ID				int,
			@Con_AO_GRV_Details_ID		int,
			@Qty_Left					decimal(9,3),
			@ConsignmentGRVed			decimal(9,3),
			@CurrentConsignmentGRVQty	decimal(9,3),
			
			@Suppliers_ID				int,
			@AW_Transaction_Type		int,
    		@Order_ID					int,
    		@DateReceived				DateTime,
    		@DelNoteNo					varchar(20),
    		@SupplierRef				varchar(20),
    					
    		@AP_Products_ID				int,
    		@Det_Qty					decimal(9,3),
    		@Det_Unit_Price				money,
    		@Det_Trade_Discount_Amount	money,
    		@Det_Rebate_Discount_Amount	money,
    		@Det_Other_Discount_Amount	money,
    		@Det_Net_Amount				money,
    		@Det_Tax_Amount				Money,
    		@Det_Total_Cost				Money,
    		@Det_Tax_Code_ID			int,

    		@GRV_Qty					decimal(9,3),
    		@GRV_Unit_Price				money,
    		@GRV_Trade_Discount_Amount	money,
    		@GRV_Rebate_Discount_Amount	money,
    		@GRV_Other_Discount_Amount	money,
    		@GRV_Net_Amount				money,
    		@GRV_Tax_Amount				Money,
    		@GRV_Total_Cost				Money,
    		@GRV_DateReceived			DateTime,
    		@Comment					varchar(20),
    		@Slu_AW_Years_ID			int,  		
			@Slu_AW_Months_ID			int,
    		@Year						int,  		
			@Month						int,
			@ProductsQty				decimal(9,3),
			@ProductConsignmentStockQty		decimal(9,3),
			@ProductOffSite	decimal(9,3)
			

	SET @ConsignmentGRVQty = 0
	SET @IsConsignmentStock = 0
	SET @ConsignmentGRVed = 0
	SET @CurrentConsignmentGRVQty = 0
	
	SELECT @ConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
	
--Insert Into Temp_Debug Values('@ConsignmentStockQty',Convert(Varchar(100),@ConsignmentStockQty))  
 	SELECT @ProductOffSite = dbo.fn_AP_Get_Products_Out_On_Consignment(@ProductID)
 	SELECT @ProductOffSite = 0
 	
	SELECT  @Current_OnHandQty = On_Hand + @ProductOffSite- @ConsignmentStockQty,
			@OnHand = On_Hand
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID
	
--Insert Into Temp_Debug Values('28 - @Current_OnHandQty',Convert(Varchar(100),@Current_OnHandQty))   	
--Insert Into Temp_Debug Values('28 - @OnHand',Convert(Varchar(100),@OnHand))   
--Insert Into Temp_Debug Values('28 - @SoldQty',Convert(Varchar(100),@SoldQty))  
 
--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)

--Insert Into Temp_Debug Values('28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	


	SET @IsConsignmentStock = 0	
	IF @Current_OnHandQty < 0
		SET @Current_OnHandQty = 0
		
	IF @ConsignmentStockQty <> 0
	BEGIN
		IF @Current_OnHandQty < @SoldQty
		BEGIN
			SET @ConsignmentGRVQty = @SoldQty - @Current_OnHandQty
			IF @ConsignmentGRVQty > @ConsignmentStockQty
				SET @ConsignmentGRVQty = @ConsignmentStockQty
				
			SET @IsConsignmentStock = 1
		END
	END

--Insert Into Temp_Debug Values('28 - @Current_OnHandQty',Convert(Varchar(100),@Current_OnHandQty))   	
--Insert Into Temp_Debug Values('28 - @OnHand',Convert(Varchar(100),@OnHand))   
--Insert Into Temp_Debug Values('28 - @SoldQty',Convert(Varchar(100),@SoldQty))   	
	
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID

--Insert Into Temp_Debug Values('28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
	
--Insert Into Temp_Debug Values('@IsConsignmentStock',Convert(Varchar(100),@IsConsignmentStock))   	

	IF @IsConsignmentStock = 1
	BEGIN

		SELECT 
			m.AO_GRV_ID, 
			d.AO_GRV_Details_ID, 			
			m.AO_Suppliers_ID,
    		m.AO_Orders_ID,
    		m.Date_Received,
    		m.Delivery_Note_Number, 
    		m.Supplier_Reference,
    		d.Qty,
    		d.Qty_Left,
    		d.Unit_Price,
    		d.Trade_Discount_Amount,
    		d.Rebate_Discount_Amount,
    		d.Other_Discount_Amount,
    		d.Net_Amount,
    		d.Tax_Amount,
    		d.Total_Cost,
    		d.Sys_AW_Tax_Codes_ID	
		FROM AO_GRV m
			INNER JOIN AO_GRV_Details d
				ON m.AO_GRV_ID = d.AO_GRV_ID
		WHERE d.AP_Products_ID = @ProductID
		AND m.Sys_AW_Transaction_Types_ID = 31
		AND d.Qty_Left > 0
		ORDER BY m.Date_Received ASC, AO_GRV_Details_ID ASC
		
		DECLARE GetDataGRV CURSOR
		FOR
		SELECT 
			m.AO_GRV_ID, 
			d.AO_GRV_Details_ID, 			
			m.AO_Suppliers_ID,
    		m.AO_Orders_ID,
    		m.Date_Received,
    		m.Delivery_Note_Number, 
    		m.Supplier_Reference,
    		d.Qty,
    		d.Qty_Left,
    		d.Unit_Price,
    		d.Trade_Discount_Amount,
    		d.Rebate_Discount_Amount,
    		d.Other_Discount_Amount,
    		d.Net_Amount,
    		d.Tax_Amount,
    		d.Total_Cost,
    		d.Sys_AW_Tax_Codes_ID	
		FROM AO_GRV m
			INNER JOIN AO_GRV_Details d
				ON m.AO_GRV_ID = d.AO_GRV_ID
		WHERE d.AP_Products_ID = @ProductID
		AND m.Sys_AW_Transaction_Types_ID = 31
		AND d.Qty_Left > 0
		ORDER BY m.Date_Received ASC, AO_GRV_Details_ID ASC
		
		OPEN GetDataGRV
		FETCH NEXT FROM GetDataGRV INTO 
				@Con_AO_GRV_ID, 
				@Con_AO_GRV_Details_ID, 
				@Suppliers_ID,
				@Order_ID,
				@DateReceived,
				@DelNoteNo,
				@SupplierRef,
				@Det_Qty,
				@Qty_Left,
	  			@Det_Unit_Price,
    			@Det_Trade_Discount_Amount,
    			@Det_Rebate_Discount_Amount,
    			@Det_Other_Discount_Amount,
    			@Det_Net_Amount,
    			@Det_Tax_Amount,
    			@Det_Total_Cost,
    			@Det_Tax_Code_ID
							
		--Select * From AO_GRV_Details		
		WHILE @@Fetch_Status = 0
		BEGIN
		
--Insert Into Temp_Debug Values('28-1 - @Qty_Left',Convert(Varchar(100),@Qty_Left))   	
--Insert Into Temp_Debug Values('28-1 - @ConsignmentGRVQty',Convert(Varchar(100),@ConsignmentGRVQty))   	
--Insert Into Temp_Debug Values('28-1 - @CurrentConsignmentGRVQty',Convert(Varchar(100),@CurrentConsignmentGRVQty))   	
--Insert Into Temp_Debug Values('28-1 - @ConsignmentGRVed',Convert(Varchar(100),@ConsignmentGRVed))   	
--Insert Into Temp_Debug Values('28-1 - @GRV_Qty',Convert(Varchar(100),@GRV_Qty))   	
--Insert Into Temp_Debug Values('28-1 - @Det_Unit_Price',Convert(Varchar(100),@Det_Unit_Price)) 
--Insert Into Temp_Debug Values('28-1 - @Con_AO_GRV_ID',Convert(Varchar(100),@Con_AO_GRV_ID)) 	
		
			IF @Qty_Left > @ConsignmentGRVQty
			BEGIN
				SET @CurrentConsignmentGRVQty = @ConsignmentGRVQty
				SET @ConsignmentGRVed = @ConsignmentGRVed + @ConsignmentGRVQty
			END
			ELSE
			BEGIN
				SET @CurrentConsignmentGRVQty = @Qty_Left
				SET @ConsignmentGRVed = @ConsignmentGRVQty + @Qty_Left		
			END	
			
			SET @GRV_Qty = @CurrentConsignmentGRVQty
			SET @GRV_Unit_Price = @Det_Unit_Price
			
			SET @GRV_Trade_Discount_Amount = 0
			SET @GRV_Rebate_Discount_Amount = 0
			SET @GRV_Other_Discount_Amount = 0
			
--Insert Into Temp_Debug Values('28-2 - @Qty_Left',Convert(Varchar(100),@Qty_Left))   	
--Insert Into Temp_Debug Values('28-2 - @ConsignmentGRVQty',Convert(Varchar(100),@ConsignmentGRVQty))   	
--Insert Into Temp_Debug Values('28-2 - @CurrentConsignmentGRVQty',Convert(Varchar(100),@CurrentConsignmentGRVQty))   	
--Insert Into Temp_Debug Values('28-2 - @ConsignmentGRVed',Convert(Varchar(100),@ConsignmentGRVed))   	
--Insert Into Temp_Debug Values('28-2 - @GRV_Qty',Convert(Varchar(100),@GRV_Qty))   	

IF @GRV_Qty <> 0
BEGIN
			
			IF @Det_Qty <> 0 And @GRV_Qty <> 0
			BEGIN
				SET @GRV_Trade_Discount_Amount = (Convert(Decimal(12,3),@Det_Trade_Discount_Amount) / @Det_Qty) * @GRV_Qty
    			SET @GRV_Rebate_Discount_Amount = (Convert(Decimal(12,3),@Det_Rebate_Discount_Amount) / @Det_Qty) * @GRV_Qty
    			SET @GRV_Other_Discount_Amount = (Convert(Decimal(12,3),@Det_Other_Discount_Amount) / @Det_Qty) * @GRV_Qty
    		END
    		
    		SET @GRV_Net_Amount = (@GRV_Qty * Convert(Decimal(12,3),@GRV_Unit_Price) ) 
    																				- Convert(Decimal(12,3),@GRV_Trade_Discount_Amount)
    																				- Convert(Decimal(12,3),@GRV_Rebate_Discount_Amount)
    																				- Convert(Decimal(12,3),@GRV_Other_Discount_Amount)
    		
    		SET @GRV_Total_Cost = Convert(Decimal(12,3),@GRV_Net_Amount) * 1.14
    		SET @GRV_Tax_Amount = Convert(Decimal(12,3),@GRV_Total_Cost) - Convert(Decimal(12,3),@GRV_Net_Amount)    		
    		    		
    		SET @GRV_DateReceived = GETDATE() --Date received is set to today. If original date received is used it will affect the Supplier Ageing
		
		    SET @Comment = 'GRV ' + CONVERT(Varchar(16),@AO_GRV_ID)
		
			SET @Slu_AW_Months_ID = DATEPART(mm, @GRV_DateReceived)
			SET @Year = DATEPART(yy, @GRV_DateReceived)

			SELECT @Slu_AW_Years_ID = Slu_AW_Years_ID
			FROM Slu_AW_Years
			WHERE [Description] = CONVERT(varchar(10), @Year)

			IF @Slu_AW_Months_ID = 0 OR @Slu_AW_Years_ID = 0
			BEGIN
				SELECT	@Slu_AW_Months_ID = Slu_AW_Months_ID,
						@Slu_AW_Years_ID = Slu_AW_Years_ID
				FROM AW_User_Companies
				WHERE AW_User_Companies_ID = @CompanyID
			END

			--34 - Consignment Sold Begin
			SET @GRV_Net_Amount = @GRV_Net_Amount * -1
			SET @GRV_Tax_Amount = @GRV_Tax_Amount * -1
			SET @GRV_Total_Cost = @GRV_Total_Cost * -1
			SET @GRV_Trade_Discount_Amount = @GRV_Trade_Discount_Amount * -1
			SET @GRV_Rebate_Discount_Amount = @GRV_Rebate_Discount_Amount * -1
			SET @GRV_Other_Discount_Amount = @GRV_Other_Discount_Amount * -1
			SET @GRV_Qty = @GRV_Qty * -1

			EXEC @AO_GRV_ID = sp_AO_Insert_GRV    
    			@Suppliers_ID,
    			34, --@AW_Transaction_Type int,
    			@Order_ID,
    			@GRV_DateReceived,
    			@DelNoteNo,
    			@SupplierRef,
    			@GRV_Trade_Discount_Amount,
    			@GRV_Rebate_Discount_Amount,
    			@GRV_Other_Discount_Amount,
    			@GRV_Net_Amount,
    			@GRV_Tax_Amount,
    			@GRV_Total_Cost,
    			@Con_AO_GRV_ID,
    			@UserID,
    			@CompanyID        
    
--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
--Insert Into Temp_Debug Values('(34 Begin)28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID
--Insert Into Temp_Debug Values('(34 Begin)28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
--Insert Into Temp_Debug Values('28 - @GRV_Qty',Convert(Varchar(100),@GRV_Qty))   	
--Insert Into Temp_Debug Values('28 - @GRV_Unit_Price',Convert(Varchar(100),@GRV_Unit_Price))   	
    
			EXEC @AO_GRV_Details_ID = sp_AO_Insert_OR_Update_GRV_Detail   
    			0, --@AO_Order_Details_ID int = 0, Order delt with when the consignment stock came in
    			@AO_GRV_ID,
    			@ProductID,
    			@GRV_Qty,
    			@GRV_Unit_Price, --@Unit_Last_Cost money,
    			@GRV_Trade_Discount_Amount,
    			@GRV_Rebate_Discount_Amount,
    			@GRV_Other_Discount_Amount,
    			@GRV_Net_Amount,
    			@Det_Tax_Code_ID,
    			@GRV_Tax_Amount,
    			@GRV_Total_Cost,
    			@Con_AO_GRV_Details_ID,
    			@UserID,
    			@CompanyID			

--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
--Insert Into Temp_Debug Values('(34 End)28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID
--Insert Into Temp_Debug Values('(34 End)28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
		
			EXEC sp_AO_Insert_AO_Transactions
			   	@Suppliers_ID,
    			@SupplierRef,
    			34, --@Transaction_Type tinyint,		
    			@DelNoteNo, --@Invoice_No varchar(20),
    			@GRV_DateReceived, --@Invoice_Date datetime,
    			@AO_GRV_ID,
    			@GRV_Trade_Discount_Amount,
    			@GRV_Rebate_Discount_Amount,
    			@GRV_Other_Discount_Amount,
    			@GRV_Net_Amount,
    			@GRV_Tax_Amount,
    			@GRV_Total_Cost,
    			@Slu_AW_Months_ID,
    			@Slu_AW_Years_ID,
    			@UserID,
    			@CompanyID,
				0, --@GLAccountID int = 0,
				@Comment -- GRV + @AO_GRV_ID
	
			--34 - Consignment Sold End
			
			--19 - GRV Begin
			SET @GRV_Net_Amount = @GRV_Net_Amount * -1
			SET @GRV_Tax_Amount = @GRV_Tax_Amount * -1
			SET @GRV_Total_Cost = @GRV_Total_Cost * -1
			SET @GRV_Trade_Discount_Amount = @GRV_Trade_Discount_Amount * -1
			SET @GRV_Rebate_Discount_Amount = @GRV_Rebate_Discount_Amount * -1
			SET @GRV_Other_Discount_Amount = @GRV_Other_Discount_Amount * -1
			SET @GRV_Qty = @GRV_Qty * -1		
		
			EXEC @AO_GRV_ID = sp_AO_Insert_GRV    
    			@Suppliers_ID,
    			19, --@AW_Transaction_Type int,
    			@Order_ID,
    			@GRV_DateReceived,
    			@DelNoteNo,
    			@SupplierRef,
    			@GRV_Trade_Discount_Amount,
    			@GRV_Rebate_Discount_Amount,
    			@GRV_Other_Discount_Amount,
    			@GRV_Net_Amount,
    			@GRV_Tax_Amount,
    			@GRV_Total_Cost,
    			@Con_AO_GRV_ID,
    			@UserID,
    			@CompanyID    
    			    
--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
--Insert Into Temp_Debug Values('(19 Begin)28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID
--Insert Into Temp_Debug Values('(19 Begin)28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
    
			EXEC @AO_GRV_Details_ID = sp_AO_Insert_OR_Update_GRV_Detail   
    			0, --@AO_Order_Details_ID int = 0, Order delt with when the consignment stock came in
    			@AO_GRV_ID,
    			@ProductID,
    			@GRV_Qty,
    			@GRV_Unit_Price, --@Unit_Last_Cost money,
    			@GRV_Trade_Discount_Amount,
    			@GRV_Rebate_Discount_Amount,
    			@GRV_Other_Discount_Amount,
    			@GRV_Net_Amount,
    			@Det_Tax_Code_ID,
    			@GRV_Tax_Amount,
    			@GRV_Total_Cost,
    			@Con_AO_GRV_Details_ID,
    			@UserID,
    			@CompanyID
    			
--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
--Insert Into Temp_Debug Values('(19 End)28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID
--Insert Into Temp_Debug Values('(19 End)28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	

		
			EXEC sp_AO_Insert_AO_Transactions
			   	@Suppliers_ID,
    			@SupplierRef,
    			8, --@Transaction_Type tinyint,		
    			@DelNoteNo, --@Invoice_No varchar(20),
    			@GRV_DateReceived, --@Invoice_Date datetime,
    			@AO_GRV_ID,
    			@GRV_Trade_Discount_Amount,
    			@GRV_Rebate_Discount_Amount,
    			@GRV_Other_Discount_Amount,
    			@GRV_Net_Amount,
    			@GRV_Tax_Amount,
    			@GRV_Total_Cost,
    			@Slu_AW_Months_ID,
    			@Slu_AW_Years_ID,
    			@UserID,
    			@CompanyID,
				0, --@GLAccountID int = 0,
				@Comment -- GRV + @AO_GRV_ID
        
        	UPDATE AO_GRV_Details
        	SET Qty_Sold = Qty_Sold + @GRV_Qty,
        		Qty_Left = Qty_Left - @GRV_Qty
        	WHERE AO_GRV_Details_ID = Convert(Int,@Con_AO_GRV_Details_ID)   
        	   	
        	--19 - GRV End
        	SET @ConsignmentGRVQty = @ConsignmentGRVQty - @GRV_Qty
END        		
			FETCH NEXT FROM GetDataGRV INTO 
					@Con_AO_GRV_ID, 
					@Con_AO_GRV_Details_ID, 
					@Suppliers_ID,
					@Order_ID,
					@DateReceived,
					@DelNoteNo,
					@SupplierRef,
					@Det_Qty,
					@Qty_Left,
	  				@Det_Unit_Price,
    				@Det_Trade_Discount_Amount,
    				@Det_Rebate_Discount_Amount,
    				@Det_Other_Discount_Amount,
    				@Det_Net_Amount,
    				@Det_Tax_Amount,
    				@Det_Total_Cost,
    				@Det_Tax_Code_ID


		END
		CLOSE GetDataGRV
		DEALLOCATE GetDataGRV
	
	END
	
--	RETURN @IsConsignmentStock

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Consignment_Check
--Purpose       :Checks to see if product sold was consignment stock
--Functionality :SELECT 
--Parameters    :@AS_Transaction_Details_ID, @UserID, @CompanyID
--Date          :2015/04/10
--Version		:V6.2
--Authors       :RL
--MODS          :
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Transaction_Detail_Consignment_Check]
    (
    	@ProductID				int,
    	@SoldQty				decimal(9,3),
    	@UserID					int,
		@CompanyID				int,
		@IsConsignmentStock		int Output    	
    )

AS
	DECLARE @ConsignmentStockQty		decimal(9,3),
			@Current_OnHandQty			decimal(9,3),
			@ConsignmentGRVQty			decimal(9,3),
			@OnHand						decimal(9,3),
			@Qty_Left					decimal(9,3),
			@ConsignmentGRVed			decimal(9,3),
			@CurrentConsignmentGRVQty	decimal(9,3)
			
	SET @ConsignmentGRVQty = 0
	SET @IsConsignmentStock = 0
	SET @ConsignmentGRVed = 0
	SET @CurrentConsignmentGRVQty = 0
	
	SELECT @ConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)

	SELECT  @Current_OnHandQty = On_Hand - @ConsignmentStockQty,
			@OnHand = On_Hand
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID
	
	IF @Current_OnHandQty < 0
		SET @Current_OnHandQty = 0
		
	IF @ConsignmentStockQty <> 0
	BEGIN
		IF @Current_OnHandQty < @SoldQty
		BEGIN
			SET @ConsignmentGRVQty = @SoldQty - @Current_OnHandQty
			IF @ConsignmentGRVQty > @ConsignmentStockQty
				SET @ConsignmentGRVQty = @ConsignmentStockQty
				
			SET @IsConsignmentStock = 1	
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (Periodic Billing)
--              :    also UPDATES AP_Products: On_Hand, Last_Sale_Date
--              :         UPDATES AS_Transactions: Total_Cost
--Functionality :AS_Transactions types with Detail only: 3, 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/01/20
--Authors       :TB
--MODS          :
--V6.2 RL	2016-06-26	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_Transaction_Detail_Insert]
    (
		@DocumentID int,
		@TranTypeID int,
		@ProductID int,
        @CostMethod tinyint,
		@Qty decimal(9,3),
		@UnitPrice money,
		@Amount money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
            @Cost money,
            @TotalCost money,
    		@OriginalPrice money,
        	@OppositeQty decimal(9,3)


    SET @DocumentDetailsID = 0

    ---------------------------------------------------------------------------
    --> Set Product Cost
    ---------------------------------------------------------------------------
    IF @CostMethod = 0        --Average
        BEGIN
            SELECT @Cost = Average_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 1        --Last
        BEGIN
            SELECT @Cost = Last_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 2        --Standard
        BEGIN
            SELECT @Cost = Standard_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END

    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
    SET @TotalCost = ROUND(@Qty * @Cost, 2)

    UPDATE AS_Transactions
    SET Total_Cost = @TotalCost
    WHERE AS_Transactions_ID = @DocumentID

    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
	IF @TranTypeID = 3    --> Invoice
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate()
            WHERE AP_Products_ID = @ProductID
            
			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,			--@ProductID int,
					1,					--@ProductBinID int,
					@OppositeQty,		--@Qty decimal(9,3)
					'SALE',				--@Source varchar(10),
					0,					--@Batch_No
					@UserID,			--@UserID int,
					@CompanyID			--@CompanyID int
			END	
            
		END

	ELSE
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty
            WHERE AP_Products_ID = @ProductID
            
			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,			--@ProductID int,
					1,					--@ProductBinID int,
					@OppositeQty,		--@Qty decimal(9,3)
					'CN',				--@Source varchar(10),
					0,					--@Batch_No
					@UserID,			--@UserID int,
					@CompanyID			--@CompanyID int
			END	
            
		END


    ---------------------------------------------------------------------------

	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Tax_Amount,
			Extended_Amount,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@Cost,
			@UnitPrice,
			@OriginalPrice,
			@Tax,
			@Total,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()



RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Insert_Cons
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS for consignment stock
--              :    also UPDATES AP_Products: On_Hand, Last_Sale_Date
--              :         UPDATES AS_Transactions: Total_Cost
--Functionality :AS_Transactions types with Detail only: 34, 35
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2015-05-21
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_Transaction_Detail_Insert_Cons]
    (
		@DocumentID		int,
		@TranTypeID		int,
		@Qty			decimal(9,3),
		@OriginalPrice	money,
		@UnitPrice		money,
		@Discount		money,
		@Tax			money,
        @Total			money,
        @DatePosted		datetime,
        @ConsignmentID	int,
		@UserID			int,
		@CompanyID		int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID		int,
            @Cost					money,
            @TotalCost				money,    		
    		@ProductID				int,
			@IsConsignmentStock		int,
			@Oppisite_Qty			decimal(9,3),
			@ProductBinID			int,
			@ProductsQty			decimal(9,3),		

			@H_Total_Cost				money,
			@H_Amount					money,
			@H_Total_Tax_Amount			money,
			@H_Total_Discount_Amount	money,
			@H_Total_Amount				money

    SET @DocumentDetailsID = 0

	SELECT @Cost = Unit_Cost,
		   @ProductID = AP_Products_ID,
		   @ProductBinID = Lup_AP_Product_Bins_ID
	FROM AS_Transaction_Details
	WHERE AS_Transaction_Details_ID = @ConsignmentID
 
	IF ( (@TranTypeID = 34))	--Consignment Sold
	BEGIN
		--SET @IsConsignmentStock = 0
		--EXEC sp_AS_Transaction_Detail_Consignment_Check @ProductID, @Qty, @UserID, @CompanyID, @IsConsignmentStock OUTPUT	
		
		--IF @IsConsignmentStock = 1
		--BEGIN
		
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID

--Insert Into Temp_Debug Values('40 - @ConsignmentID',Convert(Varchar(100),@ConsignmentID))   	
--Insert Into Temp_Debug Values('40 - @Qty',Convert(Varchar(100),@Qty))   	
--Insert Into Temp_Debug Values('40 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
		
			UPDATE AP_Products
			SET On_Hand = On_Hand + @Qty,
			[User_ID] = @UserID
			WHERE AP_Products_ID = @ProductID
			
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				--SELECT @Oppisite_Qty = @Qty
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,							--@ProductID int,
					@ProductBinID,						--@ProductBinID int,
					@Qty,								--@Qty decimal(9,3)
					'Cons Sale',						--@Source varchar(10),
					0,									--@Batch_No
					@UserID,							--@UserID int,
					@CompanyID							--@CompanyID int			    	
			END	
			
		--END			
				    
		SET @TotalCost = ( ROUND(@Qty * @Cost, 2) * -1)
		SET @Discount = @Discount

		--UPDATE AS_Transactions
		--SET Total_Cost = ISNULL(Total_Cost, 0) + @TotalCost
		--WHERE AS_Transactions_ID = @DocumentID				

	END
	ELSE
	BEGIN --Consignment Returned

		UPDATE AP_Products
		SET On_Hand = On_Hand + @Qty,
		[User_ID] = @UserID
		WHERE AP_Products_ID = @ProductID
    
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SELECT @Oppisite_Qty = @Qty
			
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,							--@ProductID int,
				@ProductBinID,						--@ProductBinID int,
				@Qty,								--@Qty decimal(9,3)
				'ConsReturn',						--@Source varchar(10),
				0,									--@Batch_No
				@UserID,							--@UserID int,
				@CompanyID							--@CompanyID int			    	
		END	
		
		SET @TotalCost = ( ROUND(@Qty * @Cost, 2) * -1)

		--UPDATE AS_Transactions
		--SET Total_Cost = ISNULL(Total_Cost, 0) + @TotalCost
		--WHERE AS_Transactions_ID = @DocumentID	
	END

	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Discount_Amount,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID,
			Lup_AP_Product_Bins_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			(@Qty * -1),
			@Cost,
			@UnitPrice,
			@OriginalPrice,
			@Discount,
			(@Tax * -1),
			(@Total * -1),
            '',
            '',
            '',
            '',
            @DatePosted,
			@UserID,
			@CompanyID,
			@ProductBinID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

	--V6.3 RL 2017-05-13 Recalc Header Totals
	IF	( 
			@TranTypeID = 1 Or		--Quote
			@TranTypeID = 2 Or		--Job Card
			@TranTypeID = 3 Or		--Tax Invoice
			@TranTypeID = 4 Or		--Tax Credit Note
			@TranTypeID = 13 Or		--Pro Forma
			@TranTypeID = 16 Or		--Sales Order
			@TranTypeID = 23 Or		--Stock Transfer
			@TranTypeID = 33 Or		--Consignment Note
			@TranTypeID = 34 Or		--Consignment Sold
			@TranTypeID = 35			--Consignment Returned
		)
	BEGIN
		
		SELECT @H_Total_Cost = SUM((Quantity + Back_Order) * Unit_Cost),
			   @H_Total_Discount_Amount = SUM(Discount_Amount),
			   @H_Amount = SUM(Extended_Amount - Tax_Amount),
			   @H_Total_Tax_Amount = SUM(Tax_Amount),
			   @H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
            Total_Discount_Amount = @H_Total_Discount_Amount,
            Amount = @H_Amount,
            Total_Tax_Amount = @H_Total_Tax_Amount,
            Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @DocumentID
		
	END

	INSERT INTO AS_Transaction_Details_Consignment
	(		
		AS_Transaction_Details_ID, --Sys_AW_Transaction_Types_ID 33 Consignment Stock Note
		Consignment_ID,
		Sys_AW_Transaction_Types_ID,
		Quantity,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID	
	)
	VALUES
	(
		@ConsignmentID,
		@DocumentDetailsID,
		@TranTypeID,
		(@Qty),
		@DatePosted,
		@UserID,
		@CompanyID
	)

RETURN @DocumentDetailsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Insert_Update
--Purpose       :Called from POS when a transaction is registered
--              :NB PARAMETER NAMES MUST BE THE SAME AS THE FIELDS IN THE VIEW
--              :vw_AS_Transaction_Details, except for the @Choice
--Date          : 2001/6/25
--Authors       :TB
--Version       :1.0.0
--MODS          :15/02/04 - Replaced d.Item_Number with NEW d.AP_Promotion_Products_ID
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AS_Transaction_Detail_Insert_Update
    (
        @Choice varchar(6),
        @Description varchar(50), 
        @Code varchar(20), 
        @Qty decimal(9,3), 
        @Cost money, 
        @Price money, 
        @OriginalPrice money, 
        @Discount money, 
        @Tax money, 
        @Amount money, 
        @Commission money, 
        @Item int, 
        @ProductID int, 
        @TransactionID int,
        @Date datetime, 
        @UserID int, 
        @CompanyID int,
        @ID int OUTPUT,
        @TransactionTypeID int
    )

AS

SET NOCOUNT ON

	IF @Choice <> 'Update'
		BEGIN
			INSERT AS_Transaction_Details 
			   (  Quantity ,
			      Unit_Cost,
			      Unit_Price ,
			      Original_Price ,
			      Discount_Amount ,
			      Tax_Amount ,
			      Extended_Amount ,
			      Commission_Amount ,
			      AP_Promotion_Products_ID ,
			      AP_Products_ID ,
			      AS_Transactions_ID ,
			      Date_Captured ,
			      User_ID ,
			      AW_User_Companies_ID)
			   VALUES
			   (  @Qty,
			      @Cost,
			      @Price,
			      @OriginalPrice,
			      @Discount,
			      @Tax,
			      @Amount,
			      @Commission,
			      @Item,
			      @ProductID,
			      @TransactionID,
			      @Date,
			      @UserID,
			      @CompanyID)
			SELECT @ID = Scope_Identity()
		
		
		-- 	SELECT @TransactionType = Sys_AW_Transaction_Types_ID 
		-- 	FROM  AS_Transactions
		-- 	WHERE AS_Transactions_ID = @TransactionID
			
			IF @TransactionTypeID = 3 --Invoice
				UPDATE AP_Products 
				SET ON_Hand = On_Hand - @qty, 
					Last_Sale_Date = getdate() 
				WHERE AP_Products_ID = @ProductID
			ELSE
			IF @TransactionTypeID = 4 --Refund
				UPDATE AP_Products SET ON_Hand = On_Hand + @qty
				WHERE AP_Products_ID = @ProductID
			ELSE
			IF @TransactionTypeID = 1 --Quote
				UPDATE AP_Products SET Quote_Reserved = Quote_Reserved + @qty
				WHERE AP_Products_ID = @ProductID
			ELSE
			IF @TransactionTypeID = 2 --Job
				UPDATE AP_Products SET Job_Reserved = Job_Reserved + @qty   
				WHERE AP_Products_ID = @ProductID
			ELSE
			IF @TransactionTypeID = 16 --Sales Order
				UPDATE AP_Products SET Sales_Order_Reserved = Sales_Order_Reserved + @qty
				WHERE AP_Products_ID = @ProductID
			ELSE
			IF @TransactionTypeID = 17 --Sales Order Reversal
				UPDATE AP_Products SET Sales_Order_Reserved = Sales_Order_Reserved - @qty
				WHERE AP_Products_ID = @ProductID
		END
	ELSE
		BEGIN
			IF @TransactionTypeID = 0 or @TransactionTypeID = 13 or @TransactionTypeID is null
				UPDATE AS_Transaction_Details SET
				      Quantity = @Qty,
				      Unit_Cost = @Cost,
				      Unit_Price = @Price,
				      Original_Price = @OriginalPrice,
				      Discount_Amount = @Discount,
				      Tax_Amount = @Tax,	
				      Extended_Amount = @Amount,
				      Commission_Amount = @Commission,
				      AP_Promotion_Products_ID = @Item,
				      AP_Products_ID = @ProductID,
				      AS_Transactions_ID = @TransactionID,
				      Date_Captured = @Date,
				      User_ID = @UserID,
				      AW_User_Companies_ID = @CompanyID
				WHERE AS_Transaction_Details_ID = @ID
		  
			ELSE
				RAISERROR   ('Only Pro Formas can be updated',    16, 1)
		END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : Selects the Transaction Details for POS
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/6/25
--Authors       : GL
--Version       : 1
-------------------------------------------------------------------------------
CREATE  PROCEDURE sp_AS_Transaction_Details_Select
	@CompanyID int,
	@UserID int,
	@TransactionID int 
AS
SELECT * FROM vw_AS_Transaction_Details
	WHERE TransactionID = @TransactionID 
		 AND CompanyID = @CompanyID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Header_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTIONS (Periodic Billing)
--Functionality :Financial AS_Transactions types only: 3, 4, 5, 7, 15, 18, 21, 22
--              :NB NB - SIGN REVERSAL DONE IN UI
--Date          :2011/01/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AS_Transaction_Header_Insert
    (
        @TranDate datetime,
    	@CustomerID int,
    	@TranTypeID tinyint,
        @RefNo varchar(19),
        @Amount money,
        @Tax money,
        @Total money,
    	@GLAccountID int,
    	@Comment varchar(20),
    	@Notes varchar(250),
        @DatePosted datetime,
    	@UserID int,
    	@CompanyID int
    )

AS

	DECLARE @DocumentID int,
            @CommentID int


    IF @TranTypeID = 3 OR @TranTypeID = 4
        BEGIN
            IF RTRIM(LTRIM(@Notes)) <> ''
                BEGIN
                    EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Notes
                END
        END


	IF NOT @TranTypeID = 5
        BEGIN
            SET @GLAccountID = NULL
        END


	INSERT AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Amount,
            Total_Tax_Amount,
            Total_Amount,
            Transaction_Date,
            Comment,
            AW_Comments_ID,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
		)
	VALUES
		(
            @CustomerID,
            @GLAccountID,
            @RefNo,
            @Amount,
            @Tax,
            @Total,
            @TranDate,
            @Comment,
            @CommentID,
            @UserID,
            @TranTypeID,
            @DatePosted,
            @UserID,
            @CompanyID
		)

    SELECT @DocumentID = Scope_Identity()


    --> Update the Customer Account Balance
	UPDATE AC_Customers
    SET Account_Balance = Account_Balance + @Total
    WHERE AC_Customers_ID = @CustomerID


    ---------------------------------------------------------------------------
    --> UPDATE PAYMENTS
    ---------------------------------------------------------------------------
	IF @TranTypeID = 21 OR @TranTypeID = 22
		BEGIN
        	INSERT AS_Transaction_Payments
                (
            		Payor_Name,
            		Card_Expiry_Date,
            		Card_Number,
            		Authorisation_Number,
            		Amount,
            		Sys_AW_Payment_Methods_ID,
            		Slu_AS_Card_Institutions_ID,
            		AS_Transactions_ID,
            		Date_Captured,
            		[User_ID],
            		AW_User_Companies_ID
                )
        	VALUES
                (
            		'Periodic Billing Payment',
            		'',
            		'',
            		'',
            		@Total,
            		6,
            		1,
            		@DocumentID,
            		@DatePosted ,
            		@UserID,
            		@CompanyID
                )
		END



RETURN @DocumentID

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Header_Insert_Cons
--Purpose       :INSERTS CUSTOMER TRANSACTIONS for consignment stock
--Functionality :Financial AS_Transactions types only: 34, 35
--              :NB NB - SIGN REVERSAL
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transaction_Header_Insert_Cons]
    (
        @TranDate		datetime,
    	@CustomerID		int,
    	@TranTypeID		tinyint,
        @RefNo			varchar(19),
        @TotalCost		money,
        @Amount			money,
        @Discount		money,
        @Tax			money,
        @Total			money,
    	@GLAccountID	int,
    	@Comment		varchar(20),
    	@Order_No		varchar(15),
    	@Notes			varchar(500),
        @DatePosted		datetime,
        @Reps_ID		int,
    	@UserID			int,
    	@CompanyID		int
    )
AS

	DECLARE @DocumentID int,
            @CommentID int

    IF @TranTypeID = 34 OR @TranTypeID = 35 OR @TranTypeID = 3
        BEGIN
            IF RTRIM(LTRIM(@Notes)) <> ''
                BEGIN
                    EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Notes
                END
        END

    SET @GLAccountID = NULL

	IF @TranTypeID <> 3
	BEGIN
		SET @TotalCost = @TotalCost * -1
		SET @Amount = @Amount * -1
		SET @Tax = @Tax * -1
		SET @Total = @Total * -1
	END

	INSERT AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Total_Cost,
            Amount,
            Total_Tax_Amount,
            Total_Discount_Amount,
            Total_Amount,
            Transaction_Date,
            Customer_Reference,
            Comment,
            AW_Comments_ID,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            Lup_AS_Reps_ID,
            [User_ID],
            AW_User_Companies_ID
		)			
	VALUES
		(
            @CustomerID,
            @GLAccountID,
            @RefNo,
            @TotalCost,
            @Amount,
            @Tax,
            @Discount,
            @Total,
            @TranDate,
            @Order_No,
            @Comment,
            @CommentID,
            @UserID,
            @TranTypeID,
            @DatePosted,
            @Reps_ID,
            @UserID,
            @CompanyID
		)

    SELECT @DocumentID = Scope_Identity()

	IF @TranTypeID = 3
	BEGIN
		--> Update the Customer Account Balance
		UPDATE AC_Customers
		SET Account_Balance = Account_Balance + @Total
		WHERE AC_Customers_ID = @CustomerID
	END

RETURN @DocumentID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--*** NOT USED ***
-------------------------------------------------------------------------------
--Description   :Insert/Update Transaction
--              :NB THE PARAMETER NAMES HAS TO BE THE SAME AS IN THE VIEW 
--              :vw_POS_Transaction_eaders_Select
--              :NB - Only a Pro Forma can be updated
--Returns	    :New Inserted ID
--Purpose       :
--Functionality : 
--Parameters    : 
--Date          :2002/01/13
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
--	1	 - 	Quote
--	2	 - 	Job Card
--	3	 - 	Invoice
--	4	 - 	Refund
--	5	 - 	Journal
--	6	 - 	Delivery Note
--	7	 - 	Payment
--	8	 - 	Purchase Invoice
--	9	 - 	Purchase Refund
--	10	 - 	Purchase Journal
--	11	 - 	Purchase Delivery Note
--	12	 - 	Supplier Payment
--	13	 - 	Pro Forma
--	14	 - 	Purchase Order
--	15	 - 	Customer Interest Journal
--  16   -  Sales Order
--  17   -  Sales Order Reversal
--	18	 -	Settlement Discount
-------------------------------------------------------------------------------------------------

CREATE    Procedure sp_AS_Transaction_Header_Insert_Update
	(
    	@No varchar(19) = '',
		@Amount money = 0,
		@Payment money = 0,
		@Discount money = 0,
		@Tax money = 0,
		@Date datetime = null,
		@Expiry datetime = null,
		@Ver smallint =0,
		@CustomerID int = null ,
		@Comment varchar(500) = null ,
		@TypeID tinyint =13,
		@IndID int = null,
		@StoreID int = null,
		@StationID int =null,
		@TillID int =null,
		@CashierID int=null,
		@RepID int=null,
		@CurrencyID int=null,
		@CancelUserID int=null,
		@CancelDate smalldatetime =null,
		@CashUp smalldatetime =null,
		@DayEnd smallDateTime =null,
		@Transmit smalldatetime =null,
		@DateCaptured smalldatetime =null,
		@UserID int = 1,
		@CompanyID int = 1,
		@OldTypeID int =null,
		@ID int = Null OUTPUT
    )

AS

SET NOCOUNT ON

	DECLARE @InsUp char(1), @Bridge char(1), @NewTransactionNumber int
   	DECLARE @NewTransactionID int, @NoDiscountAmount money
	DECLARE @NewCommentID int

	SET @NoDiscountAmount = @Amount + @Tax - @Discount

----Pro Forma-------------------------------------------------------------------------------------------------------------
	IF @TypeID = 13
		BEGIN
			IF @OldTypeID = 13 AND NOT @ID IS Null
				SET @InsUp = 'U'
			ELSE
				BEGIN
					SET @InsUp = 'I'
					SET @OldTypeID = @TypeID
				END
		END
	ELSE
---Invoice--------------------------------------------------------------------------------------------------------------
	IF @TypeID = 3
		BEGIN
			IF @OldTypeID = 13 AND NOT @ID IS Null
				SET @InsUp = 'U'
			ELSE
				BEGIN
					SET @InsUp = 'I'
					SET @OldTypeID = @TypeID
					SET @Bridge = 'Y'
					UPDATE AC_Customers SET Account_Balance = Account_Balance - @Amount  WHERE AC_Customers_ID = @CustomerID
				END
		END
	ELSE
----Quote & Jobcard-------------------------------------------------------------------------------------------------------------
	IF @TypeID = 1 or @TypeID = 2 
		BEGIN
			IF @OldTypeID = 13 AND NOT @ID IS Null
				SET @InsUp = 'U'
			ELSE
				BEGIN
					SET @InsUp = 'I'
					SET @OldTypeID = @TypeID
					SET @Bridge= 'Y'
				END
		END
	ELSE
---Refund & Sales Order Reversal--------------------------------------------------------------------------------------------------------------
	IF @TypeID = 4 or  @TypeID = 17
		BEGIN
			IF @OldTypeID = 3 OR @OldTypeID = 13 OR @OldTypeID = 0 OR @OldTypeID Is Null
				BEGIN
					SET @Amount = -@Amount
					SET @Payment 	  = -@Payment
					SET @Discount    = -@Discount
					SET @Tax 		  = -@Tax
					SET @NoDiscountAmount = -@NoDiscountAmount
					UPDATE AC_Customers SET Account_Balance = Account_Balance - @Amount  WHERE AC_Customers_ID = @CustomerID
					IF @OldTypeID = 13 AND NOT @ID IS Null
						SET @InsUp = 'U'
					ELSE
						BEGIN
							SET @InsUp = 'I'
							SET @OldTypeID = @TypeID
							SET @Bridge= 'Y'
						END
				END
			ELSE
				BEGIN
					Raiserror ('This transaction can not be saved as a Refund', 16,1)
				END
		END
	ELSE
----Payment-------------------------------------------------------------------------------------------------------------
	IF @TypeID = 7 
		BEGIN
			IF NOT @ID IS Null and @ID > 0 
				SET @OldTypeID = @TypeID
			ELSE
				SET @InsUp = 'I'
				SET @NoDiscountAmount = @Amount
				SET @Payment = -@Payment
				UPDATE AC_Customers SET Account_Balance = Account_Balance - @Amount WHERE AC_Customers_ID = @CustomerID
		END
	ELSE
---Settlement Discount---------------------------------------------------------------------------------------------------------
	IF @TypeID = 18
		BEGIN
			SET @InsUp = 'I'
			SET @Bridge = 'Y'
			SET @Payment 	  = -@Payment
		END

       EXEC sp_AW_Get_Next_Transaction_Number @TypeID, @CompanyID, @NewTransactionNumber OUTPUT

	IF @InsUp = 'I'
		BEGIN
			INSERT AS_Transactions (	
				AC_Customers_ID,					Transaction_Number,					Total_Tax_Amount,
				Total_Discount_Amount,				Total_Amount,							Payment_Amount,
				Amount,								Transaction_Date,						Expiry_Date,
				Version_Number,					
--						Comments  ,								
				Sys_AW_Transaction_Types_ID ,
				Lup_AS_Marketing_Indicators_ID,	Lup_AW_Stores_ID,						Lup_AW_Workstations_ID,
				Lup_AS_Tills_ID,					Lup_AS_Cashiers_ID,					Lup_AS_Reps_ID,
				Slu_AW_Currencies_ID,				Old_Sys_AW_Transaction_Types_ID,	Cancelled_User_ID,
				Cancelled_DateTime,				Cashed_Up,								Day_End,
				Transmitted,							Date_Captured,							User_ID,
				AW_User_Companies_ID)
			VALUES
				(@CustomerID ,						@NewTransactionNumber,				@Tax ,
				@Discount,    						@Amount, 								@Payment ,
				@NoDiscountAmount,				@Date, 								@Expiry ,
				@Ver, 								
				--@Comments ,							
				@TypeID ,
				@IndID ,							@StoreID ,								@StationID ,
				@TillID ,							@CashierID ,							@RepID ,
				@CurrencyID ,						@OldTypeID ,							@CancelUserID ,
				@CancelDate ,						@CashUp ,								@DayEnd ,
				@Transmit, 							@DateCaptured ,						@UserID, 
				@CompanyID)

			SELECT @NewTransactionID = Scope_Identity()
			IF @Comment <> '' 
				BEGIN
					INSERT AW_Comments (Actor_ID, Sys_AT_Actor_Types_ID, Comment)
							VALUES            (@NewTransactionID, -7, @Comment)
					SELECT @NewCommentID = Scope_Identity()
					UPDATE AS_Transactions SET AW_Comments_ID = @NewCommentID WHERE AS_Transactions_ID = @NewTransactionID
				END

			IF @Bridge = 'Y'
				BEGIN
					INSERT AS_Transactions_Transactions (Source_AS_Transactions_ID,Destination_AS_Transactions_ID)
					VALUES (@ID, @NewTransactionID)
				END
			
			SET @ID = @NewTransactionID
		END
	ELSE
-------------------------------------------------------------------------------------------------------------
--Updates - Make sure something is not updated when it should not be
	IF @TypeID = 7 
		BEGIN
			SELECT @NewCommentID = AW_Comments_ID FROM AS_Transactions WHERE AS_Transactions_ID = @ID
			
			IF @Comment = '' AND NOT @NewCommentID IS NULL
				BEGIN
					DELETE FROM AW_Comments WHERE Actor_ID = @ID and Sys_AT_Actor_Types_ID = -7
					SET @NewCommentID = NULL
				END
			ELSE
			IF @Comment <> '' AND NOT @NewCommentID IS NULL
				BEGIN
					INSERT AW_Comments (Actor_ID, Sys_AT_Actor_Types_ID, Comment) 
							VALUES		(@ID, -7, @Comment)
					SELECT @NewCommentID = Scope_Identity()
				END
			ELSE
			IF @Comment <> '' AND @NewCommentID IS NULL
				BEGIN
					INSERT AW_Comments (Actor_ID, Sys_AT_Actor_Types_ID, Comment) 
							VALUES		(@ID, -7, @Comment)
					SELECT @NewCommentID = Scope_Identity()
				END
					

			UPDATE AS_Transactions SET 
				Payment_Amount	=	@Payment 	+ Payment_Amount,
				Version_Number	=	Version_Number + 1 	,
				AW_Comments_ID	=	@NewCommentID	,
				Date_Captured=	@Date 	,
				[User_ID]	=	@UserID 	
			WHERE AS_Transactions_ID = @ID

		END
	ELSE
		BEGIN

			SELECT @NewCommentID = AW_Comments_ID FROM AS_Transactions WHERE AS_Transactions_ID = @ID
			
			IF @Comment = '' AND NOT @NewCommentID IS NULL
				BEGIN
					DELETE FROM AW_Comments WHERE Actor_ID = @ID and Sys_AT_Actor_Types_ID = -7
					SET @NewCommentID = NULL
				END
			ELSE
			IF @Comment <> '' AND NOT @NewCommentID IS NULL
				BEGIN
					INSERT AW_Comments (Actor_ID, Sys_AT_Actor_Types_ID, Comment) 
							VALUES		(@ID, -7, @Comment)
					SELECT @NewCommentID = Scope_Identity()
				END
			ELSE
			IF @Comment <> '' AND @NewCommentID IS NULL
				BEGIN
					INSERT AW_Comments (Actor_ID, Sys_AT_Actor_Types_ID, Comment) 
							VALUES		(@ID, -7, @Comment)
					SELECT @NewCommentID = Scope_Identity()
				END


			UPDATE AS_Transactions
					SET AC_Customers_ID	=	@CustomerID 	,
						Transaction_Number	=	@No	,
						Total_Tax_Amount	=	@Tax 	,
						Total_Discount_Amount	=	@Discount    	,
						Total_Amount	=	@Amount 	,
						Payment_Amount	=	@Payment 	,
						Amount				= @NoDiscountAmount,
						Transaction_Date	=	@Date 	,
						Expiry_Date	=	@Expiry 	,
						Version_Number	=	@Ver 	,
						--Comments  	=	@Comments 	,
						Sys_AW_Transaction_Types_ID 	=	@TypeID 	,
						Lup_AS_Marketing_Indicators_ID	=	@IndID 	,
						Lup_AW_Stores_ID	=	@StoreID 	,
						Lup_AW_Workstations_ID	=	@StationID 	,
						Lup_AS_Tills_ID	=	@TillID 	,
						Lup_AS_Cashiers_ID	=	@CashierID 	,
						Lup_AS_Reps_ID	=	@RepID 	,
						Slu_AW_Currencies_ID	=	@CurrencyID 	,
						Old_Sys_AW_Transaction_Types_ID	=	@OldTypeID 	,
						Cancelled_User_ID	=	@CancelUserID 	,
						Cancelled_DateTime	=	@CancelDate 	,
						Cashed_Up	=	@CashUp 	,
						Day_End	=	@DayEnd 	,
						Transmitted	=	@Transmit 	,
						Date_Captured=	@Date 	,
						User_ID	=	@UserID 	,
						AW_User_Companies_ID	=	@CompanyID
			WHERE AS_Transactions_ID = @ID
		END
	RETURN @ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Header_Payment_Insert
--Purpose       :Back Office Customer Payments Insert
--              :    Updates Customer Account_Balance
--Date          :2002/01/21
--Authors       :TB
--Version       :1
--MODS:         :22/04/02 - Modified VALUES to Amount * -1 instead of -Amount
--              :24/05/02 - Update the Account Balance in AC_Customers
--              :11/06/02 - Removed empty Variant @ASTransactionsID causing rollback
--              :05/07/02 - Inserted new 'Customer BO Payment' type 21 & 22
--              :           inserted into Old_Sys_AW_Transaction_Types_ID
--              :03/10/02 - Implemented Sys_AW_Transaction_Types_ID type 21 & 22
--              :           into @TypeID from Customer Payments UI
--              :06/08/04 - Added Lup_AS_Cashiers_ID and insert @UserID to standarize
--2004.2.4      :08/06/05 - Cleaned up and removed superflous vars including last
--              :           input parameter @PayOption(tinyint) and other dead code
--2004.2.4.2    :24/11/05 - Added Lup_AS_Tills_ID field with default = 1 into
--              :           AS_Transactions INSERT to prevent inserting a NULL
--              :           if field DEFAULT value was omitted with an upgrade
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Transaction_Header_Payment_Insert
	(
		@Amount money,
		@Payment money,
		@Discount money,
		@Date datetime,
		@Comment varchar(20),
		@CustomerID int,
		@DateCaptured DateTime,
		@TypeID int,
		@UserID int,
		@CompanyID int
	)

AS

    DECLARE @TransactionNumber varchar(15),
            @Num int,
            @ASTransactionsID int


	BEGIN TRAN

    --> Get next PAYMENT TRANSACTION NUMBER
    ---------------------------------------
        SELECT @Num = ISNULL(Last_Number,0) 
        FROM Sys_AW_Transaction_Numbers
        WHERE AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID = 7
        
        UPDATE Sys_AW_Transaction_Numbers
        SET Last_Number = @Num + 1 
        WHERE AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID = 7
    
        SET @TransactionNumber = CONVERT(VARCHAR(15), @Num + 1) 
    ---------------------------------------

		INSERT AS_Transactions 
			(	
                AC_Customers_ID,
                Transaction_Number,
                Total_Discount_Amount,	
                Total_Amount,
                Payment_Amount,
                Amount, 
                Transaction_Date,
                Comment,								
                Sys_AW_Transaction_Types_ID,
                Lup_AS_Tills_ID,
                Lup_AS_Cashiers_ID,
                Date_Captured,
                [User_ID],
                AW_User_Companies_ID
			)
		VALUES
			(
                @CustomerID,
                @TransactionNumber,
                @Discount,            --0
               (@Amount * -1),        --Credit Total_Amount
                @Payment,             --0
               (@Amount * -1),        --Credit Amount
                @Date, 
                @Comment,
                @TypeID,
                1,
                @UserID,
                @DateCaptured,
                @UserID, 
                @CompanyID
			)
		

        SET @ASTransactionsID = Scope_Identity()


-------------------------------------------------------
    --> Update the Account Balance in AC_Customers
        UPDATE AC_Customers
        SET Account_Balance = Account_Balance - @Amount
        WHERE AC_Customers_ID = @CustomerID
-------------------------------------------------------

    COMMIT TRAN



RETURN @ASTransactionsID

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : Selects the transactions to display at POS
--Purpose       :
--Functionality :Send in the filter criteria
--Parameters    : 
--Date          : 2001/6/25
--Authors       : GL
--Version       : 1
-------------------------------------------------------------------------------
CREATE    PROCEDURE sp_AS_Transaction_Headers_Select
	@CompanyID int,
	@UserID int,
       @Criteria varchar(1000) 
AS
   SET NOCOUNT ON
   
   IF @Criteria <> ''
      BEGIN
         SET @Criteria = ' WHERE CompanyID =  ' + convert(varchar(10),@CompanyID) + ' AND '  + @Criteria
         EXEC ('   SELECT * FROM vw_AS_Transaction_Headers ' + @Criteria)
      END
   ELSE
      SELECT TOP 1000 * FROM vw_AS_Transaction_Headers
      WHERE  CompanyID =   @CompanyID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Headers_Unallocated_Select
--Purpose       :Select Transactions for Customer Catalog, Payments, Unallocated
--Parameters    :
--Date          :2002/01/21
--Authors       :TB
--Version       :1.0.0
--MODS          :28/05/02 - Added [User] to Choice 1 for display in
--              :           Customer Catalog Unallocated Ageing Transactions
--              :25/06/02 - ALTER NEW @Choice = 10 for Customer Catalog Ageing
--              :           1. ORDER BY to t.Transaction_Date DESC
--              :           2. SELECT list columns re-ordered
--              :02/07/02 - ALTER @Choice = 3 for Customer Payments Picklist
--              :           Select ONLY Customer with UNALLOCATED TRANSACTIONS
--              :           using fn_AC_Customer_Has_Outstanding_Transactions
--              :02/07/02 - ALTER @Choice = 10 to include Payment Transactions
--              :03/07/02 - Added @Choice = 11 for Unallocated PAYMENTS Picklist
--              :           Select ONLY Customers with UNALLOCATED PAYMENTS
--              :07/07/02 - Cleaned up @Choice 6,7 & 8
--              :09/07/02 - ALTER @Choice = 10 to same search criteria as ageing
--              :           source from fn_AC_Customer_Ageing_Non_Grouped
--              :10/07/02 - VALIDATE for NULLs (e.g. Customer_Number)
--              :10/07/02 - Modified WHERE clauses to be INCLUSIVE vs EXCLUSIVE
--              :20/07/02 - Added @Choice = 12 for Unallocated JOURNALS Picklist
--              :           Select ONLY Customers with UNALLOCATED JOURNALS
--              :24/07/02 - Added Sys_AW_Transaction_Types_ID 21 & 22 to ALL Options
--              :08/08/02 - Added @Choice = 14 & 15 for Unallocated REFUNDS Picklist
--              :           Select ONLY Customers with UNALLOCATED REFUNDS
--              :24/09/02 - Modified @Now to return MIDNIGHT TONIGHT which caused
--              :           not all transactions to be included for the @Now day
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :           in @Choice 10. This Mod causes an 'multiple step' ADO error
--              :           in Customer Payments used in @Choices 1, 2, 13, 15
--              :10/11/02 - Validate NULL column values for ALL amount columns
--              :           in @Choice 10 because of a 'multiple step' ADO error
--              :04/04/03 - Removed ISNULL validation of the [Description] column
--              :           in option 6, 7 & 8 because DBC in UI does not populate
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--              :25/10/03 - Added filter CUSTOMER PAYMENTS: PickList by Company
--              :           options 3, 10, 11, 12 & 14
--              :27/11/04 - Added CUSTOMER PAYMENT TYPES 21 and 22 for LUMPSUM
--              :           payments in options 2
--              :08/12/04 - Replaced option 10 (Account Balances) with SHAPED sp's
--2004.2.4      :03/06/05 - Added CUSTOMER UNPAID PAYMENT in option 16
--2004.2.4.1    :21/11/05 - Added Centralised Billing filter in Option 6 and
--              :           added ORDER BY [Description] in Option 8
--2004.2.7      :04/04/06 - Removed option 16 - Unpaid Cheques
--2004.4.3      :07/02/09 - Moved CUSTOMER PAYMENTS PickList rs (@Choice = 3)
--              :           to new sp_AC_Customer_Payments_PickList
--2004.4.8      :23/05/10 - Added NEW Option 3 for Unallocated Payments BOTTOM grid
--              :           and EXCLUDED Ageing and INCLUDED ALL Payments transactions
--              :23/05/10 - Changed field order of Options 2,3,13,15 for Unallocated Payments
--              :23/05/10 - Replaced using vw_AS_Transactions with AS_Transactions
--              :           in Options 2,3,13,15 for Unallocated Payments
--2004.5.0      :18/02/11 - Added Customer Ageing AGAIN for Unallocated Payments BOTTOM grid - S Hurly
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transaction_Headers_Unallocated_Select]
	(
        @Choice tinyint,
        @CompanyID int,
        @CustomerID int = 0
    )

AS

SET NOCOUNT ON

    DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime



--> (24/09/02) Truncates the decimal of getdate() and add 1 day then
--             this returns midnite tonight '2002-09-25 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))



    EXEC sp_AW_Period_Procedures_Select
             @Now,
             @D1 OUTPUT,
             @D2 OUTPUT,
             @D3 OUTPUT,
             @D4 OUTPUT,
             @D5 OUTPUT,
             @D6 OUTPUT,
             @D7 OUTPUT,
             1,
             @CompanyID



--> CUSTOMER PAYMENTS: Unallocated Transactions (EXCLUDING Payments)
--                 NB: ISNULL validation of amount fields cause 'multiple step' ADO error
    IF @Choice = 1
    	SELECT
            t.AS_Transactions_ID AS [ID], 
            t.AC_Customers_ID AS [CustomerID],
            ISNULL(t.Comment, '') AS [Comment],
            t.Total_Amount AS [Balance],
            t.Total_Amount + t.Payment_Amount AS [Old Balance],
            ISNULL(t.Transaction_Number, '') AS [No], 
            t.Total_Amount AS [Amount], 
            t.Payment_Amount AS [Payment], 
            t.Transaction_Date AS [Date], 
            ISNULL(tt.[Description], '') AS [Type],
--NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
            a.[Current] ,
            a.[30 Days],
            a.[60 Days],
            a.[90 Days],
            a.[120 Days],
            a.[150 Days],
            a.[180+ Days],
            a.[User]
    	FROM AS_Transactions t 
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
                ON t.AS_Transactions_ID = a.ID
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    	WHERE t.AC_Customers_ID = @CustomerID AND
              t.AW_User_Companies_ID = @CompanyID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR
              t.Sys_AW_Transaction_Types_ID = 4 OR
              t.Sys_AW_Transaction_Types_ID = 5 OR
              t.Sys_AW_Transaction_Types_ID = 15 OR
              t.Sys_AW_Transaction_Types_ID = 18)
    	ORDER BY t.Transaction_Date


--> CUSTOMER UNALLOCATED: Unallocated Payments (ALL Payments)
--  NB: ISNULL validation of amount fields cause 'multiple step' ADO error
    ELSE
    IF @Choice = 2
    	SELECT    
            AS_Transactions_ID AS [ID], 
            AC_Customers_ID AS [CustomerID],
            Total_Amount AS [Balance],
            Total_Amount + Payment_Amount AS [Old Balance],
            Transaction_Date AS [Date],
            ISNULL(Transaction_Number, '') AS [No], 
            Total_Amount AS [Amount], 
            Payment_Amount AS [Payment],
            ISNULL(Comment, '') AS [Comment]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
            AW_User_Companies_ID = @CompanyID AND
           (Total_Amount + Payment_Amount <> 0) AND
           (Sys_AW_Transaction_Types_ID = 7 OR
            Sys_AW_Transaction_Types_ID = 21 OR
            Sys_AW_Transaction_Types_ID = 22)


--  NEW 2004.4.8 23 MAY 2010 - Copied from @Choice = 1 and removed AGEING
--> CUSTOMER UNALLOCATED: Unallocated Transactions (INCLUDING Payments)
--  NB: ISNULL validation of amount fields cause 'multiple step' ADO error
    ELSE
    IF @Choice = 3
    	SELECT
            t.AS_Transactions_ID AS [ID], 
            t.AC_Customers_ID AS [CustomerID],
            t.Total_Amount AS [Balance],
            t.Total_Amount + Payment_Amount AS [Old Balance],
            t.Transaction_Date AS [Date], 
            ISNULL(t.Transaction_Number, '') AS [No], 
            t.Total_Amount AS [Amount], 
            t.Payment_Amount AS [Payment],
            ISNULL(t.Comment, '') AS [Comment],
            t.Sys_AW_Transaction_Types_ID AS [Type],
        --NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
            a.[Current] ,
            a.[30 Days],
            a.[60 Days],
            a.[90 Days],
            a.[120 Days],
            a.[150 Days],
            a.[180+ Days],
            [User_ID] AS [User]
    	FROM AS_Transactions t
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
                ON t.AS_Transactions_ID = a.ID
    	WHERE t.AC_Customers_ID = @CustomerID AND
              t.AW_User_Companies_ID = @CompanyID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR
              t.Sys_AW_Transaction_Types_ID = 4 OR
              t.Sys_AW_Transaction_Types_ID = 5 OR
              t.Sys_AW_Transaction_Types_ID = 7 OR
              t.Sys_AW_Transaction_Types_ID = 15 OR
              t.Sys_AW_Transaction_Types_ID = 18 OR
              t.Sys_AW_Transaction_Types_ID = 21 OR
              t.Sys_AW_Transaction_Types_ID = 22)
    	ORDER BY t.Transaction_Date


    ELSE 
    IF @Choice = 4
    	BEGIN
    		SELECT *
            FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
    	END


--> CUSTOMER CATALOG, PAYMENTS, UNALLOCATED: Ageing Totals of ALL Financial TranTypes
    ELSE
    IF @Choice = 5
    	BEGIN
    		SELECT
    			CustomerID,
    			SUM(Payment) AS [Payment],
    			SUM(Amount) AS [Amount],
    			SUM([Current]) AS [Current],
    			SUM([30 Days]) AS [30 Days],
    			SUM([60 Days]) AS [60 Days],
    			SUM([90 Days]) AS [90 Days],
    			SUM([120 Days]) AS [120 Days],
    			SUM([150 Days]) AS [150 Days],
    			SUM([180+ Days]) AS [180+ Days]
     		FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
    		GROUP BY CustomerID
    	END


--> CUSTOMER PAYMENTS: Payment Methods
    ELSE
    IF @Choice = 6
    	SELECT Sys_AW_Payment_Methods_ID AS [ID],
               [Description] AS [Method]
    	FROM Sys_AW_Payment_Methods 
    	WHERE Sys_AW_Payment_Methods_ID <> 1 AND
              Sys_AW_Payment_Methods_ID <> 7 AND
              Sys_AW_Payment_Methods_ID <> 8 AND
              Sys_AW_Payment_Methods_ID <> 10 AND
              Sys_AW_Payment_Methods_ID <> 11 AND
              Sys_AW_Payment_Methods_ID <> 13


--> CUSTOMER PAYMENTS: Card Institution
    ELSE
    IF @Choice = 7
       	SELECT Slu_AS_Card_Institutions_ID as [ID],
               [Description]
    	FROM Slu_AS_Card_Institutions
        ORDER BY [Description]


--> CUSTOMER PAYMENTS: Banks dbc    (Currently not used)
    ELSE
    IF @Choice = 8
       	SELECT Slu_AW_Banks_ID as [ID],
               [Description]
    	FROM Slu_AW_Banks
        ORDER BY [Description]


--> CUSTOMER JOURNALS: Unallocated Transactions (REDUNDANT OLD VERSION)
    ELSE
    IF @Choice = 9
    	SELECT    
    		t.AS_Transactions_ID AS [ID], 
    		t.AC_Customers_ID AS [CustomerID],
    		ISNULL(tt.[Description], '') AS [Type], 
    		ISNULL(t.Comment, '') AS [Comment],
    		t.Total_Amount AS [Balance],
    		t.Total_Amount + t.Payment_Amount AS [Old Balance],
    		ISNULL(t.Transaction_Number, '') AS [No], 
    		t.Total_Amount AS [Amount], 
    		t.Payment_Amount AS [Payment], 
    		t.Transaction_Date AS [Date], 
--NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
    		a.[Current],
    		a.[30 Days],
    		a.[60 Days],
    		a.[90 Days],
    		a.[120 Days],
    		a.[150 Days],
    		a.[180+ Days]
    	FROM AS_Transactions t 
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a
                ON t.AS_Transactions_ID = a.ID
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
    	WHERE t.AC_Customers_ID = @CustomerID AND
              t.AW_User_Companies_ID = @CompanyID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR
              t.Sys_AW_Transaction_Types_ID = 4 OR
              t.Sys_AW_Transaction_Types_ID = 5 OR
              t.Sys_AW_Transaction_Types_ID = 7 OR
              t.Sys_AW_Transaction_Types_ID = 15 OR
              t.Sys_AW_Transaction_Types_ID = 18 OR
              t.Sys_AW_Transaction_Types_ID = 21 OR
              t.Sys_AW_Transaction_Types_ID = 22)
    	ORDER BY t.Transaction_Date


--> CUSTOMER CATALOG: Unallocated Ageing Transactions (used in Account Balances tab ONLY)
--> 2004/12/08 Replaced by SHAPE with sp_AS_Shape_Account_Balance_Header AND
--                                    sp_AS_Shape_Account_Balance_Detail
    ELSE
    IF @Choice = 10
    	SELECT
    		t.AS_Transactions_ID AS [ID], 
    		t.AC_Customers_ID AS [CustomerID],
    		ISNULL(tt.[Description], '') AS [Type],
    		t.Transaction_Date AS [Date], 
    		ISNULL(t.Transaction_Number, '') AS [No], 
    		ISNULL(t.Total_Amount, 0) AS [Amount], 
    		ISNULL(t.Payment_Amount, 0) AS [Payment], 
--     		t.Total_Amount AS [Balance],
--     		t.Total_Amount + t.Payment_Amount AS [Old Balance],
       		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
       		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Old Balance],
    		ISNULL(t.Comment, '') AS [Comment],
--NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
    		a.[Current] ,
    		a.[30 Days],
    		a.[60 Days],
    		a.[90 Days],
    		a.[120 Days],
    		a.[150 Days],
    		a.[180+ Days],
            a.[User]
    	FROM AS_Transactions t 
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
                ON t.AS_Transactions_ID = a.[ID]
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    	WHERE t.AW_User_Companies_ID = @CompanyID AND
              t.AC_Customers_ID = @CustomerID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
              t.Sys_AW_Transaction_Types_ID = 4 OR   --Refund
              t.Sys_AW_Transaction_Types_ID = 5 OR   --Journal
              t.Sys_AW_Transaction_Types_ID = 7 OR   --Payment
              t.Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
              t.Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
              t.Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
              t.Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
    	ORDER BY t.Transaction_Date         --DESC


--> UNALLOCATED PAYMENTS: --> PickList rs - ONLY Customers with UNALLOCATED PAYMENTS
    ELSE
    IF @Choice = 11
    	SELECT
    		AC_Customers_ID AS [ID], 
    		ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
    		ISNULL(Customer_Number, '') AS [No] 
    	FROM AC_Customers
    	WHERE AW_User_Companies_ID = @CompanyID AND
              dbo.fn_AC_Customer_Has_Unallocated_Payments(AC_Customers_ID) = 1
     	ORDER BY [Name]


--> UNALLOCATED JOURNALS: --> PickList rs - ONLY Customers with UNALLOCATED JOURNALS
    ELSE
    IF @Choice = 12
    	SELECT
    		AC_Customers_ID AS [ID], 
    		ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
    		ISNULL(Customer_Number, '') AS [No] 
    	FROM AC_Customers
    	WHERE AW_User_Companies_ID = @CompanyID AND
              dbo.fn_AC_Customer_Has_Unallocated_Journals(AC_Customers_ID) = 1
     	ORDER BY [Name]


--> CUSTOMER UNALLOCATED: Unallocated JOURNALS
    ELSE
    IF @Choice = 13
    	SELECT    
            AS_Transactions_ID AS [ID], 
            AC_Customers_ID AS [CustomerID],
            Total_Amount AS [Balance],
            Total_Amount + Payment_Amount AS [Old Balance],
            Transaction_Date AS [Date],
            ISNULL(Transaction_Number, '') AS [No], 
            Total_Amount AS [Amount], 
            Payment_Amount AS [Payment],
            ISNULL(Comment, '') AS [Comment]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
            AW_User_Companies_ID = @CompanyID AND
            ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
            Sys_AW_Transaction_Types_ID = 5


--> UNALLOCATED REFUNDS: --> PickList rs - ONLY Customers with UNALLOCATED REFUNDS
    ELSE
    IF @Choice = 14
    	SELECT
    		AC_Customers_ID AS [ID], 
    		ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
    		ISNULL(Customer_Number, '') AS [No] 
    	FROM AC_Customers
    	WHERE AW_User_Companies_ID = @CompanyID AND
              dbo.fn_AC_Customer_Has_Unallocated_Refunds(AC_Customers_ID) = 1
     	ORDER BY [Name]


--> CUSTOMER UNALLOCATED: Unallocated REFUNDS
    ELSE
    IF @Choice = 15
        SELECT    
            AS_Transactions_ID AS [ID], 
            AC_Customers_ID AS [CustomerID],
            Total_Amount AS [Balance],
            Total_Amount + Payment_Amount AS [Old Balance],
            Transaction_Date AS [Date],
            ISNULL(Transaction_Number, '') AS [No], 
            Total_Amount AS [Amount], 
            Payment_Amount AS [Payment],
            ISNULL(Comment, '') AS [Comment]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
            AW_User_Companies_ID = @CompanyID AND
            ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
            Sys_AW_Transaction_Types_ID = 4





SET NOCOUNT OFF    

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Invoice_Cons
--Purpose       :Create an Invoice for Consignment stock sold
--Functionality :Financial AS_Transactions types only: 3
--              :NB NB - SIGN REVERSAL
--Authors       :RL
--Date          :2015/05/21
--MODS          :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_Transaction_Invoice_Cons]
    (
        @SoldConsignmentID int,
        @ConsignmentID int,
        @CustomerID int,
        @Notes varchar(500),
        @Total money,
        @Reps_ID		int,
    	@UserID int,
    	@CompanyID int
    )

AS

	DECLARE @DocumentID					int,
			@DocumentDetailsID			int,
            @CommentID					int,
            @Transaction_Number			varchar(19),
            @AS_Transaction_Details_ID	int, 
            @AP_Products_ID				int, 
            @Quantity					decimal(9,3),
            @Quantity_Cons				decimal(9,3),
            @Detail_Date_Captured		datetime,
   			@IsConsignmentStock			int,
			@CostingMethod				int,
			@Cost						money,
			@Cost_Original				money,
			@Cost_Diff					money,
			@Oppisite_Qty				decimal(9,3),
			@ProductBinID				int,
			@ProductsQty				decimal(9,3),

			@H_Total_Cost				money,
			@H_Amount					money,
			@H_Total_Tax_Amount			money,
			@H_Total_Discount_Amount	money,
			@H_Total_Amount				money

	EXEC sp_AW_Get_Next_Transaction_Number 3, 1, @Transaction_Number Output

	IF RTRIM(LTRIM(@Notes)) <> ''
	BEGIN
		EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Notes
	END
	
	INSERT INTO AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Total_Cost,
            Amount,
            Total_Tax_Amount,
            Total_Discount_Amount,
            Total_Amount,
            Transaction_Date,
            Customer_Reference,
            Comment,
            AW_Comments_ID,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            Lup_AS_Reps_ID,
            [User_ID],
            AW_User_Companies_ID
		)
	SELECT  AC_Customers_ID,
            AB_Accounts_ID,
            @Transaction_Number,
            (Total_Cost*-1),
            (Amount*-1),
            (Total_Tax_Amount*-1),
            (Total_Discount_Amount*-1),
            (Total_Amount*-1),
            Transaction_Date,
            Customer_Reference,
            Comment,
            @CommentID,
            Lup_AS_Cashiers_ID,
            3,
            Date_Captured,
            @Reps_ID,
            @UserID,
            AW_User_Companies_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @SoldConsignmentID        

    SELECT @DocumentID = Scope_Identity()

 --   --> Update the Customer Account Balance
	UPDATE AC_Customers
	SET Account_Balance = Account_Balance + @Total
	WHERE AC_Customers_ID = @CustomerID

	SELECT @Cost_Original = Total_Cost
	FROM AS_Transactions
    WHERE AS_Transactions_ID = @SoldConsignmentID
    
--Insert Into Temp_Debug Values('@SoldConsignmentID',Convert(Varchar(100),@SoldConsignmentID))   	

	DECLARE GetData CURSOR 
	FOR
		SELECT AS_Transaction_Details_ID, AP_Products_ID, Quantity, Date_Captured, Lup_AP_Product_Bins_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @SoldConsignmentID
		ORDER BY AS_Transaction_Details_ID	
	
	OPEN GetData
	FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @AP_Products_ID, @Quantity, @Detail_Date_Captured, @ProductBinID
	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @IsConsignmentStock = 0
		SET @Quantity_Cons = @Quantity * -1
	
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
	
--Insert Into Temp_Debug Values('41 - @Quantity_Cons',Convert(Varchar(100),@Quantity_Cons))   	
--Insert Into Temp_Debug Values('41 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
		
		EXEC sp_AS_Transaction_Detail_Consignment @AP_Products_ID, @Quantity_Cons, @UserID, @CompanyID, @IsConsignmentStock OUTPUT	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
--Insert Into Temp_Debug Values('41 - @ProductsQty After GRV',Convert(Varchar(100),@ProductsQty))   	
	
		--It does not matter if the the product is a consignment stock item. 
		--You still need to get the latest product cost
		--IF @IsConsignmentStock = 1
		--BEGIN
			
			SET @CostingMethod = 0
			SELECT @CostingMethod = Control_Index 
			FROM Sys_AW_Options 
			WHERE Control_Name = 'optInventoryValuation' 
			AND Control_Value = 'True'
		
			--0 - Average Cost
			--1	- Last Cost
			--2 - Standard Cost
			IF @CostingMethod IS NULL
				SET @CostingMethod = 0
				
			IF @CostingMethod = 0
			BEGIN
				SELECT @Cost = ISNULL(Average_Cost,0)
				FROM AP_Products
				WHERE AP_Products_ID = @AP_Products_ID
			END

			IF @CostingMethod = 1
			BEGIN
				SELECT @Cost = ISNULL(Last_Cost,0)
				FROM AP_Products
				WHERE AP_Products_ID = @AP_Products_ID
			END
			
			IF @CostingMethod = 2
			BEGIN
				SELECT @Cost = ISNULL(Standard_Cost,0)
				FROM AP_Products
				WHERE AP_Products_ID = @AP_Products_ID
			END		
		--END 

		--V6.2 RL 2015-08-18 If the Cost has changed due to consignment stock being GRV into the system, Update Total Cost
		SET @Cost_Diff = 0
		SET @Cost_Diff = @Cost_Original - @Cost
		--IF @Cost_Diff <> 0
		--BEGIN
		--	UPDATE AS_Transactions
		--		SET Total_Cost = Total_Cost + (@Cost_Diff * @Quantity)
		--	WHERE AS_Transactions_ID = @DocumentID
		--END
				
--		IF @IsConsignmentStock = 0
--		BEGIN
			UPDATE AP_Products
			SET On_Hand = On_Hand + @Quantity,
				Last_Sale_Date = getdate(),
				[User_ID] = @UserID
			WHERE AP_Products_ID = @AP_Products_ID
		--END
		--ELSE
		--BEGIN
		--	UPDATE AP_Products
		--	SET Last_Sale_Date = getdate(),
		--		[User_ID] = @UserID
		--	WHERE AP_Products_ID = @AP_Products_ID		
		--END

		--V6.2 Update Bin Qty
		IF @Quantity <> 0
		BEGIN
			--SELECT @Quantity_Cons = @Quantity_Cons * -1
			
			EXEC sp_AP_Products_Bins_Update_Insert 
				@AP_Products_ID,	--@ProductID int,
				@ProductBinID,		--@ProductBinID int,
				@Quantity,		--@Qty decimal(9,3)
				'CON S',			--@Source varchar(10),
				0,					--@Batch_No
				@UserID,			--@UserID int,
				@CompanyID			--@CompanyID int			    	
		END	
		
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
--Insert Into Temp_Debug Values('41 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
				
		INSERT INTO AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Discount_Amount,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID,
			Lup_AP_Product_Bins_ID
		)
		SELECT
			@DocumentID,
			AP_Products_ID,
			(Quantity*-1),
			@Cost, --Costing could have changed since it was sold on consignment note
			Unit_Price,
			Original_Price,
			(Discount_Amount*-1),
			(Tax_Amount*-1),
			(Extended_Amount*-1),
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			[User_ID],
			AW_User_Companies_ID,
			Lup_AP_Product_Bins_ID
		FROM AS_Transaction_Details
		WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID	
		
		SELECT @DocumentDetailsID = Scope_Identity()

		--V6.3 RL 2017-05-13 Recalc Header Totals
		SELECT @H_Total_Cost = SUM((Quantity + Back_Order) * Unit_Cost),
				@H_Total_Discount_Amount = SUM(Discount_Amount),
				@H_Amount = SUM(Extended_Amount - Tax_Amount),
				@H_Total_Tax_Amount = SUM(Tax_Amount),
				@H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
			Total_Discount_Amount = @H_Total_Discount_Amount,
			Amount = @H_Amount,
			Total_Tax_Amount = @H_Total_Tax_Amount,
			Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @DocumentID
		
		INSERT INTO AS_Transaction_Details_Consignment
		(		
			AS_Transaction_Details_ID, --Sys_AW_Transaction_Types_ID 33 Consignment Stock Note
			Consignment_ID,
			Sys_AW_Transaction_Types_ID,
			Quantity,
			Date_Captured,
			[User_ID],
			AW_User_Companies_ID	
		)
		VALUES
		(
			@ConsignmentID,
			@DocumentDetailsID,
			3,
			ABS(@Quantity),
			@Detail_Date_Captured,
			@UserID,
			@CompanyID
		)

		FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @AP_Products_ID, @Quantity, @Detail_Date_Captured, @ProductBinID
	END
	CLOSE GetData
	DEALLOCATE GetData


RETURN @DocumentID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--Used at the Customer Payments 
--GL
--2001/10/12

CREATE PROCEDURE sp_AS_Transaction_Payment_Allocate
	(
		@ID int,
		@Amount money,
		@SourceTransactionID int = NULL
	)
AS

	UPDATE AS_Transactions SET Payment_Amount = Payment_Amount + @Amount WHERE AS_Transactions_ID = @ID

	IF NOT @SourceTransactionID IS NULL
		INSERT AS_Transactions_Transactions (Source_AS_Transactions_ID, Destination_AS_Transactions_ID, Amount)
		VALUES (@ID,  @SourceTransactionID, @Amount)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Payment_Insert
--Purpose       :Inserts Supporting Details FOR EACH Customer PAYMENT 1:1 Rel
--SEE ALSO      :sp_AS_POS_Transaction_Payment_Insert (POS Payment insert)
--Required      :A previously INSERTED PAYMENT in AS_Transaction 
--              :NB - THE PARAMATER NAMES MUST BE THE SAME(WITHOUT THE SPACES) AS
--              :	  vw_AS_Transaction_Payments
--Date          :2002/1/22
--Authors       :TB
--MODS          :
--2004.3.8      :29/05/08 - Changed @Amount to -(@Amount) insert into
--              :           AS_Transaction_Payments to insert the SAME value as inserted 
--              :           in AS_Transactions -  - Payment Reversal problem
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AS_Transaction_Payment_Insert
    (
    	@Method varchar(20) = NULL,
    	@Institution varchar(50) = NULL,
    	@PayorName varchar(50) = NULL,
    	@CardExpiryDate varchar(6) = NULL,
    	@CardNumber varchar(20) = NULL,
    	@AuthorisationNumber varchar(20) = NULL,
    	@Amount money = 0,
    	@MethodID tinyint = NULL,
    	@InstitutionID int = NULL,
    	@TransactionID int = NULL,
    	@Date datetime = NULL,
    	@UserID int = NULL,
    	@CompanyID int = NULL,
    	@ID int OUTPUT
    )

AS

SET NOCOUNT ON

	INSERT AS_Transaction_Payments
        (
    		Payor_Name,
    		Card_Expiry_Date,
    		Card_Number,
    		Authorisation_Number,
    		Amount,
    		Sys_AW_Payment_Methods_ID,
    		Slu_AS_Card_Institutions_ID,
    		AS_Transactions_ID,
    		Date_Captured,
    		[User_ID],
    		AW_User_Companies_ID
        )
	VALUES
        (
    		@PayorName,
    		@CardExpiryDate,
    		@CardNumber,
    		@AuthorisationNumber,
    		-(@Amount),
    		@MethodID,
    		@InstitutionID,
    		@TransactionID,
    		@Date ,
    		@UserID,
    		@CompanyID
        )

	SELECT @ID = Scope_Identity()









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description	:sp_AS_Transaction_Payment_Update
--Purpose       :UPDATE AS_Transactions.Payment_Amount
--Date			:2010/05/21
--Authors		:TB
--MODS    		:
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AS_Transaction_Payment_Update
	(
		@TransactionID int,
        @PayAmount money
	)

AS

SET NOCOUNT ON


	UPDATE AS_Transactions
    SET Payment_Amount = @PayAmount
    WHERE AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF
	








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   : sp_AS_Transaction_Payments_IPay_Insert
--Purpose       : Inserts POS i-Pay Payment Details
--Functionality : Tables: AS_Transaction_Payments
--Parameters    : 
--Date          : 2018-03-20
--Authors       : RL
--Version       :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transaction_Payments_IPay_Insert]
	(					
		@Ipay_Action					[varchar](10),
		@AS_Transactions_ID				[int],
		@AS_Transaction_Payments_ID		[int],
		@IPay_ID						[varchar](50),
		@IPay_Tran_Ref					[varchar](50),
		@IPay_Bank_Ref					[varchar](50),
		@IPay_URL						[varchar](250),
		@IPay_Status					int, --0 Still awaiting payment, 1 Paid, 2 Other
		@Amount							money,
		@Cell_No						[varchar](20),
		@Email							[varchar](100),	
		@Status_Code					[varchar](50),
		@Status_Description				[varchar](250),
		@HTTPStatus						[varchar] (20),
		@User_ID						[int],
		@CompanyID						[int]
	)

AS

	DECLARE	@Done	int,
			@PaymentID int,
			@CustomerID int,
			@AccountID int,
			@TransactionNumber varchar(19),
			@TotalAmount money,
			@PaymentAmount money,
			@CustomerReference varchar(15),
			@TransactionTypeID int,
			@StoreID int,
			@WorkstationID int,
			@TillID int,
			@CashierID int,
			@RepID int,
			@CurrencyID int,
			@DateCaptured datetime,
			@SourceTransactionID int
	
	SELECT @Done = 0
	
	IF @IPay_Status = 99
	BEGIN
		UPDATE AS_Transaction_Payments_IPay
		SET AS_Transactions_ID = @AS_Transactions_ID
		WHERE IPay_ID = @IPay_ID
		AND IPay_Action = 'PAY SUC'
		
		SELECT @Done = 1
	END
	
	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'DAYEND_1'
		BEGIN
	--Select @AS_Transactions_ID As '@AS_Transactions_ID'	
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				'PAYDONE',
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			

			SELECT  @PaymentAmount = Payment_Amount,
					@TotalAmount = Total_Amount,
					@CustomerID = AC_Customers_ID,
					@TransactionTypeID = Sys_AW_Transaction_Types_ID,
					@CustomerReference = Customer_Reference,
					@TillID = Lup_AS_Tills_ID,
					@CashierID = Lup_AS_Cashiers_ID,
					@RepID = LUP_AS_Reps_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @AS_Transactions_ID

			SELECT @DateCaptured = GETDATE()
			
			IF @PaymentAmount = 0
			BEGIN
				Exec sp_AS_POS_Transaction_Payment_Insert
					@PaymentID Output,
					@CustomerID,
					@AccountID,
					@TransactionNumber,
					@Amount,
					@Amount,
					@CustomerReference,
					@TransactionTypeID,
					@StoreID,
					NULL,--@WorkstationID,
					@TillID,
					@CashierID,
					@RepID,
					@CurrencyID,
					@DateCaptured,
					@User_ID,
					@CompanyID,
					@AS_Transactions_ID
			END
			ELSE
			BEGIN
				Exec sp_AS_POS_Transaction_Payment_Insert
					@PaymentID Output,
					@CustomerID,
					@AccountID,
					@TransactionNumber,
					@Amount,
					0,
					@CustomerReference,
					@TransactionTypeID,
					@StoreID,
					NULL,--@WorkstationID,
					@TillID,
					@CashierID,
					@RepID,
					99,
					@DateCaptured,
					@User_ID,
					@CompanyID,
					@AS_Transactions_ID			
			END
				 
			SET @TotalAmount = @Amount * -1
 
			Exec sp_AS_POS_Transaction_Payment_Detail_Insert
				@TotalAmount,--@Amount,	
				'',--@PayorName,
				'',--@CardExpiryDate,
				'',--@CardNo,
				'',--@AuthorisationNo,
				14,--@MethodID,
				1,--@InstitutionID,
				@User_ID,
				@CompanyID,
				0,--@PaymentDetailsID,
				@PaymentID,--@PaymentID
				@DateCaptured,
				@IPay_ID,
				'',--@IPay_Tran_Ref,
				'',--@IPay_Bank_Ref,
				1,--@IPay_Status
				'',--@Cell_No,
				''--@Email

			UPDATE AS_Transaction_Payments_IPay
			SET IPay_Status = 1,
				Status_Code = @Status_Code,
				Status_Description = @Status_Description
			WHERE IPay_ID = @IPay_ID
			AND IPay_Action = 'PAY SUC'

			SELECT @Done = 1		
		END
	END
	
	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'DAYEND_2'
		BEGIN
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				@Ipay_Action,
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			
			
			IF @Status_Code NOT IN ('Created', 'Waiting', 'Cancelled')
			BEGIN
				UPDATE AS_Transaction_Payments_IPay
				SET IPay_Status = 1,
					Status_Code = @Status_Code,
					Status_Description = @Status_Description
				WHERE IPay_ID = @IPay_ID
				AND IPay_Action = 'PAY SUC'
			END
			
			SELECT @Done = 1		
		END		
	END

	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'DAYEND_3'
		BEGIN
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				'PAYDONE',
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			
			
			UPDATE AS_Transaction_Payments_IPay
			SET IPay_Status = 1,
				Status_Code = @Status_Code,
				Status_Description = @Status_Description
			WHERE IPay_ID = @IPay_ID
			AND IPay_Action = 'PAY SUC'
		
			SELECT @Done = 1		
		END		
	END

	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'PAYDONE'
		BEGIN
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				@Ipay_Action,
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			
			
			--Used to pole unpaid transactions on day-end
			UPDATE AS_Transaction_Payments_IPay
			SET IPay_Status = 1,
					Status_Code = @Status_Code,
					Status_Description = @Status_Description
			WHERE IPay_ID = @IPay_ID
			AND IPay_Action = 'PAY SUC'

			SELECT @Done = 1		
		END
	END
	
	IF @Done = 0 
	BEGIN
		INSERT INTO AS_Transaction_Payments_IPay
		(
			Ipay_Action,
			AS_Transactions_ID,
			AS_Transaction_Payments_ID,
			IPay_ID,
			IPay_Tran_Ref,
			IPay_Bank_Ref,
			IPay_URL,
			IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
			Amount,
			Cell_No,
			Email,
			Status_Code,
			Status_Description,
			HTTPStatus,
			[User_ID],
			AW_User_Companies_ID
		)
		VALUES
		(
			@Ipay_Action,
			@AS_Transactions_ID,
			@AS_Transaction_Payments_ID,
			@IPay_ID,
			@IPay_Tran_Ref,
			@IPay_Bank_Ref,
			@IPay_URL,
			@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
			@Amount,
			@Cell_No,
			@Email,	
			@Status_Code,
			@Status_Description,
			@HTTPStatus,
			@User_ID,
			@CompanyID
		)
	END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Payments_IPay_Select
--Purpose       :Gets IPay Details
--Date          :2018-03-28
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transaction_Payments_IPay_Select]
    (    	    	
    	@AS_Transactions_ID	int
    )
AS 

	IF @AS_Transactions_ID = 0
	BEGIN
		SELECT 
			AS_Transaction_Payments_IPay_ID, Ipay_Action, 
			AS_Transactions_ID, 
			AS_Transaction_Payments_ID, 
			IPay_ID, 
			IPay_Tran_Ref, 
			IPay_Bank_Ref, 
			IPay_URL, 
			IPay_Status,
			Amount, 
			Cell_No, 
			Email, 
			Status_Code, 
			Status_Description, 
			HTTPStatus, 
			Date_Captured
		FROM AS_Transaction_Payments_IPay
		WHERE IPay_Status = 0 
		AND IPay_Action = 'PAY SUC'
	END		
	ELSE
	BEGIN
		SELECT 
			AS_Transaction_Payments_IPay_ID, Ipay_Action, 
			AS_Transactions_ID, 
			AS_Transaction_Payments_ID, 
			IPay_ID, 
			IPay_Tran_Ref, 
			IPay_Bank_Ref, 
			IPay_URL, 
			IPay_Status,
			Amount,  
			Cell_No, 
			Email, 
			Status_Code, 
			Status_Description, 
			HTTPStatus, 
			Date_Captured
		FROM AS_Transaction_Payments_IPay
		WHERE AS_Transactions_ID = @AS_Transactions_ID
		AND IPay_Action = 'PAY SUC'
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : Selects the Transaction Details for POS
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/6/25
--Authors       : GL
--Version       : 1
-------------------------------------------------------------------------------
CREATE  PROCEDURE sp_AS_Transaction_Payments_Select
	@CompanyID int,
	@UserID int,
	@TransactionID int 
AS
SELECT * FROM vw_AS_Transaction_Payments
	WHERE TransactionID = @TransactionID 
		 AND CompanyID = @CompanyID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description	:sp_AS_Transaction_Status_Update
--Purpose       :De-Activates a AS_Transactions
--              :
--Date			:2002/03/12
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------
--     ID	Description
--     --   -----------
--     1	Enabled
--     2	Disabled
--     3	Discontinued
--     4	Ignore
--     5	Delete
-------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AS_Transaction_Status_Update
	(
		@TransactionID int,
        @ActiveStatus tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @TranTypeID int

    IF EXISTS
       (
        	SELECT AS_Transactions_ID
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @TransactionID
        )
        BEGIN
        	UPDATE AS_Transactions
            SET Slu_AW_Active_ID = @ActiveStatus
            WHERE AS_Transactions_ID = @TransactionID
        END


SET NOCOUNT OFF
	







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_AS_Transaction_Transaction_Insert
--Purpose       :Inserts an Payment Allocation in AS_Transactions_Transactions
--    			:NB - THE PARAMETER NAMES MUST BE THE SAME (WITHOUT THE SPACES)
--				:	  AS vw_AS_Transaction_Payments
--    			:NB - You must first have inserted a Payment Transaction
--              :     in the AS_Transactions Table
--Date			:2002/01/22
--Authors		:TB
--Version		:1.0.0
--MODS          :07/07/02 - Cleaned up @Choice 6,7 & 8
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_AS_Transaction_Transaction_Insert
	(
        @SourceTransactionID int = NULL,
        @DestinationTransactionID int = NULL,
        @Amount money = NULL,
        @UnAllocated bit = NULL,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

	INSERT AS_Transactions_Transactions
		(
            Source_AS_Transactions_ID,
            Destination_AS_Transactions_ID,
            Amount,
            [User_ID],
            AW_User_Companies_ID
        )
	VALUES
		(
            @SourceTransactionID,
            @DestinationTransactionID,
            @Amount,
            @UserID,
            @CompanyID
        )

	IF @Amount IS NOT NULL
        BEGIN
        	IF @SourceTransactionID IS NOT NULL
                BEGIN
            		UPDATE AS_Transactions 
            		SET Payment_Amount = Payment_Amount + @Amount 
            		WHERE AS_Transactions_ID = @SourceTransactionID
                END

        --> Used only to update Unallocated Payments SOURCE PAYMENT
        	IF @UnAllocated = 1    --TRUE
                BEGIN
            		UPDATE AS_Transactions 
            		SET Payment_Amount = Payment_Amount + @Amount 
            		WHERE AS_Transactions_ID = @DestinationTransactionID    --Orig Payment ID
                END
        END

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Insert
--Purpose       :Keeps a record of address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-01-02
--Authors       :RL
--Mod			:RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID
--V6.3	RL	2017-02-28	:Changed so that each document will have its own link in the address details table
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Insert]
   (	@AC_Customers_ID					int,	--RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID	
		@Company_ID							int,			--In POS code, Customer is sent through first
    	@AS_Transactions_ID					int,
    	@Inv_Customer_Name					varchar(100),
		@Inv_Address1						varchar(40),
		@Inv_Address2						varchar(40),
		@Inv_City							varchar(30),
		@Inv_Code							varchar(10),
		@Inv_Tax_Number						varchar(16),
		@Cell_No							varchar(16),
		@Email								varchar(100),
		@Delivery_Address					varchar(40),
		@Delivery_Suburb					varchar(40),
		@Delivery_City						varchar(30),
		@Delivery_Post_Code					varchar(10),
		@User_ID							int
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
		@AS_Transactions_Address_Detail_ID	int,
    	@AW_YesNo_Delivery_Address int,
    	@AW_YesNo_Invoice int

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 0
	SET @AS_Transactions_Address_Detail_ID = 0
		
	SET @Inv_Customer_Name = LTRIM(RTRIM(ISNULL(@Inv_Customer_Name,'')))
	SET @Inv_Address1 = LTRIM(RTRIM(ISNULL(@Inv_Address1,'')))
	SET @Inv_Address2 = LTRIM(RTRIM(ISNULL(@Inv_Address2,'')))
	SET @Inv_Code = LTRIM(RTRIM(ISNULL(@Inv_Code,'')))
	SET @Inv_City = LTRIM(RTRIM(ISNULL(@Inv_City,'')))
	SET @Inv_Tax_Number = LTRIM(RTRIM(ISNULL(@Inv_Tax_Number,'')))
	SET @Delivery_Address = LTRIM(RTRIM(ISNULL(@Delivery_Address,'')))
	SET @Delivery_Suburb = LTRIM(RTRIM(ISNULL(@Delivery_Suburb,'')))
	SET @Delivery_City = LTRIM(RTRIM(ISNULL(@Delivery_City,'')))
	SET @Delivery_Post_Code = LTRIM(RTRIM(ISNULL(@Delivery_Post_Code,'')))
	SET @Cell_No = LTRIM(RTRIM(ISNULL(@Cell_No,'')))
	SET @Email = LTRIM(RTRIM(ISNULL(@Email,'')))

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	
	
	-- Check if values changed from customer
	DECLARE 
		@Inv_Customer_Name_DB					varchar(100),
		@Inv_Address1_DB						varchar(40),
		@Inv_Address2_DB						varchar(40),
		@Inv_City_DB							varchar(30),
		@Inv_Code_DB							varchar(10),
		@Inv_Tax_Number_DB						varchar(16),
		@Cell_No_DB								varchar(16),
		@Email_DB								varchar(100),
		@WhichAddress							tinyint = 0,
		@WhichName								tinyint = 0;
	
	SELECT @WhichAddress = ISNULL(Control_Index, 0)
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
		Control_Name = 'optPOSPrintAddress' AND
		Control_Value = 'True'

	--> Get Which Name Format To Use
	SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM Sys_AW_Options
	WHERE Control_Index = 0 AND
	Control_Type = 'CheckBox' AND
	Control_Name = 'chkPOSPrintTradeName'
	
	IF (@WhichAddress = 0)
	BEGIN
		SELECT 
			@Inv_Customer_Name_DB = (CASE WHEN @WhichName = 1 THEN 
									  (CASE 
										WHEN ISNULL(Initials,'') = ''  
										THEN    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname))    
											ELSE LTRIM(RTRIM(Surname)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										ELSE    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))    
											ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										END)
									ELSE
									  CASE WHEN ISNULL(Initials,'') = ''   
										THEN LTRIM(RTRIM(Surname))   
										ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))
									  END
									END),
			@Inv_Address1_DB = Post_Box,						
			@Inv_Address2_DB = Post_Office,						
			@Inv_City_DB = City,							
			@Inv_Code_DB = Post_Code,							
			@Inv_Tax_Number_DB = Tax_Number,						
			@Cell_No_DB = Cell_No						
		FROM
			AC_Customers		
		WHERE 
			AC_Customers_ID = @AC_Customers_ID 
	END
	ELSE 
	BEGIN
		SELECT 
			@Inv_Customer_Name_DB = (CASE WHEN @WhichName = 1 THEN 
									  (CASE 
										WHEN ISNULL(Initials,'') = ''  
										THEN    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname))    
											ELSE LTRIM(RTRIM(Surname)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										ELSE    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))    
											ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										END)
									ELSE
									  CASE WHEN ISNULL(Initials,'') = ''   
										THEN LTRIM(RTRIM(Surname))   
										ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))
									  END 
									END),
			@Inv_Address1_DB = Street_Address,						
			@Inv_Address2_DB = Suburb,						
			@Inv_City_DB = City,							
			@Inv_Code_DB = Street_Post_Code,							
			@Inv_Tax_Number_DB = Tax_Number,						
			@Cell_No_DB = Cell_No						
		FROM
			AC_Customers		
		WHERE 
			AC_Customers_ID = @AC_Customers_ID 
	END 
	
	IF 
	(
		@Inv_Customer_Name <> @Inv_Customer_Name_DB Or
		@Inv_Address1 <> @Inv_Address1_DB Or
		@Inv_Address2 <> @Inv_Address2_DB Or
		@Inv_Code <> @Inv_Code_DB Or
		@Inv_City <> @Inv_City_DB Or
		@Inv_Tax_Number <> @Inv_Tax_Number_DB Or
		@Cell_No <> @Cell_No_DB
	)
	BEGIN
		SET @AW_YesNo_Invoice = 1
	END
	
	
		 
	--V6.3 Each document will have its own link in the address details table
	--SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID
	--FROM AS_Transactions_Address_Detail
	--WHERE AC_Customers_ID = @AC_Customers_ID AND
	--	  Customer_Name = @Inv_Customer_Name AND
	--	  Inv_Address1 = @Inv_Address1 AND
	--	  Inv_Address2 = @Inv_Address2 AND
	--	  Inv_Code = @Inv_Code AND
	--	  Inv_City = @Inv_City AND
	--	  Tax_Number = @Inv_Tax_Number AND
	--	  Delivery_Address = @Delivery_Address AND
	--	  Delivery_Suburb = @Delivery_Suburb AND
	--	  Delivery_City = @Delivery_City AND
	--	  Delivery_Post_Code = @Delivery_Post_Code

	--IF @AS_Transactions_Address_Detail_ID = 0
	--BEGIN
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				Cell_No,
				Email, 
				Delivery_Address, 
				Delivery_Suburb, 
				Delivery_City, 
				Delivery_Post_Code, 
				Date_Captured,
				User_ID, 
				AW_User_Companies_ID,
				AW_YesNo_Delivery_Address,
				AW_YesNo_Invoice
			)
		VALUES
			(
				@AC_Customers_ID,
				@Inv_Customer_Name,
				@Inv_Address1,
				@Inv_Address2,
				@Inv_Code,
				@Inv_City,
				@Inv_Tax_Number,
				@Cell_No,
				@Email,
				@Delivery_Address,
				@Delivery_Suburb,
				@Delivery_City,
				@Delivery_Post_Code,
				GETDATE(),
				@User_ID,
    			@Company_ID,
    			@AW_YesNo_Delivery_Address,
    			@AW_YesNo_Invoice
			)
			
		SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
		
		INSERT INTO AS_Transactions_Address
			(
				AS_Transactions_ID, 
				AS_Transactions_Address_Detail_ID, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID
			)
		VALUES
			(
				@AS_Transactions_ID,
				@AS_Transactions_Address_Detail_ID,
				GETDATE(),
				@User_ID,
    			@Company_ID
			)	
	--END
	--ELSE
	--BEGIN
	--	INSERT INTO AS_Transactions_Address
	--		(
	--			AS_Transactions_ID, 
	--			AS_Transactions_Address_Detail_ID, 
	--			Date_Captured, 
	--			User_ID, 
	--			AW_User_Companies_ID
	--		)
	--	VALUES
	--		(
	--			@AS_Transactions_ID,
	--			@AS_Transactions_Address_Detail_ID,
	--			GETDATE(),
	--			@User_ID,
 --   			@Company_ID
	--		)		
	--END
SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Select
--Purpose       :Select address details used on Invoices
--Functionality :Select address details used on Invoices
--Date          :2013-01-02
--Authors       :RL
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Select]
    (    	    	
    	@AS_Transactions_ID int
    )
AS 

	SET NOCOUNT ON

	IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions_Address
			WHERE AS_Transactions_ID = @AS_Transactions_ID
		)
	BEGIN
		SELECT AS_Transactions_ID,
			   Customer_Name AS 'Customer_Name',
			   Inv_Address1 AS 'Inv_Address1',
			   Inv_Address2 AS 'Inv_Address2',
			   Inv_City AS 'Inv_City',
			   Inv_Code AS 'Inv_Code',		
			   Tax_Number As 'Tax_Number',	   
			   Cell_No AS 'Cell_No',
			   Email AS 'Email',
			   Delivery_Address AS 'Delivery_Address',
			   Delivery_Suburb AS 'Delivery_Suburb',
			   Delivery_City AS 'Delivery_City',
			   Delivery_Post_Code AS 'Delivery_Post_Code'
		FROM AS_Transactions_Address_Detail d
			INNER JOIN AS_Transactions_Address a 
				ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID	
		WHERE a.AS_Transactions_ID = @AS_Transactions_ID
	END
	ELSE
	BEGIN
		SELECT 
			0 AS 'AS_Transactions_ID',
			'' AS 'Customer_Name',
			'' AS 'Inv_Address1',
			'' AS 'Inv_Address2',
			'' AS 'Inv_City',
			'' AS 'Inv_Code',
			'' AS 'Tax_Number',			
			'' AS 'Cell_No',
			'' AS 'Email',
			'' AS 'Delivery_Address',
			'' AS 'Delivery_Suburb',
			'' AS 'Delivery_City',
			'' AS 'Delivery_Post_Code'
			
	END
	
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Update
--Purpose       :Updates address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-07-09
--Authors       :RL
--Mods
--V6.3	RL	2017-02-28	:Don't remove address details
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Update]
    (    	    	
    	@AS_Transactions_Address_Detail_ID	int,
    	@Inv_Customer_Name					varchar(100),	--1
		@Inv_Address1						varchar(40),	--2
		@Inv_Address2						varchar(40),	--3
		@Inv_City							varchar(30),	--4
		@Inv_Code							varchar(10),	--5
		@Inv_Tax_Number						varchar(16),	--6
		@Cell_No							varchar(16),	--7
		@Email								varchar(100),	--8
		@Delivery_Address					varchar(40),
		@Delivery_Suburb					varchar(40),
		@Delivery_City						varchar(30),
		@Delivery_Post_Code					varchar(10),
		@User_ID							int,
		@AC_Customers_ID					int,
		@AS_Transactions_ID					int,
		@Company_ID							int		
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
    	@AW_YesNo_Delivery_Address	int,
    	@AW_YesNo_Invoice			int,
    	@Exact_Record				int,
    	@Other_Record				int

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 0
	SET @Exact_Record = 0
	SET @Other_Record = 0
		
	SET @Inv_Customer_Name = LTRIM(RTRIM(ISNULL(@Inv_Customer_Name,'')))
	SET @Inv_Address1 = LTRIM(RTRIM(ISNULL(@Inv_Address1,'')))
	SET @Inv_Address2 = LTRIM(RTRIM(ISNULL(@Inv_Address2,'')))
	SET @Inv_Code = LTRIM(RTRIM(ISNULL(@Inv_Code,'')))
	SET @Inv_City = LTRIM(RTRIM(ISNULL(@Inv_City,'')))
	SET @Inv_Tax_Number = LTRIM(RTRIM(ISNULL(@Inv_Tax_Number,'')))
	SET @Cell_No = LTRIM(RTRIM(ISNULL(@Cell_No,'')))
	SET @Email = LTRIM(RTRIM(ISNULL(@Email,'')))	
	SET @Delivery_Address = LTRIM(RTRIM(ISNULL(@Delivery_Address,'')))
	SET @Delivery_Suburb = LTRIM(RTRIM(ISNULL(@Delivery_Suburb,'')))
	SET @Delivery_City = LTRIM(RTRIM(ISNULL(@Delivery_City,'')))
	SET @Delivery_Post_Code = LTRIM(RTRIM(ISNULL(@Delivery_Post_Code,'')))

	IF (
		@Inv_Customer_Name <> '' Or
		@Inv_Address1 <> '' Or
		@Inv_Address2 <> '' Or
		@Inv_Code <> '' Or
		@Inv_City <> '' Or
		@Inv_Tax_Number <> '' Or
		@Cell_No <> '' Or
		@Email <> ''
		)
	BEGIN
		SET @AW_YesNo_Invoice = 1
	END

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	
	
	SELECT @Other_Record = COUNT(*)
	FROM AS_Transactions_Address ta
		INNER JOIN AS_Transactions_Address_Detail ad
			ON ta.AS_Transactions_Address_Detail_ID = ad.AS_Transactions_Address_Detail_ID
	WHERE ta.AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	AND AS_Transactions_ID <> @AS_Transactions_ID	
	
	--IF (@AW_YesNo_Invoice = 0 AND @AW_YesNo_Delivery_Address = 0)
	--BEGIN
	--	DELETE FROM AS_Transactions_Address_Detail WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	--	DELETE FROM AS_Transactions_Address WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	--END
	--ELSE
	--BEGIN
	IF (@AS_Transactions_Address_Detail_ID = 0) OR (@Other_Record > 0)
	BEGIN	
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				Cell_No,
				Email, 
				Delivery_Address, 
				Delivery_Suburb, 
				Delivery_City, 
				Delivery_Post_Code,
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID,
				AW_YesNo_Delivery_Address,
				AW_YesNo_Invoice
			)
		VALUES
			(
				@AC_Customers_ID,
				@Inv_Customer_Name,
				@Inv_Address1,
				@Inv_Address2,
				@Inv_Code,
				@Inv_City,
				@Inv_Tax_Number,
				@Cell_No,
				@Email,
				@Delivery_Address,
				@Delivery_Suburb,
				@Delivery_City,
				@Delivery_Post_Code,
				GETDATE(),
				@User_ID,
    			@Company_ID,
    			@AW_YesNo_Delivery_Address,
    			@AW_YesNo_Invoice
			)
			
		SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
		
		IF @Other_Record = 0
		BEGIN
			INSERT INTO AS_Transactions_Address
				(
					AS_Transactions_ID, 
					AS_Transactions_Address_Detail_ID, 
					Date_Captured, 
					User_ID, 
					AW_User_Companies_ID
				)
			VALUES
				(
					@AS_Transactions_ID,
					@AS_Transactions_Address_Detail_ID,
					GETDATE(),
					@User_ID,
    				@Company_ID
    			)
    	END
    	ELSE
    	BEGIN
    		UPDATE AS_Transactions_Address
    		SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
    		WHERE AS_Transactions_ID = @AS_Transactions_ID
    	END
	END
	ELSE
	BEGIN	 
		UPDATE AS_Transactions_Address_Detail
		SET
			Customer_Name = @Inv_Customer_Name,
			Inv_Address1 = @Inv_Address1,
			Inv_Address2 = @Inv_Address2,
			Inv_Code = @Inv_Code,
			Inv_City = @Inv_City,
			Tax_Number = @Inv_Tax_Number,
			Cell_No = @Cell_No,
			Email = @Email,			
			Delivery_Address = @Delivery_Address,
			Delivery_Suburb = @Delivery_Suburb,
			Delivery_City = @Delivery_City,
			Delivery_Post_Code = @Delivery_Post_Code
		WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
			  
	END
SET NOCOUNT ON

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description	:sp_AS_Transactions_Xref
--Purpose       :INSERTS AS_Transactions_Xref row and
--              :deactivates recalled AS_Transactions used as source in POS
--              :
--Date			:2002/12/26
--Authors		:TB
--MODS          :22/05/04 - Added decrement the RESERVED values in AP_Products
--2004.4.8      :26/04/10 - Commented Decrement the RESERVED values - NO LONGER USED
--V6.3	RL	2017-10-10	:Added Back Order Functionality
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transactions_Xref]
	(
		@SourceTranID int,
		@DestinTranID int,
        @UserID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @XrefID int
--             @ProductID int,
--             @Qty decimal(9, 3),
--             @Reserved decimal(9, 3),
--             @TranTypeID tinyint
    
    BEGIN

        IF NOT EXISTS
            (
                SELECT AS_Transactions_Xref_ID
                FROM AS_Transactions_Xref
                WHERE AS_Transactions_ID = @DestinTranID
    
            )
            BEGIN
                INSERT AS_Transactions_Xref
                    (
                        AS_Transactions_ID,
                        [User_ID],
                        AW_User_Companies_ID
                    )
                VALUES
                    (
                        @DestinTranID,
                        @UserID,
                        @CompanyID
                    )

                SET @XrefID = (SELECT scope_identity())

            END
        ELSE
            BEGIN
                SELECT @XrefID = AS_Transactions_Xref_ID
                FROM AS_Transactions_Xref
                WHERE AS_Transactions_ID = @DestinTranID
            END

--------------------------------------------------------
-- INSERT the Transactions Xref
--------------------------------------------------------
        INSERT AS_Transactions_Xref_Sources
            (
                AS_Transactions_Xref_ID,
                AS_Transactions_ID,
                [User_ID],
                AW_User_Companies_ID
            )
        VALUES
            (
                @XrefID,
                @SourceTranID,
                @UserID,
                @CompanyID
            )

--------------------------------------------------------
-- DE-ACTIVATE the Source Transaction
--------------------------------------------------------
        UPDATE AS_Transactions
        SET Slu_AW_Active_ID = 0
        WHERE AS_Transactions_ID = @SourceTranID

--------------------------------------------------------
-- Remove back order items placed in the purchase order shopping list
--------------------------------------------------------
		IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @SourceTranID AND
				Sys_AW_Transaction_Types_ID = 16
		)
		BEGIN
			UPDATE AO_Order_Candidates
			SET Qty = Qty - Back_Order
			FROM AO_Order_Candidates o
				INNER JOIN AS_Transaction_Details d
					On o.AP_Products_ID = d.AP_Products_ID
			WHERE d.AS_Transactions_ID = @SourceTranID AND
				Back_Order <> 0

			DELETE FROM AO_Order_Candidates
			WHERE Qty <= 0
		END



-- COMMENTED 2004.4.8 - NO LONGER USED
-- --------------------------------------------------------
-- -- Decrement the RESERVED values
-- --------------------------------------------------------
-- 
--         SELECT @TranTypeID = Sys_AW_Transaction_Types_ID
--         FROM AS_Transactions
--         WHERE AS_Transactions_ID = @SourceTranID
-- 
-- 
--     --> Define a CURSOR to update the RESERVED in AP_Products
--     	DECLARE Tran_Cursor CURSOR FOR
--             (
--                 SELECT AP_Products_ID,
--                        ISNULL(Quantity, 0)
--                 FROM AS_Transaction_Details
--                 WHERE AS_Transactions_ID = @SourceTranID
--             )
--     
--     	OPEN Tran_Cursor
--     
--         	FETCH NEXT FROM Tran_Cursor 
--         	INTO
--                 @ProductID,
--                 @Qty
-- 
--         	
--         	WHILE @@FETCH_STATUS = 0
--         	BEGIN
-- 
--                 IF @TranTypeID = 1        --Quote
--                     BEGIN
--                         SELECT @Reserved = Quote_Reserved
--                         FROM AP_Products
--                         WHERE AP_Products_ID = @ProductID
-- 
--                         IF @Reserved - @Qty < 0
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Quote_Reserved = 0
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                         ELSE
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Quote_Reserved = Quote_Reserved - @Qty
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                     END
--                 ELSE
--                 IF @TranTypeID = 2        --Jobcard
--                     BEGIN
--                         SELECT @Reserved = Job_Reserved
--                         FROM AP_Products
--                         WHERE AP_Products_ID = @ProductID
-- 
--                         IF @Reserved - @Qty < 0
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Job_Reserved = 0
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                         ELSE
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Job_Reserved = Job_Reserved - @Qty
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                     END
-- 
-- 
--                 ELSE
--                 IF @TranTypeID = 16       --Sales Order
--                     BEGIN
--                         SELECT @Reserved = Sales_Order_Reserved
--                         FROM AP_Products
--                         WHERE AP_Products_ID = @ProductID
-- 
--                         IF @Reserved - @Qty < 0
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Sales_Order_Reserved = 0
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                         ELSE
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Sales_Order_Reserved = Sales_Order_Reserved - @Qty
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                     END
-- 
-- 
-- 
--             	FETCH NEXT FROM Tran_Cursor 
--             	INTO
--                     @ProductID,
--                     @Qty
--         
--             END
--     	
--     	CLOSE Tran_Cursor
--     
--     	DEALLOCATE Tran_Cursor


    END


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AS_Update_Email_Marketing_Customers
--Purpose       :Updates AC_Customers with UI grid mods
--Date          :2004/10/19
--Authors       :TB
--Version       :1.0.0
--MODS:
--2004.3.3      :29/10/06 - Added input parameter to select if AC_Customers or
--              :           AC_Prospects table being updated
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AS_Update_Email_Marketing_Customers
    (
    	@CustomerID int,
        @SendEmail tinyint,
        @CustNo varchar(10),
        @HomeEmail varchar(40),
        @CellNo varchar(16),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @UpdateTable tinyint
    )

AS

SET NOCOUNT ON

    IF @UpdateTable = 0
        BEGIN
            IF EXISTS
                (
                    SELECT AC_Customers_ID
                    FROM AC_Customers
                    WHERE AC_Customers_ID = @CustomerID
                )
                BEGIN
                    UPDATE AC_Customers
                    SET AW_YesNo_Send_Email_ID = @SendEmail,
                        Customer_Number = @CustNo,
                        Home_Email = @HomeEmail,
                        Cell_No = @CellNo,
                        Post_Box = @PostBox,
                        Post_Office = @PostOffice,
                        Post_Code = @PostCode
                    WHERE AC_Customers_ID = @CustomerID
                END        END

    ELSE
    IF @UpdateTable = 2
        BEGIN
            IF EXISTS
                (
                    SELECT AC_Prospects_ID
                    FROM AC_Prospects
                    WHERE AC_Prospects_ID = @CustomerID
                )
                BEGIN
                    UPDATE AC_Prospects
                    SET AW_YesNo_Send_Email_ID = @SendEmail,
                        Customer_Number = @CustNo,
                        Home_Email = @HomeEmail,
                        Cell_No = @CellNo,
                        Post_Box = @PostBox,
                        Post_Office = @PostOffice,
                        Post_Code = @PostCode
                    WHERE AC_Prospects_ID = @CustomerID
                END        END



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AS_Update_Mail_Merge_Customers
--Purpose       :Updates AC_Customers with UI grid mods
--Date          :2007/12/05
--Authors       :TB
--MODS          :    
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AS_Update_Mail_Merge_Customers
    (
    	@CustomerID int,
        @SendEmail tinyint,
        @CustNo varchar(10),
        @FaxNo varchar(16),
        @HomeEmail varchar(40),
        @Contact varchar(30),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @StreetAddress varchar(40),
        @Suburb varchar(30),
        @City varchar(30),
        @StreetCode varchar(10),
        @UpdateTable tinyint
    )

AS

SET NOCOUNT ON

    IF @UpdateTable = 0
        BEGIN
            IF EXISTS
                (
                    SELECT AC_Customers_ID
                    FROM AC_Customers
                    WHERE AC_Customers_ID = @CustomerID
                )
                BEGIN
                    UPDATE AC_Customers
                    SET AW_YesNo_Send_Email_ID = @SendEmail,
                        Customer_Number = @CustNo,
                        Fax_No = @FaxNo,
                        Home_Email = @HomeEmail,
                        Contact_Name = @Contact,
                        Post_Box = @PostBox,
                        Post_Office = @PostOffice,
                        Post_Code = @PostCode,
                        Street_Address = @StreetAddress,
                        Suburb = @Suburb,
                        City = @City,
                        Street_Post_Code = @StreetCode
                    WHERE AC_Customers_ID = @CustomerID
                END        END

    ELSE
    IF @UpdateTable = 2
        BEGIN
            IF EXISTS
                (
                    SELECT AC_Prospects_ID
                    FROM AC_Prospects
                    WHERE AC_Prospects_ID = @CustomerID
                )
                BEGIN
                    UPDATE AC_Prospects
                    SET AW_YesNo_Send_Email_ID = @SendEmail,
                        Customer_Number = @CustNo,
                        Fax_No = @FaxNo,
                        Home_Email = @HomeEmail,
                        Contact_Name = @Contact,
                        Post_Box = @PostBox,
                        Post_Office = @PostOffice,
                        Post_Code = @PostCode,
                        Street_Address = @StreetAddress,
                        Suburb = @Suburb,
                        City = @City,
                        Street_Post_Code = @StreetCode
                    WHERE AC_Prospects_ID = @CustomerID
                END        END



SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AS_Update_Transaction_Activity
--Purpose       :
--Date          :2007/08/09
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AS_Update_Transaction_Activity
	(
        @TranID int,
        @Active tinyint
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AS_Transactions_ID
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @TranID

        )
        BEGIN
            UPDATE AS_Transactions
            SET Slu_AW_Active_ID = @Active
            WHERE AS_Transactions_ID = @TranID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Update_Zero_Cost_Transaction
--Purpose       :UPDATE AS_Transaction_Details Cost
--Date          :2004/07/11
--Authors       :TB
--MODS          :
--2004.4.2      :13/11/08 - Replaced @Cost with @UnitCost to prevent confusion
--RL	V6.0	2014-10-15 - Update transaction master cost as well for Day End GL entries
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Update_Zero_Cost_Transaction]
	(
        @TranDetailID int,
        @UnitCost money
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int
	DECLARE @AS_Transactions_ID int
	DECLARE @Master_Cost int	
	
    SET @ReturnValue = 0
	SET @AS_Transactions_ID = 0
	SET @Master_Cost = 0

    IF EXISTS
        (
            SELECT AS_Transaction_Details_ID
            FROM AS_Transaction_Details
            WHERE AS_Transaction_Details_ID = @TranDetailID

        )
        BEGIN
            UPDATE AS_Transaction_Details
            SET Unit_Cost = @UnitCost
            WHERE AS_Transaction_Details_ID = @TranDetailID

			Select @AS_Transactions_ID = AS_Transactions_ID
			From AS_Transaction_Details
			Where AS_Transaction_Details_ID = @TranDetailID
			
			Select @Master_Cost = SUM(ISNULL(Unit_Cost,0) * ISNULL(Quantity,0))
			From AS_Transaction_Details
			Where AS_Transactions_ID = @AS_Transactions_ID
			
			Update AS_Transactions
			Set Total_Cost = @Master_Cost
			Where AS_Transactions_ID = @AS_Transactions_ID
			
            SET @ReturnValue = 1

        END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AS_Zero_Sales_Order_Item_Qty
--Purpose       :Delete a Sales Order item
--Date          :08 JUN 2008
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE             Procedure sp_AS_Zero_Sales_Order_Item_Qty
    (
        @OrderID int
    )

AS

SET NOCOUNT ON


	UPDATE AS_Sales_Order_Details
	SET Quantity = 0
	WHERE AS_Sales_Order_Details_ID = @OrderID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















---------------------------------------------------------------------------------
--Description   :sp_AT_Delete_Task
--Purpose       :Deletes a selected Task
--Functionality :
--Parameters    :
--Date          :2003/05/09
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AT_Delete_Task
    (
        @TaskID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AT_Tasks_ID
            FROM AT_Tasks
            WHERE AT_Tasks_ID = @TaskID

        )
        BEGIN
            DELETE AT_Tasks
            WHERE AT_Tasks_ID = @TaskID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   :sp_AT_Insert_Subject_Specific_Task
--Purpose       :This is used by the Catalogs to insert Tasks for the specified 
--				:Subject Type (Catalog)
--Date          :2003/06/16
--Authors       :TB
--Version       :1.0.0
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AT_Insert_Subject_Specific_Task
    (
    
    	@StartDate datetime,
    	@DueDate datetime,
        @ALTERdFor int,
        @ALTERdBy int,
    	@Subject_Type_ID int,
    	@SubjectID int, 
    	@Remind bit,
    	@Message varchar(200),
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    INSERT AT_Tasks
        (
            Start_Date,
            Due_Date,
            Remind,
            Task_Message,
            Actor1_ID,
            Actor2_ID,
            Sys_AT_Subject_Type_ID,
            Subject_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
	VALUES
        (
            @StartDate,
            @DueDate,
            @Remind,
            @Message,
            @ALTERdBy,
            @ALTERdFor,
            @Subject_Type_ID,
            @SubjectID,
            getdate(),
            @ALTERdBy,
            @CompanyID,
            1
        )












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AT_Insert_Update_Task
--Purpose       :Insert/Update AT_Tasks
--Functionality :
--Date          :2003/05/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           Procedure sp_AT_Insert_Update_Task
    (
        @Remind bit = 0, 
        @Message varchar(200) = '',	
        @Start_Date datetime = NULL, 
        @Date_Started datetime = NULL,
        @Due_Date datetime = NULL,
        @Date_Completed datetime = NULL,  
        @Actual_Work varchar(20) = '', 
        @Actor1_ID int = NULL ,
        @Actor2_ID int = NULL,
        @Subject_Type_ID tinyint = NULL,
        @Subject_ObjectName varchar(20) = '',	
        @Subject_ID int = NULL, 
        @Sys_AT_Status_ID int = NULL,
        @Sys_AT_Notifications_ID int = NULL,
        @Date_Captured datetime = NULL,
        @User_ID int = NULL,
        @AW_User_Companies_ID int = NULL,
        @Slu_AW_Active_ID tinyint = 1,
        @AT_Tasks_ID int = -1
    )

AS

SET NOCOUNT ON

	DECLARE @ReturnCode int

    SET @ReturnCode = 0        -- 0 = Unsuccessful (False)

	IF @AT_Tasks_ID > 0 
		BEGIN
			IF EXISTS( SELECT AT_Tasks_ID
                       FROM AT_Tasks
                       WHERE AT_Tasks_ID = @AT_Tasks_ID)

                BEGIN

    				UPDATE AT_Tasks
                    SET Remind = @Remind, 
                        Task_Message = @Message,                    
                        Start_Date = @Start_Date, 
                        Date_Started = @Date_Started,
                        Due_Date = @Due_Date,
                        Date_Completed = @Date_Completed,  
                        Actual_Work  = @Actual_Work, 
                        Actor1_ID  = @Actor1_ID,
                        Actor2_ID = @Actor2_ID,
                        Sys_AT_Subject_Type_ID = @Subject_Type_ID,
                        Subject_ObjectName = LEFT(@Subject_ObjectName, 20),                     
                        Subject_ID = @Subject_ID,
                        Sys_AT_Status_ID = @SYS_AT_Status_ID,
                        Sys_AT_Notifications_ID = @SYS_AT_Notifications_ID,
                        [User_ID]  = @User_ID,
                        AW_User_Companies_ID = @AW_User_Companies_ID,
                        Slu_AW_Active_ID = @Slu_AW_Active_ID 
    				WHERE AT_Tasks_ID = @AT_Tasks_ID

                    SET @ReturnCode = 1       -- 1 = Successful (True)
                
                    RETURN @ReturnCode

                END

			ELSE
                BEGIN
    				INSERT AT_Tasks
                        (
                            Remind, 
                            Task_Message,
                            Start_Date, 
                            Date_Started,
                            Due_Date,
                            Date_Completed,  
                            Actual_Work , 
                            Actor1_ID,
                            Actor2_ID,
                            Sys_AT_Subject_Type_ID,
                            Subject_ObjectName, 
                            Subject_ID,
                            Sys_AT_Status_ID,
                            Sys_AT_Notifications_ID,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID,
                            Slu_AW_Active_ID
                        )
    				VALUES
                        (
                            @Remind, 
                            @Start_Date, 
                            @Date_Started,
                            @Due_Date,
                            @Date_Completed,  
                            @Actual_Work, 
                            @Message,	
                            @Actor1_ID,
                            @Actor2_ID,
                            @Subject_ObjectName, 
                            @Subject_Type_ID,
                            @Subject_ID,
                            @Sys_AT_Status_ID,
                            @Sys_AT_Notifications_ID,
                            getdate(),
                            @User_ID,
                            @AW_User_Companies_ID ,
                            @Slu_AW_Active_ID
                        )

                    SELECT @ReturnCode = scope_identity()
                
                    RETURN @ReturnCode 

                END

		END    --BEGIN
    ELSE    -- INSERT NEW TASK
        BEGIN
            INSERT AT_Tasks
                (
                    Remind, 
                    Task_Message,
                    Start_Date, 
                    Date_Started,
                    Due_Date,
                    Date_Completed,  
                    Actual_Work, 
                    Actor1_ID,
                    Actor2_ID,
                    Sys_AT_Subject_Type_ID,
                    Subject_ObjectName,
                    Subject_ID,
                    Sys_AT_Status_ID,
                    Sys_AT_Notifications_ID,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID,
                    Slu_AW_Active_ID
                )
        	VALUES
                (
                    @Remind, 
                    @Message,
                    @Start_Date, 
                    @Date_Started,
                    @Due_Date,
                    @Date_Completed,  
                    @Actual_Work, 
                    @Actor1_ID,
                    @Actor2_ID,
                    @Subject_Type_ID,
                    @Subject_ObjectName,                
                    @Subject_ID,
                    @Sys_AT_Status_ID,
                    @Sys_AT_Notifications_ID,
                    getdate(),
                    @User_ID,
                    @AW_User_Companies_ID,
                    @Slu_AW_Active_ID
                )
    
            SELECT @ReturnCode = scope_identity()
        
            RETURN @ReturnCode 

        END



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE Procedure sp_AT_Login
   @Username varchar(50) ='',
   @Password varchar(50) = '',
   @CompanyID int = 0
AS
SELECT DISTINCT 
   u.UserName, 
   u.Password, 
   cu.AW_User_Companies_ID, 
   u.AW_Users_ID as ID,
   u.Surname + isnull(', ' + Firstname, '') as Fullname
FROM AW_Users u 
      INNER JOIN AW_Company_Users cu ON u.AW_Users_ID = cu.AW_Users_ID 
WHERE u.UserName = @UserName AND  u.[Password] = @Password AND
   cu.AW_User_Companies_ID = @CompanyID 










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AT_Select_Lookups
--Purpose       :
--Functionality :
--Date          :2003/05/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AT_Select_Lookups
    (
        @Option tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    IF @Option = 1    -- 'User'
        SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + Firstname, '') AS [Description]
        FROM AW_Users
        ORDER BY [Description]

    ELSE
    IF @Option = 2    -- 'Status'
        SELECT Sys_AT_Status_ID AS [ID],
               [Description]
        FROM Sys_AT_Status

    ELSE
    IF @Option = 3    -- 'Notification'
        SELECT Sys_AT_Notifications_ID AS [ID],
               [Description]
        FROM Sys_AT_Notifications

    ELSE
    IF @Option = 4    -- 'Actor'
        SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + Firstname, '') AS [Description]
        FROM AW_Users
        ORDER BY [Description]

--         UNION
-- 
--         SELECT Sys_AT_Actor_Types_ID AS [ID],
--                [Description]
--         FROM Sys_AT_Actor_Types
--         ORDER BY [Description]

    ELSE
    IF @Option = 5    -- 'Company'
        SELECT AW_User_Companies_ID AS [ID],
               Company_Name AS [Description]
        FROM AW_User_Companies

    ELSE
    IF @Option = 6    -- 'Active'
        SELECT Slu_AW_Active_ID AS [ID],
               [Description] AS [Description] 
        FROM Slu_AW_Active
    
    ELSE
    IF @Option = 7    -- 'Subject Type'
        SELECT Sys_AT_Subject_Types_ID AS [ID],
               [Description] AS [Description] 
        FROM Sys_AT_Subject_Types
    
    ELSE
    IF @Option = 8    -- 'YesNo'
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [Description] 
    	FROM Slu_AW_YesNo

    ELSE
    IF @Option = 9    -- 'Customers'
    	SELECT AC_Customers_ID AS [ID], 
    		Surname + ISNULL(', ' + Firstnames, '') AS [Description] 
    	FROM AC_Customers
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Option = 10    -- 'Products'
    	SELECT AP_Products_ID AS [ID], 
            [Description] AS [Description] 
    	FROM AP_Products
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Option = 11    -- 'Suppliers'
    	SELECT AO_Suppliers_ID AS [ID], 
            Supplier_Name AS [Description] 
    	FROM AO_Suppliers
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Option = 12    -- 'GL Accounts'
    	SELECT AB_Accounts_ID AS [ID], 
            [Description] AS [Description] 
    	FROM AB_Accounts
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AT_Select_Subject_Specific_Tasks
--Purpose       :Select tasks based on @Subject_ID
--Functionality :
--Date          :2003/05/09
--Authors       :TB
--Version       :1.0.0
--MODS          :06/01/04 - Changed field sequence to match Task Manager layout
-------------------------------------------------------------------------------

CREATE            Procedure sp_AT_Select_Subject_Specific_Tasks
    (
        @Subject_Type_ID int,
    	@Subject_ID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	SELECT
		t.Remind AS [Remind],
		t.Task_Message AS [Task],
		t.Start_Date AS [Start Date],
		t.Date_Started AS [Started],
		t.Due_Date AS [Due],
		t.Date_Completed AS [Completed],
		t.Actual_Work AS [Worked],
		a1.Actor as [Created By],
		a2.Actor as [Created For],
		t.Actor1_ID,
		t.Actor2_ID,
		st.[Description] AS [Subject Type],
        t.Subject_ID AS [Subject],
        t.Sys_AT_Status_ID AS [Task Status],
        s.[Description] AS [Status],
        t.Sys_AT_Notifications_ID AS [Task Notification],
        n.[Description] AS [Notification],
		t.Date_Captured AS [Date Captured],
		t.[User_ID] AS [UserID],
		a.[Description] AS [Active],
        t.AW_User_Companies_ID AS [CompanyID],
        t.AT_Tasks_ID AS [ID]
	FROM AT_Tasks t
        LEFT JOIN dbo.fn_AT_Get_Actor() a1 
			ON t.Actor1_ID= a1.[ID]
		LEFT JOIN dbo.fn_AT_Get_Actor() a2 
			ON t.Actor2_ID= a2.[ID]
		INNER JOIN Sys_AT_Subject_Types st 
			ON t.Sys_AT_Subject_Type_ID = st.Sys_AT_Subject_Types_ID
		INNER JOIN Sys_AT_Status s 
			ON t.Sys_AT_Status_ID = s.Sys_AT_Status_ID
		INNER JOIN Sys_AT_Notifications n 
			ON t.Sys_AT_Notifications_ID = n.Sys_AT_Notifications_ID
		INNER JOIN Slu_AW_Active a 
			ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
	WHERE t.Sys_AT_Subject_Type_ID = @Subject_Type_ID AND
          t.Subject_ID = @Subject_ID AND 
          t.AW_User_Companies_ID = @CompanyID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE  Procedure sp_AT_Select_Task
   @ID int
AS
   SELECT 
      AT_Tasks_ID as ID , 
      Remind, 
      Start_Date as [StartDate], 
      Date_Started as [DateStarted],
      Due_Date as [DueDate],
      Date_Completed as [DateCompleted],  
      Actual_Work as [ActualWork], 
      Task_Message as [Message],	
      Actor1_ID as [CreatedBy] ,
      Actor2_ID as [CreatedFor],
      Subject_ObjectName as [SubjectType], 
      Subject_ID as [Subject],
      SYS_AT_Status_ID as [Status],
      SYS_AT_Notifications_ID as Notification,
      Date_Captured as [DateCaptured] ,
      User_ID as [User] ,
      AW_User_Companies_ID as Company  ,
      Slu_AW_Active_ID as Active 
   FROM AT_Tasks 
   WHERE AT_Tasks_ID = @ID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AT_Select_Tasks
--Purpose       :Select tasks based on criteria
--Functionality :
--Date          :2003/05/08
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AT_Select_Tasks
    (
    	@Criteria varchar(4000) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

--SET @Criteria = '[Created For] = 2 AND [Company] = 1 AND  (Datediff(day, ''2003/05/08'',[Due]) < = 0 or [Due] IS NULL ) AND  (Datediff(day, ''2003/05/08'',[Completed]) > 0 or [Completed] IS NULL )'

    --> Translate column aliases to respective column names
    IF NOT @Criteria = ''
        BEGIN
            SET @Criteria = REPLACE(@Criteria,'[Remind]','Remind')
            SET @Criteria = REPLACE(@Criteria,'[Message]','Task_Message')
            SET @Criteria = REPLACE(@Criteria,'[Start]','Start_Date')
            SET @Criteria = REPLACE(@Criteria,'[Started]','Date_Started')
            SET @Criteria = REPLACE(@Criteria,'[Due]','Due_Date')
            SET @Criteria = REPLACE(@Criteria,'[Completed]','Date_Completed')
            SET @Criteria = REPLACE(@Criteria,'[Actual work]','Actual_Work')
            SET @Criteria = REPLACE(@Criteria,'[Created by]','Actor1_ID')
            SET @Criteria = REPLACE(@Criteria,'[Created for]','Actor2_ID')
            SET @Criteria = REPLACE(@Criteria,'[Subject type]','Sys_AT_Subject_Type_ID')
            SET @Criteria = REPLACE(@Criteria,'[Subject name]','Subject_ObjectName')
            SET @Criteria = REPLACE(@Criteria,'[Subject_ID]','Subject_ID')
            SET @Criteria = REPLACE(@Criteria,'[Status]','Sys_AT_Status_ID')
            SET @Criteria = REPLACE(@Criteria,'[Notification]','Sys_AT_Notifications_ID')
            SET @Criteria = REPLACE(@Criteria,'[Date Captured]','Date_Captured')
            SET @Criteria = REPLACE(@Criteria,'[User]','User_ID')
            SET @Criteria = REPLACE(@Criteria,'[Company]','AW_User_Companies_ID')
            SET @Criteria = REPLACE(@Criteria,'[Active]','Slu_AW_Active_ID')
            SET @Criteria = REPLACE(@Criteria,'[ID]','AT_Tasks_ID')
            SET @Criteria  = ' WHERE ' + @Criteria
        END

    SET @sql = ' '
    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '    Remind AS [Remind], ' 
    SET @sql = @sql + '    Task_Message AS [Message], '
    SET @sql = @sql + '    Start_Date AS [Start], '
    SET @sql = @sql + '    Date_Started AS [Started], '
    SET @sql = @sql + '    Due_Date AS [Due], '
    SET @sql = @sql + '    Date_Completed AS [Completed], '
    SET @sql = @sql + '    Actual_Work AS [Actual work], '
    SET @sql = @sql + '    Actor1_ID AS [Created by], '
    SET @sql = @sql + '    Actor2_ID AS [Created for], '
    SET @sql = @sql + '    Sys_AT_Subject_Type_ID AS [Subject type], '
    SET @sql = @sql + '    Subject_ObjectName AS [Subject name], '    
    SET @sql = @sql + '    Subject_ID AS [Subject_ID], '
    SET @sql = @sql + '    Sys_AT_Status_ID AS [Status], '
    SET @sql = @sql + '    Sys_AT_Notifications_ID AS [Notification], '
    SET @sql = @sql + '    Date_Captured AS [Date Captured], '
    SET @sql = @sql + '    User_ID AS [User], '
    SET @sql = @sql + '    AW_User_Companies_ID AS [Company], '
    SET @sql = @sql + '    Slu_AW_Active_ID  AS [Active], '
    SET @sql = @sql + '    AT_Tasks_ID AS [ID] '
    
    SET @sql = @sql + ' FROM AT_Tasks ' + @Criteria
    SET @sql = @sql + ' ORDER BY Date_Captured DESC'



SET NOCOUNT OFF


EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE     PROCEDURE sp_AT_Select_Tasks_New
	(
		@Message 			varchar(10)  = '',
		@DateToStart 		datetime = 0 ,
		@DateStarted 		datetime  = 0,
		@DateDue 			datetime  = 0,
		@DateCompleted 	datetime  = 0,
		@ActualWork 		int  = 0,
		@CreatedBy 		int  = 0,
		@CreatedFor 		int  = 0,
		@SubjectTypeID 	int  = 0,
		@SubjectID 		int  = 0,
		@Status 			int  = 0,
		@Notification 		int  = 0,
		@DateCaptured 	datetime = 0 ,
		@UserID 			int  = 0,
		@CompanyID 		int  = 0,
		@ActiveID 			int  = 0,
		@TaskID 			int = 0
	)
AS

	DECLARE @Filter varchar(4000)
-- 	IF NOT @Message = '' then
-- 		SET @Filter = ' Task_Message like ''%' + @Message +'%'''
-- 	IF NOT @DateToStart = 0
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = ' Start_Date
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END
-- 	IF
-- 		BEGIN 
-- 			IF @Filter = ''
-- 				SET @Filter = 
-- 			ELSE
-- 				SET @Filter = @Filter + ' ' 
-- 		END








--       Remind, 
--       Task_Message as [Message],	
--       Start_Date as [Start], 
--       Date_Started as [Started],
--       Due_Date as [Due],
--       Date_Completed as [Completed],  
--       Actual_Work as [Actual Work], 
--       Actor1_ID  as [Created By],
--       Actor2_ID as [Created For],
--       Subject_ObjectName as [Subject Type], 
--       Subject_ID as Subject,
--       SYS_AT_Status_ID as Status,
--       SYS_AT_Notifications_ID as Notification,
--       Date_Captured  as [Date Captured],
--       User_ID  as [User],
--       AW_User_Companies_ID as [Company],
--       Slu_AW_Active_ID  as [Active],
--       AT_Tasks_ID as ID  










--------------------------------------------------------------------
	SELECT * FROM vw_AT_Tasks
	--WHERE 


-- 	DECLARE @spMessage 			varchar(10) 
-- 	DECLARE @spDateToStart 			varchar(10) 
-- 	DECLARE @spDateStarted 			varchar(10) 
-- 	DECLARE @spDateDue 			varchar(10) 
-- 	DECLARE @spDateCompleted 		varchar(10) 
-- 	DECLARE @spActualWork 			varchar(10) 
-- 	DECLARE @spCreatedBy 			varchar(10) 
-- 	DECLARE @spCreatedFor 			varchar(10) 
-- 	DECLARE @spSubjectTypeID 		varchar(10) 
-- 	DECLARE @spSubjectID 			varchar(10) 
-- 	DECLARE @spStatus 				varchar(10) 
-- 	DECLARE @spNotification 			varchar(10) 
-- 	DECLARE @spDateCaptured 		varchar(10) 
-- 	DECLARE @spUserID 				varchar(10) 
-- 	DECLARE @spCompany]ID 			varchar(10) 
-- 	DECLARE @spActiveID 				varchar(10) 
-- 	DECLARE @spTaskID 				varchar(10) 
-- 
-- 
-- 	SET @spMessage 			= ''
-- 	SET @spDateToStart 		= '' 
-- 	SET @spDateStarted 		= '' 
-- 	SET @spDateDue 			= '' 
-- 	SET @spDateCompleted 	= '' 
-- 	SET @spActualWork 		= '' 
-- 	SET @spCreatedBy 			= '' 
-- 	SET @spCreatedFor 		= '' 
-- 	SET @spSubjectTypeID 	= '' 
-- 	SET @spSubjectID 			= '' 
-- 	SET @spStatus 				= '' 
-- 	SET @spNotification 		= '' 
-- 	SET @spDateCaptured 		= '' 
-- 	SET @spUserID 			= '' 
-- 	SET @spCompany]ID 		= '' 
-- 	SET @spActiveID 			= '' 
-- 	SET @spTaskID 			= '' 
-- 
-- 
-- 	







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE  PROCEDURE sp_AT_Update_Task
   @AT_Tasks_ID int, 
   @StartDate datetime = Null,
   @CompleteDate datetime = Null,
   @Remind bit = 1
AS
   IF NOT @StartDate IS NULL
      UPDATE AT_Tasks SET Date_Started = @StartDate,
                          Remind = 0 
          WHERE AT_Tasks_ID = @AT_Tasks_ID
   ELSE
   IF NOT @CompleteDate IS NULL
      UPDATE AT_Tasks SET Date_Completed = @CompleteDate,
                          Remind = 0 
            WHERE AT_Tasks_ID = @AT_Tasks_ID
   ELSE
      UPDATE AT_Tasks SET Remind = @Remind WHERE AT_Tasks_ID = @AT_Tasks_ID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








-----------------------------------------------------------------------------
--Description   : sp_AW_8800
--Purpose       : Save Notes/Memo fields and EDIT/INSERT AW_Comments messages
--              : for one Actor (Customer/Product) in ActiveAnalyst
--Parameters    :
--Date          : 05 OCT 2001
--Authors       : TB
--Version       : 1.0.1
-----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_8800
    (
        @CompanyID int,
        @Option tinyint,        --1 = update AP_Products.Memo, 2 = update/insert AW_Comments
        @ActorTypeID int,       --Customer = -1, Product = -2
        @ActorEntityID int,     --CustomerID, ProductID
        @Message varchar(1000),
        @UserID int,
        @CommentsID int = 0
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0
    
    IF @Option = 1              --Notes/Memo
        BEGIN
            IF @ActorTypeID = -1    --Customers
                BEGIN
                    UPDATE AC_Customers SET Notes = @Message
                    WHERE AC_Customers_ID = @ActorEntityID
            
                    SET @ReturnValue = 1
                END
            ELSE
            IF @ActorTypeID = -2    --Products        
                BEGIN
                    UPDATE AP_Products SET Memo = @Message
                    WHERE AP_Products_ID = @ActorEntityID
            
                    SET @ReturnValue = 1
                END
        END
    ELSE
    IF @Option = 2            --AW_Comments
        BEGIN
            IF @CommentsID = 0    --INSERT
                BEGIN    
                    INSERT AW_Comments
                        (
                            Actor_ID,
                            Sys_AT_Actor_Types_ID,
                            Comment,
                            [User_ID],
                            AW_User_Companies_ID
                        )
                    VALUES
                        (
                            @ActorEntityID,
                            @ActorTypeID,
                            @Message,
                            @UserID,
                            @CompanyID
                        )
        
                    SET @ReturnValue = 1
                END
            ELSE                --UPDATE
                BEGIN
                    UPDATE AW_Comments SET Comment = @Message,
                           [User_ID] = @UserID
                    WHERE AW_Comments_ID = @CommentsID
        
                    SET @ReturnValue = 1
                END
        END
    
    
    RETURN @ReturnValue






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9900
--Purpose       :Wipe all SALES Transaction tables
--              :
--Parameters    :
--Date          :2002/04/19
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AW_9900]
AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

    SET @ReturnValue = 0

BEGIN

    --First wipe the customer balances
    UPDATE AC_Customers SET Account_Balance = 0,
                            Current_Balance = 0,
                            Days_30 = 0,
                            Days_60 = 0,
                            Days_90 = 0,
                            Days_120 = 0,
                            Days_150 = 0,
                            Days_180 = 0
 

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Cash_Ups]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Cash_Ups]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Day_Ends]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Day_Ends]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Customer_Sales]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_GP]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Sales]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Sales_All]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Sales_Order_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Sales_Order_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Till_Payouts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Till_Payouts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Payments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Sources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Sources]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_CBilling]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_CBilling_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Xref]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Xref]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Xref_Sources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Xref_Sources]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Address]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Address]

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Address_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Address_Detail]
 
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Details_Consignment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Details_Consignment]
 
    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Cash_Ups] (
    	[AS_Cash_Ups_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Cashier_ID] [int] NULL ,
    	[Lup_AS_Tills_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [int] NULL ,
    	[Slu_AS_Coinage_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Slu_AW_Active_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Day_Ends] (
    	[AS_Day_Ends_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Day_End] [smalldatetime] NOT NULL ,
    	[AB_Transaction_Date] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Customer_Sales] (
    	[AS_Enterprise_Customer_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_GP] (
    	[AS_Enterprise_GP_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[TotalSales] [money] NULL ,
    	[TotalCost] [money] NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Sales] (
    	[AS_Enterprise_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Quantity] [decimal](12, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Sales_All] (
    	[AS_Enterprise_Sales_All_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Sales_Order_Details] (
    	[AS_Sales_Order_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Shipping_Cost] [money] NULL ,
    	[Tax_Rate] [decimal](9, 3) NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[AP_Promotion_Products_ID] [int] NULL ,
    	[Promo_Price] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Till_Payouts] (
    	[AS_Till_Payouts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Payout_Type_ID] [tinyint] NULL ,
    	[AB_Account_DR_ID] [int] NULL ,
    	[AB_Account_CR_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Description] [varchar] (36) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Narration] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Payout_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Payout_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Details] (
    	[AS_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Original_Price] [money] NULL ,
    	[Original_Discount] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Commission_Amount] [money] NULL ,
    	[AP_Promotion_Products_ID] [int] NULL ,
    	[AS_Job_References_ID] [int] NULL ,
    	[Serial_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Make] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[TDHeader] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[TDDetail] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL ,
    	[Consignment_Left] [decimal](9, 3) NULL ,
    	[Lup_AP_Product_Bins_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Payments] (
    	[AS_Transaction_Payments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [tinyint] NULL ,
    	[Slu_AS_Card_Institutions_ID] [int] NULL ,
    	[Payor_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Card_Expiry_Date] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Card_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Authorisation_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Banked] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Sources] (
    	[AS_Transaction_Sources_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Transaction_Numbers] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions] (
    	[AS_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total_Cost] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Discount_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Expiry_Date] [smalldatetime] NULL ,
    	[Version_Number] [smallint] NULL ,
    	[Customer_Reference] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Lup_AS_Marketing_Indicators_ID] [int] NULL ,
    	[Lup_AW_Stores_ID] [smallint] NULL ,
    	[Lup_AW_Workstations_ID] [smallint] NULL ,
    	[Lup_AS_Tills_ID] [smallint] NULL ,
    	[Lup_AS_Cashiers_ID] [smallint] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Slu_AW_Currencies_ID] [smallint] NULL ,
    	[Old_Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Cancelled_User_ID] [int] NULL ,
    	[Cancelled_DateTime] [datetime] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Transmitted] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_CBilling] (
    	[AS_Transactions_CBilling_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Network_Identity_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Original_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Manufacturer_Code] [varchar] (18) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Lup_AP_Fail_Reasons_ID] [smallint] NULL ,
    	[Item_No] [smallint] NULL ,
    	[Authorization_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registration_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Odometer_Reading] [varchar] (7) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Make] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model_Year] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Client_ID_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Engine_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Chassis_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AP_Claim_Codes_ID] [smallint] NULL ,
    	[Xmit_Date] [datetime] NULL ,
    	[Xmit_File] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_CBilling_Temp] (
    	[AS_Transactions_CBilling_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
    	[cat_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_date] [datetime] NULL ,
    	[qty] [decimal](9, 3) NULL ,
    	[amount] [money] NULL ,
    	[gls_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[narr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[stock_group] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_apply] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[sys_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[updated] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[interfaced] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_age_month] [smallint] NULL ,
    	[stock_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[area] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_alpha] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[branch] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_amount] [money] NULL ,
    	[cost_amount] [money] NULL ,
    	[rep_comm] [money] NULL ,
    	[process_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[rep_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[acct_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[disc_amnt] [money] NULL ,
    	[std_sell_price] [money] NULL ,
    	[drs_trs_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_type] [smallint] NULL ,
    	[acc_month] [smallint] NULL ,
    	[acc_year] [smallint] NULL ,
    	[con_acct_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_int01] [smallint] NULL ,
    	[cntno] [smallint] NULL ,
    	[line_disc1] [decimal](9, 3) NULL ,
    	[line_disc2] [decimal](9, 3) NULL ,
    	[stock_sell1] [money] NULL ,
    	[no_of_deals] [smallint] NULL ,
    	[zz_date01] [datetime] NULL ,
    	[zz_date02] [datetime] NULL ,
    	[zz_date03] [datetime] NULL ,
    	[special_instr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[deals_flag] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[deals_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_exempt_member] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[cmonth] [smallint] NULL ,
    	[cyear] [smallint] NULL ,
    	[rep_call_status] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drsdiv_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[crs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_date] [datetime] NULL ,
    	[creation_time] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_userid] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_proc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[item_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[rep_code2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[qty2] [decimal](9, 3) NULL ,
    	[deposit_amount] [decimal](9, 3) NULL ,
    	[job_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[line_disc_amnt] [decimal](9, 3) NULL ,
    	[carhire_cntno] [smallint] NULL ,
    	[currency] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[exch_rate] [money] NULL ,
    	[cyear_month] [smallint] NULL ,
    	[zz_date04] [datetime] NULL ,
    	[zz_date05] [datetime] NULL ,
    	[zz_int02] [smallint] NULL ,
    	[zz_int03] [smallint] NULL ,
    	[zz_int04] [smallint] NULL ,
    	[zz_int05] [smallint] NULL ,
    	[zz_dec01] [decimal](9, 3) NULL ,
    	[zz_dec02] [decimal](9, 3) NULL ,
    	[zz_dec03] [decimal](9, 3) NULL ,
    	[zz_dec04] [decimal](9, 3) NULL ,
    	[zz_dec05] [decimal](9, 3) NULL ,
    	[zz_log01] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log02] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log03] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log04] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log05] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log06] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log07] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char01] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char02] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char03] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char04] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char05] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[key_glstrs] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[key_history] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[dumped] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[company_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[branch_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[crs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[prd_grp_descr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[stk_descry] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[status_ind] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments3] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments4] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments5] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments6] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments7] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments8] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[database_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[system_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_reg_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[email] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_cell_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_email_address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Transactions] (
    	[AS_Transactions_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Source_AS_Transactions_ID] [int] NULL ,
    	[Destination_AS_Transactions_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Xref] (
    	[AS_Transactions_Xref_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AW_YesNo_Checked_ID] [tinyint] NULL ,
    	[Checked_User_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Xref_Sources] (
    	[AS_Transactions_Xref_Sources_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_Xref_ID] [int] NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]



	CREATE TABLE [dbo].[AS_Transactions_Address](
		[AS_Transactions_Address_ID] [int] IDENTITY(1,1) NOT NULL,
		[AS_Transactions_ID] [int] NOT NULL,
		[AS_Transactions_Address_Detail_ID] [int] NOT NULL,
		[Date_Captured] [datetime] NOT NULL,
		[User_ID] [int] NOT NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL
	) ON [PRIMARY]


	CREATE TABLE [dbo].[AS_Transactions_Address_Detail](
		[AS_Transactions_Address_Detail_ID] [int] IDENTITY(1,1) NOT NULL,
		[AC_Customers_ID] [int] NOT NULL,
		[Inv_Address1] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_Address2] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_City] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_Code] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Address] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Suburb] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_City] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Post_Code] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Date_Captured] [datetime] NOT NULL,
		[User_ID] [int] NOT NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL,
		[Customer_Name] [varchar](100) NULL,
		[Tax_Number] [varchar](16) NULL,
		[AW_YesNo_Delivery_Address] [tinyint] NULL,
		[AW_YesNo_Invoice] [tinyint] NULL
	) ON [PRIMARY]  
  
   
	CREATE TABLE [AS_Transaction_Details_Consignment](
		[AS_Transaction_Details_Consignment_ID] [int] IDENTITY(1,1) NOT NULL,
		[AS_Transaction_Details_ID] [int] NOT NULL,
		[Consignment_ID] [int] NULL,
		[Sys_AW_Transaction_Types_ID] [int] NULL,
		[Quantity] [decimal](9, 3) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL
	) ON [PRIMARY]  


    ALTER TABLE [dbo].[AS_Transaction_Details_Consignment] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transaction_Details_Consignment] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Details_Consignment_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

  
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Cash_Ups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Cash_Ups] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Cash_Ups_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Day_Ends] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Day_Ends] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Day_Ends_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Till_Payouts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Till_Payouts] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Till_Payouts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transaction_Payments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Payments] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Payments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transaction_Sources] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transaction_Sources] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Sources_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_CBilling] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_CBilling_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_CBilling_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_CBilling_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Quotes_Sales] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Xref] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Xref] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Xref_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Xref_Sources] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Xref_Sources] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Xref_Sources_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    ALTER TABLE [dbo].[AS_Transactions_Address_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Address_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Address_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
   
   ALTER TABLE [dbo].[AS_Transactions_Address] ADD  
		CONSTRAINT [PK_AS_Transactions_Address_ID] PRIMARY KEY NONCLUSTERED 
		(
			[AS_Transactions_Address_ID]
		) WITH FILLFACTOR = 80

    ALTER TABLE [dbo].[AS_Transaction_Details] ADD 
    	CONSTRAINT [PK_AS_Transaction_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transaction_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
 
  
    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Customer_Sales_Search] ON [dbo].[AS_Enterprise_Customer_Sales]([Filter], [Customer], [CustNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_GP_Search] ON [dbo].[AS_Enterprise_GP]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_Search] ON [dbo].[AS_Enterprise_Sales]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_All_Search] ON [dbo].[AS_Enterprise_Sales_All]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Sales_Order_Details] ON [dbo].[AS_Sales_Order_Details]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transaction_Details] ON [dbo].[AS_Transaction_Details]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transactions] ON [dbo].[AS_Transactions]([AC_Customers_ID], [AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Day_Ends_Key] ON [dbo].[AS_Day_Ends]([Day_End] DESC ) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Enterprise_Customer_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Customer_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Customer_Sales_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_GP] ADD 
    	CONSTRAINT [PK_AS_Enterprise_GP] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_GP_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Sales_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_Sales_All] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Sales_All] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Sales_All_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Sales_Order_Details] ADD 
    	CONSTRAINT [PK_AS_Sales_Order_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Sales_Order_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Sales_Order_Details_AP_Products_ID] ON [dbo].[AS_Sales_Order_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transaction_Details_AP_Products_ID] ON [dbo].[AS_Transaction_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_PaymentsTranID] ON [dbo].[AS_Transaction_Payments]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_TranSourcesTranID] ON [dbo].[AS_Transaction_Sources]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [PK_AS_Transactions] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Transactions_Date_Captured] ON [dbo].[AS_Transactions]([Date_Captured]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transactions_Transaction_Type] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transactions_Comment] ON [dbo].[AS_Transactions]([Comment]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_ActiveJobSalesOrders] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID], [Slu_AW_Active_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transaction_Date_Type] ON [dbo].[AS_Transactions]([Transaction_Date], [Sys_AW_Transaction_Types_ID], [AW_User_Companies_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_CBilling_Tran_ID] ON [dbo].[AS_Transactions_CBilling]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] ADD 
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_acc] DEFAULT ('SPIRAL') FOR [drs_acc],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_gls_acc] DEFAULT ('N/A') FOR [gls_acc],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_sys_code] DEFAULT ('SPI') FOR [sys_code],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_updated] DEFAULT ('no') FOR [updated],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_interfaced] DEFAULT ('no') FOR [interfaced],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_area] DEFAULT ('N/A') FOR [area],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_acct_type] DEFAULT ('N/A') FOR [acct_type],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_trs_code] DEFAULT ('100') FOR [drs_trs_code],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_vat_exempt_member] DEFAULT ('no') FOR [vat_exempt_member],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_rep_call_status] DEFAULT ('no') FOR [rep_call_status],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log01] DEFAULT ('no') FOR [zz_log01],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log02] DEFAULT ('no') FOR [zz_log02],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log03] DEFAULT ('no') FOR [zz_log03],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log04] DEFAULT ('no') FOR [zz_log04],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log05] DEFAULT ('no') FOR [zz_log05],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log06] DEFAULT ('no') FOR [zz_log06],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log07] DEFAULT ('no') FOR [zz_log07],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_dumped] DEFAULT ('no') FOR [dumped],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_status_ind] DEFAULT ('NE') FOR [status_ind],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_database_id] DEFAULT ('SPIRAL') FOR [database_id]

    
     CREATE  INDEX [IX_SourceTranID] ON [dbo].[AS_Transactions_Transactions]([Source_AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_DestinationTranID] ON [dbo].[AS_Transactions_Transactions]([Destination_AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_Xref_Tran_ID] ON [dbo].[AS_Transactions_Xref]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_Xref_Source_Tran_ID] ON [dbo].[AS_Transactions_Xref_Sources]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

	 CREATE  INDEX [IX_AS_Transactions_ID] ON [dbo].[AS_Transactions_Address]([AS_Transactions_ID]) WITH FILLFACTOR = 80

	 CREATE  INDEX [IX_AC_Customers_ID] ON [dbo].[AS_Transactions_Address_Detail]([AC_Customers_ID]) WITH FILLFACTOR = 80

	 CREATE  INDEX [IX_AS_Transaction_Details_Consignment_AS_Transaction_Details_ID] ON [dbo].[AS_Transaction_Details_Consignment] ([AS_Transaction_Details_ID]) WITH FILLFACTOR = 80

    setuser
    --Defaults AP_Promotion_Products
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'    
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'
    
    setuser

    
    setuser
    --Defaults AP_Promotions
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'

    setuser

    
    setuser
	--Defaults AS_Cash_Ups    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Cash_Ups].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Cash_Ups].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Cash_Ups].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AS_Day_Ends    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Day_Ends].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Day_Ends].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Day_Ends].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Day_Ends].[Slu_AW_Active_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Day_Ends].[AB_Transaction_Ref]'
    
    setuser

    
    setuser
	--Defaults AS_Enterprise_GP        
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_GP].[Pack_Size]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[Total]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalCost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalSales]'

    setuser

    
    setuser
	--Defaults AS_Enterprise_Sales            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales].[Pack_Size]'
    
    setuser

    
    setuser
    --Defaults AS_Enterprise_Sales_All            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales_All].[Pack_Size]'

    setuser

    
    setuser
	--Defaults AS_Sales_Order_Details
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Sales_Order_Details].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Sales_Order_Details].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Sales_Order_Details].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Sales_Order_Details].[Slu_AW_Active_ID]'

	    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Amount]'
        
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Back_Order]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Discount_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Extended_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Original_Price]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Shipping_Cost]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Tax_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Tax_Rate]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Unit_Price]'
    
    setuser

    
    setuser
	--Defaults AS_Till_Payouts
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Till_Payouts].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Till_Payouts].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Till_Payouts].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Till_Payouts].[Slu_AW_Active_ID]'
	
	
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Till_Payouts].[Amount]'
   
    setuser

    
    setuser
	--Defaults AS_Transaction_Details
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Details].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Back_Order]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Commission_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Original_Discount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Quantity]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Unit_Price]'
    
    setuser

    
    setuser
	--Defaults AS_Transaction_Payments
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Payments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Payments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Payments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Payments].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Payments].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transaction_Payments].[Slu_AS_Card_Institutions_ID]'
    
    setuser

    
    setuser
	--Defaults AS_Transaction_Sources        
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Sources].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Sources].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Sources].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Sources].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
	--Defaults AS_Transactions  
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions].[AW_User_Companies_ID]'
	 
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions].[Slu_AW_Active_ID]'   
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Amount]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Cashiers_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Reps_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Tills_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Stores_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Workstations_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Payment_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Transaction_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Version_Number]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_CBilling
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_CBilling].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling].[Slu_AW_Active_ID]'
	

    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Authorization_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Chassis_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Client_ID_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Customer_Number]'    
       
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Engine_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Item_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling].[Lup_AP_Claim_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling].[Lup_AP_Fail_Reasons_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Make]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Manufacturer_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Model]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Model_Year]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Network_Identity_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Odometer_Reading]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Original_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Registration_No]'
       
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Transaction_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Xmit_File]'
   
    setuser

    
    setuser
	--Defaults AS_Transactions_CBilling_Temp
	EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AS_Transactions_CBilling_Temp].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling_Temp].[User_ID]'
		    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling_Temp].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling_Temp].[Slu_AW_Active_ID]'    

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[drs_age_month]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[trs_type]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_Transactions
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Transactions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Transactions].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Transactions].[Amount]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_Xref
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Xref].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Xref].[User_ID]'
	    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Xref].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Xref].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Xref].[AW_YesNo_Checked_ID]'

    setuser

    
    setuser
	--Defaults AS_Transactions_Xref_Sources
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Xref_Sources].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Xref_Sources].[User_ID]'
	    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Xref_Sources].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Xref_Sources].[Slu_AW_Active_ID]'
    
    setuser


    setuser
	--Defaults AS_Transactions_Address    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Address].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Address].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Address].[AW_User_Companies_ID]'
           
    setuser    


    setuser
    --Defaults AS_Transactions_Address    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Address_Detail].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Address_Detail].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Address_Detail].[AW_User_Companies_ID]'
           
          
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Address1]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Address2]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_City]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Address]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Suburb]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_City]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Post_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Customer_Name]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Tax_Number]'
    
    setuser

	setuser
    --Defaults AS_Transaction_Details_Consignment  
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details_Consignment].[Quantity]'

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Details_Consignment].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Details_Consignment].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Details_Consignment].[AW_User_Companies_ID]'
	
	setuser

    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)

    
    ALTER TABLE [dbo].[AS_Transaction_Payments] ADD 
    	CONSTRAINT [FK_AS_Payments_Lup_AW_Payment_Methods] FOREIGN KEY 
    	(
    		[Sys_AW_Payment_Methods_ID]
    	) REFERENCES [dbo].[Sys_AW_Payment_Methods] (
    		[Sys_AW_Payment_Methods_ID]
    	)

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [FK_AS_Transactions_AW_Comments] FOREIGN KEY 
    	(
    		[AW_Comments_ID]
    	) REFERENCES [dbo].[AW_Comments] (
    		[AW_Comments_ID]
    	) NOT FOR REPLICATION ,
    	CONSTRAINT [FK_AS_Transactions_Lup_AS_Tills] FOREIGN KEY 
    	(
    		[Lup_AS_Tills_ID]
    	) REFERENCES [dbo].[Lup_AS_Tills] (
    		[Lup_AS_Tills_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Stores] FOREIGN KEY 
    	(
    		[Lup_AW_Stores_ID]
    	) REFERENCES [dbo].[Lup_AW_Stores] (
    		[Lup_AW_Stores_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Workstations] FOREIGN KEY 
    	(
    		[Lup_AW_Workstations_ID]
    	) REFERENCES [dbo].[Lup_AW_Workstations] (
    		[Lup_AW_Workstations_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Sys_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    
    Alter Table [dbo].[AS_Transactions] nocheck constraint [FK_AS_Transactions_AW_Comments]

    SET @ReturnValue = 1

END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9910
--Purpose       :Wipe all SUPPLIER Account Balances & Transaction tables
--Date          :2001/10/14
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9910]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

BEGIN

    UPDATE AO_Suppliers
    SET Account_Balance = 0,
        Current_Balance = 0,
        Days_30 = 0,
        Days_60 = 0,
        Days_90 = 0,
        Days_120 = 0,
        Days_150 = 0,
        Days_180 = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AO_Order_Items_AO_Orders]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AO_Order_Details] DROP CONSTRAINT FK_AO_Order_Items_AO_Orders

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Ageing_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Supplier_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Supplier_Ageing]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_GRV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_GRV]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_GRV_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_GRV_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Orders]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Orders]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittance_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Remittance_Details_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittances_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Remittances_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Statement_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Statement_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Supplier_Contracts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Supplier_Contracts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Supplier_Product_Discounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Supplier_Product_Discounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transaction_Payments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions_Log]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions_Transactions]

    
    CREATE TABLE [dbo].[AO_Enterprise_Ageing_Temp] (
    	[AO_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier_Name] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Enterprise_Supplier_Ageing] (
    	[AO_Enterprise_Supplier_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SuppNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_GRV] (
    	[AO_GRV_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AO_Orders_ID] [int] NULL ,
    	[Date_Received] [datetime] NULL ,
    	[Delivery_Note_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL,
    	[AO_GRV_ID_Consignment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_GRV_Details] (
    	[AO_GRV_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_GRV_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Qty] [decimal](12, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Trade_Discount_Amount] [money] NULL ,
    	[Rebate_Discount_Amount] [money] NULL ,
    	[Other_Discount_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [int] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Total_Cost] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL ,
    	[AO_GRV_Details_ID_Consignment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Qty_Returned] [decimal](12, 3) NULL ,
    	[Qty_Sold] [decimal](12, 3) NULL ,
    	[Qty_Left] [decimal](12, 3) NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Candidates] (
    	[AO_Order_Candidates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Ready] [bit] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Reviews] [int] NULL ,
    	[Originator] [int] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Candidates_Temp] (
    	[AO_Order_Candidates_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Order_Item] [bit] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Selling] [money] NULL ,
    	[Trade_Discount] [money] NULL ,
    	[Cost] AS (round(([Selling] - [Selling] * [Trade_Discount] / 100),2)) ,
    	[Total_Cost] AS (round(([Order_Qty] * ([Selling] - [Selling] * [Trade_Discount] / 100)),2)) ,
    	[Last_Cost] [money] NULL ,
    	[Outstanding_Order_Qty] [decimal](9, 3) NULL ,
    	[Pending_Order_Qty] [decimal](9, 3) NULL ,
    	[Last_Order_Date] [datetime] NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Details] (
    	[AO_Order_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Orders_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Lead_Time] [smallint] NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Free_Qty] [decimal](9, 3) NULL ,
    	[Back_Order_Qty] [decimal](9, 3) NULL ,
    	[Receipt_Date] [datetime] NULL ,
    	[Received_Qty] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Trade_Discount_Formula_ID] [smallint] NULL ,
    	[Trade_Discount_Amount] [money] NULL ,
    	[Trade_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Rebate_Formula_ID] [smallint] NULL ,
    	[Rebate_Discount_Amount] [money] NULL ,
    	[Rebate_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Other_Discount_Formula_ID] [smallint] NULL ,
    	[Other_Discount_Amount] [money] NULL ,
    	[Other_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Net_Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [int] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Total_Cost] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Orders] (
    	[AO_Orders_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Order_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Version] [tinyint] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier_Rep] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Ordered] [datetime] NULL ,
    	[Confirmation] [tinyint] NULL ,
    	[Confirmation_Date] [datetime] NULL ,
    	[Our_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Invoice_Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Invoice_Total] [money] NULL ,
    	[Admin_Fee] [money] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Tax_Total] [money] NULL ,
    	[Order_Total] [money] NULL ,
    	[Sys_AO_Delivery_Methods_ID] [int] NULL ,
    	[Send_To_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr1] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr2] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr3] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Postal_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Complete] [bit] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Remittance_Details_Temp] (
    	[AO_Remittance_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Remittances_Temp_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Remittances_Temp] (
    	[AO_Remittances_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Credit_Limit] [money] NULL ,
    	[Credit_Terms] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Default_Settlement_Discount] [decimal](7, 2) NULL ,
    	[Supplier_Contact] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Telephone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Cellphone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Fax] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[To_Be_Paid_Total] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Statement_Details] (
    	[AO_Statement_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Statements_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Document_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Document_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Statements] (
    	[AO_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Supplier_Contracts] (
    	[AO_Supplier_Contracts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Packs_Contract_Price] [money] NULL ,
    	[Packs_Contract_Qty] [decimal](6, 3) NULL ,
    	[Packs_Purchased] [decimal](6, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Supplier_Product_Discounts] (
    	[AO_Supplier_Product_Discounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Lup_AO_Discount_Types_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transaction_Payments] (
    	[AO_Transaction_Payments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [tinyint] NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Tran_Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions] (
    	[AO_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Document_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Document_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions_Log] (
    	[AO_Transactions_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Posted_Month_ID] [tinyint] NULL ,
    	[Posted_Year_ID] [int] NULL ,
    	[Current_Month_ID] [tinyint] NULL ,
    	[Current_Year_ID] [int] NULL ,
    	[LastME_Month_ID] [tinyint] NULL ,
    	[LastME_Year_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions_Transactions] (
    	[AO_Transactions_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Source_AO_Transactions_ID] [int] NULL ,
    	[Destination_AO_Transactions_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Tran_Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_GRV] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_GRV] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_GRV_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_GRV_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_GRV_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_GRV_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Order_Candidates] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Order_Candidates_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Orders] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Orders] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Orders_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Supplier_Contracts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Supplier_Contracts] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Supplier_Contracts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Supplier_Product_Discounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Supplier_Discounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Supplier_Product_Discounts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transaction_Payments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Purchase_Transaction_Payments] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transaction_Payments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Purchase_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Purchase_Transactions_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Purchase_Transactions_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Ageing_Temp] ON [dbo].[AO_Enterprise_Ageing_Temp]([Filter], [Supplier_Name], [Supplier_Number]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Supplier_Ageing] ON [dbo].[AO_Enterprise_Supplier_Ageing]([Filter], [Supplier], [SuppNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_Order_Items_Orders_ID] ON [dbo].[AO_Order_Details]([AO_Orders_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittance_Details_Temp] ON [dbo].[AO_Remittance_Details_Temp]([AO_Remittance_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittances_Temp] ON [dbo].[AO_Remittances_Temp]([AO_Remittances_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Statement_Details] ON [dbo].[AO_Statement_Details]([AO_Statement_Details_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Statements] ON [dbo].[AO_Statements]([AO_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Enterprise_Ageing_Temp] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Ageing_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Enterprise_Supplier_Ageing] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Supplier_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Supplier_Ageing_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AO_GRV_AW_Transaction_Types_ID] ON [dbo].[AO_GRV]([Sys_AW_Transaction_Types_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Order_Candidates_AP_Products_ID] ON [dbo].[AO_Order_Candidates]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Order_Candidates_Temp_AP_Products_ID] ON [dbo].[AO_Order_Candidates_Temp]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Order_Details] ADD 
    	CONSTRAINT [PK_Order_Items] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Order_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AO_Order_Items_AP_Products_ID] ON [dbo].[AO_Order_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Orders_AO_Suppliers_ID] ON [dbo].[AO_Orders]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Open_Orders] ON [dbo].[AO_Orders]([Date_Ordered], [Complete]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Statement_Details_Key] ON [dbo].[AO_Statement_Details]([AO_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Statements_Key] ON [dbo].[AO_Statements]([AW_Period_Procedures_ID], [FullName]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Contracts_AP_Products_ID] ON [dbo].[AO_Supplier_Contracts]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Contracts_AP_Suppliers_ID] ON [dbo].[AO_Supplier_Contracts]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Product_Discounts_AP_Products_ID] ON [dbo].[AO_Supplier_Product_Discounts]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Transactions_AO_GRV_ID] ON [dbo].[AO_Transactions]([AO_GRV_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Enterprise_Ageing_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Enterprise_Ageing_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[180+Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[30Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[90Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Account_Balance]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Current]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Payment]'
    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Enterprise_Supplier_Ageing].[CompanyID]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_GRV].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_GRV].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_GRV].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_GRV].[User_ID]'

    
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV].[AO_GRV_ID_Consignment]'
	
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV_Details].[AB_Accounts_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_GRV_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_GRV_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Other_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Rebate_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_GRV_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Trade_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_GRV_Details].[User_ID]'
   
   
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV_Details].[AO_GRV_Details_ID_Consignment]'


	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Returned]'


	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Sold]'


	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Left]'
    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Order_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Originator]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Ready]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Reviews]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Candidates].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates_Temp].[AW_User_Companies_ID]'

    --Computed
    --EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates_Temp].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Order_Candidates_Temp].[Notes]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Outstanding_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Pending_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Selling]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[Service_Level]'

    --Computed
	--EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Trade_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates_Temp].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Back_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Free_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Lead_Time]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Other_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Other_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Other_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Rebate_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Rebate_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Rebate_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Received_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Trade_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Trade_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Trade_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Details].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Admin_Fee]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Orders].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Orders].[AW_Remote_Access_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Orders].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Complete]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Confirmation]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Orders].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Invoice_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Order_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Orders].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Tax_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Orders].[User_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Version]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Remittances_Temp].[Date_Captured]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Statements].[Date_Captured]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Supplier_Contracts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Supplier_Contracts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Contract_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Contract_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Purchased]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Supplier_Contracts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Supplier_Contracts].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Supplier_Product_Discounts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Supplier_Product_Discounts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Supplier_Product_Discounts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Supplier_Product_Discounts].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transaction_Payments].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transaction_Payments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transaction_Payments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transaction_Payments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Transaction_Payments].[Tran_Ref_No]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transaction_Payments].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Payment_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Remittance_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Settlement_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[To_Be_Paid]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[To_Be_Paid_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transactions].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions_Log].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions_Log].[Date_Captured]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions_Transactions].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transactions_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Transactions_Transactions].[Tran_Ref_No]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transactions_Transactions].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AO_Order_Details] ADD 
    	CONSTRAINT [FK_AO_Order_Items_AO_Orders] FOREIGN KEY 
    	(
    		[AO_Orders_ID]
    	) REFERENCES [dbo].[AO_Orders] (
    		[AO_Orders_ID]
    	)

    
    ALTER TABLE [dbo].[AO_Transactions] ADD 
    	CONSTRAINT [FK_AO_Purchase_Transactions_Lup_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    SET @ReturnValue = 1

END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9920
--Purpose       :Wipe all GENERAL LEDGER Transaction tables
--              :
--Parameters    :
--Date          :2001/10/14
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--AW_Company_Banks Not cleared
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

CREATE PROCEDURE [dbo].[sp_AW_9920]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

BEGIN

    --------------------------------------------------------------------------------
    --Clear GL Account Balances

    UPDATE AB_Accounts
    SET AB_Account_Balance = 0,
        Opening_Balance = 0,
        Opening_Date = NULL,
        Opening_Month = 0,
        Opening_Year = 0
    --------------------------------------------------------------------------------
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Journals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Journals

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Recurring]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Recurring

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Budgets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Batches]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Batches]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Detail]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Detail_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Detail_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Header]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Header]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Map]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Map]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Map_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Map_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Notes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Notes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Flow_Forecast_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Flow_Forecast_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Inflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Inflow_Projections]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Outflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Outflow_Projections]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Balance_Sheet]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Income_Statement]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Management_Accounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Trial_Balance]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_GL_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journal_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journal_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring_Details]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures_Deleted]

    
    CREATE TABLE [dbo].[AB_Budgets] (
    	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Slu_AW_Years_ID] [int] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Budget_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Batches] (
    	[AB_Cash_Book_Batches_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Split_Amount] [money] NULL ,
    	[VAT_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Detail] (
    	[AB_Cash_Book_IBS_Detail_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_IBS_Header_ID] [int] NOT NULL ,
    	[Post] [bit] NOT NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NOT NULL ,
    	[Transaction_Date] [datetime] NOT NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Post_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Description] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Detail_Splits] (
    	[AB_Cash_Book_IBS_Detail_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_IBS_Header_ID] [int] NOT NULL ,
    	[AB_Cash_Book_IBS_Detail_ID] [int] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Header] (
    	[AB_Cash_Book_IBS_Header_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NOT NULL ,
    	[Posting_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Banks_ID] [smallint] NOT NULL ,
    	[Date_Posted] [datetime] NOT NULL ,
    	[Start_Date] [datetime] NOT NULL ,
    	[End_Date] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Slu_AW_Years_ID] [smallint] NOT NULL ,
    	[Import_Filename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Auto_Recon] [tinyint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Map] (
    	[AB_Cash_Book_IBS_Map_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Map_1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Map_2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Map_3] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Bank_Description] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Map_Splits] (
    	[AB_Cash_Book_IBS_Map_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[AB_Cash_Book_IBS_Map_ID] [int] NOT NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Notes] (
    	[AB_Cash_Book_IBS_Notes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Note] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transaction_Details] (
    	[AB_Cash_Book_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transactions] (
    	[AB_Cash_Book_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Reference_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Recon_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Flow_Forecast_Temp] (
    	[AB_Cash_Flow_Forecast_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[N1] [tinyint] NULL ,
    	[M1] [bigint] NULL ,
    	[M2] [bigint] NULL ,
    	[M3] [bigint] NULL ,
    	[M4] [bigint] NULL ,
    	[M5] [bigint] NULL ,
    	[M6] [bigint] NULL ,
    	[T1] [bigint] NULL ,
    	[RowTypeID] [tinyint] NULL ,
    	[StartDate] [datetime] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Inflow_Projections] (
    	[AB_Cash_Inflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Inflow_Date] [datetime] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Outflow_Projections] (
    	[AB_Cash_Outflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Outflow_Date] [datetime] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Balance_Sheet] (
    	[AB_Enterprise_Balance_Sheet_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_B1_ID] [int] NULL ,
    	[Sys_AB_B2_ID] [int] NULL ,
    	[Sys_AB_B3_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Income_Statement] (
    	[AB_Enterprise_Income_Statement_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_I1_ID] [int] NULL ,
    	[Sys_AB_I2_ID] [int] NULL ,
    	[Sys_AB_I3_ID] [int] NULL ,
    	[Sys_AB_I4_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[TCRUST] [money] NULL ,
    	[TCSTEEL] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
    	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_I1_ID] [int] NULL ,
    	[Sys_AB_I2_ID] [int] NULL ,
    	[Sys_AB_I3_ID] [int] NULL ,
    	[Sys_AB_I4_ID] [int] NULL ,
    	[Sys_AB_I5_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level5] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
    	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Divisions] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Groups] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_GL_Transactions] (
    	[AB_GL_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[AB_Transaction_Date] [datetime] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Transaction_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journal_Details] (
    	[AB_Journal_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journals] (
    	[AB_Journals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Journal_Date] [datetime] NULL ,
    	[Journal_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Journal_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Recurring] (
    	[AB_Recurring_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Recurring_Date] [datetime] NULL ,
    	[Recurring_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Recurring_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Recurring_Details] (
    	[AB_Recurring_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Recurring_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]


	CREATE TABLE [dbo].[AW_Period_Procedures](
		[AW_Period_Procedures_ID] [int] IDENTITY(1,1) NOT NULL,
		[Sys_AW_Period_Procedure_Types_ID] [int] NULL,
		[Description] [varchar](500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Month] [tinyint] NULL,
		[Year] [smallint] NULL,
		[Month_End_Date] [datetime] NULL,
		[Year_End_Date] [datetime] NULL,
		[Stock_Valuation] [money] NULL,
		[Date_Captured] [smalldatetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY]		


	CREATE TABLE [dbo].[AW_Period_Procedures_Deleted](
		[AW_Period_Procedures_Deleted_ID] [int] IDENTITY(1,1) NOT NULL,
		[AW_Period_Procedures_ID] [int] NULL,
		[Sys_AW_Period_Procedure_Types_ID] [int] NULL,
		[Description] [varchar](500) NULL,
		[Month_ID] [tinyint] NULL,
		[Year_ID] [smallint] NULL,
		[Month_End_Date] [datetime] NULL,
		[Year_End_Date] [datetime] NULL,
		[Stock_Valuation] [money] NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL
	) ON [PRIMARY]		
		
		
	ALTER TABLE [dbo].[AW_Period_Procedures_Deleted] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures_Deleted] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_Deleted_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

			
    ALTER TABLE [dbo].[AW_Period_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Budgets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Batches] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Batches] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Batches_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Detail_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Detail_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Detail_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Header] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Header] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Header_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Map] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Map] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Map_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Map_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Map_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Map_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Notes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Notes] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Notes_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transaction_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transaction_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Inflow_Projections] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Inflow_Projections] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Inflow_Projections_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Outflow_Projections] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Outflow_Projections] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Outflow_Projections_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Balance_Sheet] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Balance_Sheet] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Balance_Sheet_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Income_Statement] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Income_Statement] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Income_Statement_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Management_Accounts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Trial_Balance_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_GL_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_GL_Transactions_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journal_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Journal_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journal_Details_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journals] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Journals] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journals_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Recurring] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Recurring_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([N1], [RowTypeID], [Description]) ON [PRIMARY]

    
     CREATE  INDEX [IX_Cash_Book_IBS_Detail] ON [dbo].[AB_Cash_Book_IBS_Detail]([Transaction_Date], [Bank_Description], [Amount], [Slu_AW_Active_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_Cash_Book_IBS_Detail] ON [dbo].[AB_Cash_Book_IBS_Detail_Splits]([AB_Cash_Book_IBS_Header_ID], [AB_Cash_Book_IBS_Detail_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AB_Cash_Book_IBS_Map_Splits] ON [dbo].[AB_Cash_Book_IBS_Map_Splits]([AW_Company_Banks_ID], [AB_Cash_Book_IBS_Map_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  INDEX [IX_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([AB_Cash_Flow_Forecast_Temp_ID]) ON [PRIMARY]

    
    setuser
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Batches].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Batches].[Slu_AW_Years_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Split_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[VAT_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Batches].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Batches].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Batches].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Batches].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Amount]'
            
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Bank_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Comments]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Post_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Ref_No]'    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail].[Sys_AB_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Detail].[Sys_AW_Tax_Methods_ID]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Tax_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail].[Transaction_Date]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail].[Date_Captured]'
	
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Detail].[User_ID]'   
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Detail].[AW_User_Companies_ID]'  
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Detail].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail_Splits].[AB_Accounts_ID]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Amount]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Detail_Splits].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Tax_Amount]'  

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail_Splits].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Detail_Splits].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Detail_Splits].[AW_User_Companies_ID]'  
	 
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Detail_Splits].[Slu_AW_Active_ID]'   
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[Auto_Recon]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Date_Posted]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[End_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Header].[Import_Filename]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Header].[Posting_Type]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Years_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Start_Date]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Header].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Header].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Bank_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Comments]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_1]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_2]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_3]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[Sys_AB_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Map].[Sys_AW_Tax_Methods_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Map].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Map].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Map].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map_Splits].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map_Splits].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Map_Splits].[Sys_AW_Tax_Methods_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Map_Splits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Map_Splits].[User_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Map_Splits].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
       
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Notes].[Note]'

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Notes].[Date_Captured]' 
	   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Notes].[User_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Notes].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transaction_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transaction_Details].[User_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transaction_Details].[AW_User_Companies_ID]'
	
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transaction_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transactions].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Transactions].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Transactions].[Slu_AW_Years_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transactions].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transactions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
       
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Flow_Forecast_Temp].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M3]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M4]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M5]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M6]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[N1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[RowTypeID]'
    
    EXEC sp_bindefault N'[dbo].[df_Todays_Date]', N'[AB_Cash_Flow_Forecast_Temp].[StartDate]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[T1]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Flow_Forecast_Temp].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Inflow_Projections].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Inflow_Projections].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Inflow_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Inflow_Projections].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Inflow_Projections].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Inflow_Projections].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Outflow_Projections].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Outflow_Projections].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Outflow_Date]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Outflow_Projections].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Outflow_Projections].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Outflow_Projections].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Ref]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_GL_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_GL_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_GL_Transactions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_GL_Transactions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Journal_Details].[Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journal_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journal_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journal_Details].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journal_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journals].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journals].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journals].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journals].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring].[Date_Captured]'   
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Recurring_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring_Details].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Period_Procedures].[Date_Captured]'   
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Period_Procedures].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Period_Procedures].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Period_Procedures].[Slu_AW_Active_ID]'
    
    setuser

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions] FOREIGN KEY 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) REFERENCES [dbo].[AB_Cash_Book_Transactions] (
    		[AB_Cash_Book_Transactions_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transactions_AW_Company_Banks] FOREIGN KEY 
    	(
    		[AW_Company_Banks_ID]
    	) REFERENCES [dbo].[AW_Company_Banks] (
    		[AW_Company_Banks_ID]
    	)

    
    ALTER TABLE [dbo].[AB_GL_Transactions] ADD 
    	CONSTRAINT [FK_AB_GL_Transactions_Lup_AB_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AB_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AB_Transaction_Types] (
    		[Sys_AB_Transaction_Types_ID]
    	),
    	CONSTRAINT [FK_AB_Transactions_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Journal_Details] ADD 
    	CONSTRAINT [FK_AB_Journal_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Journal_Details_AB_Journals] FOREIGN KEY 
    	(
    		[AB_Journals_ID]
    	) REFERENCES [dbo].[AB_Journals] (
    		[AB_Journals_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Recurring_Details] ADD 
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Recurring] FOREIGN KEY 
    	(
    		[AB_Recurring_ID]
    	) REFERENCES [dbo].[AB_Recurring] (
    		[AB_Recurring_ID]
    	)

    SET @ReturnValue = 1

END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9930
--Purpose       :Wipe all TASKS Transaction tables
--              :
--Parameters    :
--Date          :2002/02/03
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9930]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit

    SET @ReturnValue = 0

    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AT_Tasks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AT_Tasks]

        
        CREATE TABLE [dbo].[AT_Tasks] (
        	[AT_Tasks_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Start_Date] [datetime] NULL ,
        	[Date_Started] [datetime] NULL ,
        	[Date_Completed] [datetime] NULL ,
        	[Due_Date] [datetime] NULL ,
        	[Remind] [bit] NULL ,
        	[Actual_Work] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Task_Message] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Actor1_ID] [int] NULL ,
        	[Actor2_ID] [int] NULL ,
        	[User2_ID] [int] NULL ,
        	[Subject_ObjectName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Sys_AT_Subject_Type_ID] [tinyint] NULL ,
        	[Subject_ID] [int] NULL ,
        	[Sys_AT_Status_ID] [int] NULL ,
        	[Sys_AT_Notifications_ID] [tinyint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AT_Tasks] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AW_Tasks] PRIMARY KEY  CLUSTERED 
        	(
        		[AT_Tasks_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Actual_Work]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Remind]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Subject_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Subject_ObjectName]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Notifications_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Status_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Subject_Type_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Task_Message]'

        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AT_Tasks].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AT_Tasks].[User_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AT_Tasks].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AT_Tasks].[Slu_AW_Active_ID]'
        
        setuser
    
        SET @ReturnValue = 1
    
    END

RETURN @ReturnValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   : sp_AW_9940
--Purpose       : Wipe all PRODUCT Transaction tables
--Date          : 2002/02/11
--Authors       : TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9940]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

BEGIN
	--Average Cost Must be Zeroed or else audit trail will not make sense or balance??????
    --First wipe the Test Data
    UPDATE AP_Products 
    SET Average_Cost = 0,
		On_Hand = 0,
		Sales_Order_Reserved = 0,
		Quote_Reserved = 0,
		Job_Reserved = 0,
		Last_Sale_Date = NULL,
		Service_Level = 1,
		Min_Stock_Level = 0,
		Min_Order_Qty = 0,
		Max_Order_Qty = 0,
		Levy_AP_Product_ID = 0

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Bond_Stock_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Bond_Stock_Log]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Slow_Moving_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Slow_Moving_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Filter]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Filter]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Replenish_Max]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Replenish_Max]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Valuation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Valuation]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Adjustments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Adjustments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Valuations]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Valuations]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Product_Selling_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Product_Selling_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_History]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_History]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Inventory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Inventory]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Stock_Takes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Stock_Takes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Exchange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Exchange]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Take_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Take_Procedures]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfer_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfer_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfer_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfer_Log]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Audit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Audit]
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Product_Bins]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Product_Bins]
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Bins]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Bins]

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Bins_History]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Bins_History]

    CREATE TABLE [dbo].[AP_Bond_Stock_Log] (
    	[AP_Bond_Stock_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[File_Type] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Location] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Computer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Login_URL] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_User_Name] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Password] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Folder] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Date] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Time] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Row_CNT] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] (
    	[AP_Enterprise_Slow_Moving_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock] (
    	[AP_Enterprise_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Filter] (
    	[AP_Enterprise_Stock_Filter_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] (
    	[AP_Enterprise_Stock_Replenish_Max_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Valuation] (
    	[AP_Enterprise_Stock_Valuation_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Adjustments] (
    	[AP_Inventory_Adjustments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Sys_AP_Adjustment_Types_ID] [tinyint] NULL ,
    	[Previous_Last_Cost] [money] NOT NULL ,
    	[Previous_Average_Cost] [money] NULL ,
    	[Previous_On_Hand] [decimal](9, 3) NULL ,
    	[Previous_Job_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Quote_Reserved] [decimal](9, 3) NULL ,
    	[New_Last_Cost] [money] NULL ,
    	[New_Average_Cost] [money] NULL ,
    	[New_On_Hand] [decimal](9, 3) NULL ,
    	[New_Job_Reserved] [decimal](9, 3) NULL ,
    	[New_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[New_Quote_Reserved] [decimal](9, 3) NULL ,
    	[Note] [varchar] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Valuations] (
    	[AP_Inventory_Valuations_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Qty_On_Hand] [money] NULL ,
    	[Date_Captured] [smalldatetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Product_Selling_Prices] (
    	[AP_Product_Selling_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Prev_Price1_Effective_Date] [datetime] NULL ,
    	[Prev_Price1_Price1] [money] NULL ,
    	[Prev_Price1_Price2] [money] NULL ,
    	[Prev_Price2_Effective_Date] [datetime] NULL ,
    	[Prev_Price2_Price1] [money] NULL ,
    	[Prev_Price2_Price2] [money] NULL ,
    	[New_Price1_Effective_Date] [datetime] NULL ,
    	[New_Price1_Price1] [money] NULL ,
    	[New_Price1_Price2] [money] NULL ,
    	[New_Price2_Effective_Date] [datetime] NULL ,
    	[New_Price2_Price1] [money] NULL ,
    	[New_Price2_Price2] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_History] (
    	[AP_Products_History_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

 
    CREATE TABLE [dbo].[AP_Products_Inventory] (
    	[AP_Products_Inventory_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_Static_ID] [int] NOT NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NOT NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Date_Updated] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Stock_Takes] (
    	[AP_Products_Stock_Takes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Stock_Take_Procedures_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Count1] [decimal](9, 3) NULL ,
    	[Count2] [decimal](9, 3) NULL ,
    	[Count3] [decimal](9, 3) NULL ,
    	[Total_Count] [decimal](12, 3) NULL ,
    	[Unit_Cost] [money] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Variance] [decimal](12, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Exchange] (
    	[AP_Stock_Exchange_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[NodeName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[On_Order] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Count_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Take_Procedures] (
    	[AP_Stock_Take_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Procedure_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Stock_Valuation] [money] NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[Stock_Adjustment_Total] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Transfer_Details] (
    	[AP_Stock_Transfer_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Rate] [decimal](9, 3) NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Transfer_Log] (
    	[AP_Stock_Transfer_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_GL_Transactions_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Quantity] [decimal](12, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NOT NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Date_Received] [datetime] NULL ,
    	[SIT_User_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[TRF_User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
	CREATE TABLE [dbo].[AP_Products_Audit] (
		[AP_Products_Audit_ID] [int] IDENTITY(1,1) NOT NULL,
		[Record_Action] [varchar](50) NULL,
		[Action_Date] [datetime] NULL,
		[AP_Products_ID] [int] NOT NULL,
		[Field] [varchar](50) NULL,
		[Prev_Value] [varchar](50) NULL,
		[New_Value] [varchar](50) NULL,		
		[Changes_Sent] [int] NULL,
		[User_ID] [int] NULL
	) ON [PRIMARY]

  
	CREATE TABLE [AC_Product_Bins](
		[AC_Product_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[AC_Customers_ID] [int] NOT NULL,
		[Lup_AP_Product_Bins_ID] [int] NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY] 
 
	CREATE TABLE [AP_Products_Bins](
		[AP_Products_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[AP_Products_ID] [int] NOT NULL,
		[Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[On_Hand] [decimal](9, 3) NOT NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY] 

	CREATE TABLE [AP_Products_Bins_History](
		[AP_Products_Bins_History_ID] [int] IDENTITY(1,1) NOT NULL,
		[Batch_No] [int] NOT NULL,
		[AP_Products_ID] [int] NOT NULL,
		[From_Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[From_Bin_Previous_On_Hand] [decimal](9, 3) NOT NULL,
		[From_Bin_New_On_Hand] [decimal](9, 3) NOT NULL,
		[To_Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[To_Bin_Previous_On_Hand] [decimal](9, 3) NOT NULL,
		[To_Bin_New_On_Hand] [decimal](9, 3) NOT NULL,
		[Movement_Source] [varchar](10) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY] 
    
    ALTER TABLE [dbo].[AP_Bond_Stock_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Bond_Stock_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Bond_Stock_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Adjustments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Adjustments] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Adjustments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Valuations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Valuations] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Valuations_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_History_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Inventory] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Inventory] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Inventory_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Stock_Takes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Stock_Takes] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Stock_Takes_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Exchange] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Exchange] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Exchange_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Take_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Take_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Take_Procedures_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Transfer_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Transfer_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Transfer_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 


    ALTER TABLE [dbo].[AP_Products_Audit] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Audit] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Audit_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 
    

    ALTER TABLE [dbo].[AP_Products_Bins] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Bins] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Bins_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 
  

    ALTER TABLE [dbo].[AP_Products_Bins_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Bins_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Bins_History_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 


        
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Slow_Moving_Stock_Search] ON [dbo].[AP_Enterprise_Slow_Moving_Stock]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Search] ON [dbo].[AP_Enterprise_Stock]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Filter_Search] ON [dbo].[AP_Enterprise_Stock_Filter]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Replenish_Max_Search] ON [dbo].[AP_Enterprise_Stock_Replenish_Max]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Valuation_Search] ON [dbo].[AP_Enterprise_Stock_Valuation]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Product_Selling_Prices] ON [dbo].[AP_Product_Selling_Prices]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Stock_Transfer_Details] ON [dbo].[AP_Stock_Transfer_Details]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

   
	 CREATE  CLUSTERED  INDEX [IX_AC_Product_Bins_AC_Customers_ID] ON [AC_Product_Bins]([AC_Customers_ID]) WITH FILLFACTOR = 80  ON [PRIMARY]
   
    
	 CREATE  NONCLUSTERED  INDEX [IX_AP_Products_Bins_AP_Products_ID] ON [AP_Products_Bins]([AP_Products_ID]) WITH FILLFACTOR = 80


  	 CREATE  NONCLUSTERED  INDEX [IX_AP_Products_Bins_History_AP_Products_ID] ON [AP_Products_Bins_History]([AP_Products_ID]) WITH FILLFACTOR = 80
    
    
    ALTER TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Slow_Moving_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Slow_Moving_Stock_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Filter] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Filter] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Filter_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Replenish_Max] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Replenish_Max_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Valuation] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Valuation] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Valuation_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Inventory_Adjustments_AP_Products_ID] ON [dbo].[AP_Inventory_Adjustments]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Product_Selling_Prices] ADD 
    	CONSTRAINT [PK_AP_Product_Selling_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Product_Selling_Prices_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_History_AP_Products_ID] ON [dbo].[AP_Products_History]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_AP_Products_Static_ID] ON [dbo].[AP_Products_Inventory]([AP_Products_Static_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_Date_Updated] ON [dbo].[AP_Products_Inventory]([Date_Updated]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Stock_Takes_AP_Products_ID] ON [dbo].[AP_Products_Stock_Takes]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IDX_Product_Code_NodeName] ON [dbo].[AP_Stock_Exchange]([Product_Code], [NodeName]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Stock_Exchange_AP_Products_ID] ON [dbo].[AP_Stock_Exchange]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Stock_Transfer_Details] ADD 
    	CONSTRAINT [PK_AP_Stock_Transfer_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Stock_Transfer_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
	CREATE  INDEX [IX_AP_Stock_Transfer_Details_AP_Products_ID] ON [dbo].[AP_Stock_Transfer_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
	CREATE  INDEX [IDX_AP_Stock_Transfer_Log_AS_Transactions_ID] ON [dbo].[AP_Stock_Transfer_Log]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

	CREATE  INDEX [IX_AP_Products_Audit_AP_Products_ID] ON [dbo].[AP_Products_Audit]([AP_Products_ID]) WITH  FILLFACTOR = 80 ON [PRIMARY]
	
	CREATE  INDEX [Ind_AP_Products_Audit_Changes_Sent] ON [dbo].[AP_Products_Audit]([Changes_Sent]) WITH  FILLFACTOR = 80 ON [PRIMARY]
    
    
    setuser     
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[Computer]'        
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Location]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Time]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Type]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Folder]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Login_URL]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Password]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_User_Name]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[Row_CNT]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Bond_Stock_Log].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Bond_Stock_Log].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Bond_Stock_Log].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Slow_Moving_Stock].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Filter].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Valuation].[Pack_Size]'
    
    setuser

    
    setuser        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Average_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Job_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Quote_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Sales_Order_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Average_Cost]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Job_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Quote_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Sales_Order_Reserved]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Sys_AP_Adjustment_Types_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Adjustments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Adjustments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Adjustments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Adjustments].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Average_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Qty_On_Hand]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Valuations].[Date_Captured]'
	
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Valuations].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Valuations].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Valuations].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
        
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price1_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price2_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price1_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price2_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price2]'                
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Date_Captured]'  
      
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Product_Selling_Prices].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Product_Selling_Prices].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Product_Selling_Prices].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Average_Cost]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Qty]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Standard_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_History].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_History].[AW_User_Companies_ID]'
    
    setuser

    
    setuser            
        
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Products_Inventory].[Date_Updated]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Inventory].[Lup_AP_Product_Locations_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Inventory].[On_Hand]'    
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Inventory].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Inventory].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Inventory].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Inventory].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count3]'      
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[On_Hand]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Total_Count]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Unit_Cost]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Variance]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Stock_Takes].[Date_Captured]'
	
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Stock_Takes].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Stock_Takes].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Stock_Takes].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
                    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser        
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]' 
               
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Average_Cost]'                
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Order]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Exchange].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Exchange].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Exchange].[AW_User_Companies_ID]'
    
    setuser

    
    setuser        
                    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Take_Procedures].[Stock_Valuation]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Take_Procedures].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Take_Procedures].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Take_Procedures].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Take_Procedures].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Amount]'    
        
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Back_Order]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Quantity]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Tax_Rate]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Unit_Price]'        
	    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfer_Details].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfer_Details].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfer_Details].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Transfer_Details].[Slu_AW_Active_ID]'    
	
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Amount]'               
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfer_Log].[Transaction_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfer_Log].[TRF_User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Unit_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Stock_Transfer_Log].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfer_Log].[AW_User_Companies_ID]'
    
    setuser

    
	setuser
       
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Audit].[User_ID]'
    
    setuser
       
       
    setuser    
   
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Product_Bins].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Product_Bins].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Product_Bins].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Product_Bins].[Slu_AW_Active_ID]'

    setuser
    
    
    setuser    
   
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Bins].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Bins].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Bins].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Bins].[Slu_AW_Active_ID]'

    setuser


    setuser    
  
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Products_Bins_History].[Movement_Source]'
	   
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Bins_History].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Bins_History].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Bins_History].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Bins_History].[Slu_AW_Active_ID]'

    setuser
        
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)
  
    SET @ReturnValue = 1
    
END

RETURN @ReturnValue

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   : sp_AW_9950
--Purpose       : Clear all System Transaction Number tables
--              :
--Parameters    :
--Date          : 2002/02/11
--Authors       : TB
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9950]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

BEGIN

    UPDATE Sys_AB_Transaction_Numbers
    SET Last_Number = 0

    UPDATE Sys_AW_Transaction_Numbers
    SET Last_Number = 0

    SET @ReturnValue = 1
    
END

RETURN @ReturnValue

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9960
--Purpose       :Wipe all CUSTOMER Transaction tables
--              :
--Parameters    :
--Date          :2002/02/11
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------


--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--AC_Customers not cleared
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

CREATE PROCEDURE [dbo].[sp_AW_9960]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit

    SET @ReturnValue = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AS_Transactions_AW_Comments]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AS_Transactions] DROP CONSTRAINT FK_AS_Transactions_AW_Comments

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Assets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Assets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Contract_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Contract_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Ageing_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Customer_Ageing]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Associates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Associates]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Auditors]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Auditors]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Balance_Sheets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Balance_Sheets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Bankers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Bankers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Bonds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Bonds]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Credit_Limits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Credit_Limits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Default]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Default]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_ITCScores]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_ITCScores]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Income_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Income_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Info_Reports]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Info_Reports]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Judgements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Judgements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_KIScores]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_KIScores]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Motion_Roll]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Motion_Roll]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Notarial_Bonds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Notarial_Bonds]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Principal_Properties]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Principal_Properties]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Principals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Principals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Properties]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Properties]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_RD_Cheques]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_RD_Cheques]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Ratings]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Ratings]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Shareholders]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Shareholders]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Status]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Status]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Trade_References]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Trade_References]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Detail]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Detail_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Detail_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Header]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Header]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statement_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statement_Details_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statements_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Comments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Comments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Log_AC_Master_Controller]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Log_AC_Master_Controller]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Log_AC_Messages]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Log_AC_Messages]

    
    CREATE TABLE [dbo].[AC_Assets] (
    	[AC_Assets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[Make] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model_Year] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AC_Asset_Types_ID] [smallint] NULL ,
    	[Reg_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Engine_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Chassis_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[VIN_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Mileage] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Mileage_Date] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Tyre_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Tyre_Qty] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AS_Transactions_ID] [int] NULL,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL    	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Contract_Prices] (
    	[AC_Contract_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Perc] [decimal](9, 3) NULL ,
    	[Discount_Amount] [money] NULL ,
    	[MinSaleQty] [decimal](9, 3) NULL,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL    	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Enterprise_Ageing_Temp] (
    	[AC_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Enterprise_Customer_Ageing] (
    	[AC_Enterprise_Customer_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Associates] (
    	[AC_History_Associates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Associate_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Association_Types_ID] [smallint] NULL ,
    	[Shareholding_Percentage] [decimal](7, 2) NULL ,
    	[Slu_AC_Shareholding_Types_ID] [smallint] NULL ,
    	[Date_Acquired] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Auditors] (
    	[AC_History_Auditors_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Firm_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Audit_Manager] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registration_Date] [datetime] NULL ,
    	[Slu_AC_Profession_Types_ID] [smallint] NULL ,
    	[Slu_AC_Auditor_Rankings_ID] [smallint] NULL ,
    	[Profession_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Profession_Date_Changed] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Balance_Sheets] (
    	[AC_History_Balance_Sheets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Statement_Date] [datetime] NULL ,
    	[Property_Plant_and_Equipment] [money] NULL ,
    	[Investment_Property] [money] NULL ,
    	[Investments_and_Loans] [money] NULL ,
    	[Investments_and_Finance_Leases] [money] NULL ,
    	[Forward_Exchange_Contract_Asset] [money] NULL ,
    	[Inventories] [money] NULL ,
    	[Trade_and_Other_Receivables] [money] NULL ,
    	[Prepayments] [money] NULL ,
    	[Cash_and_Cash_Equivalents] [money] NULL ,
    	[Issued_Capital] [money] NULL ,
    	[Reserves] [money] NULL ,
    	[Accumulated_Profit_Loss] [money] NULL ,
    	[Interest_Bearing_Borrowings] [money] NULL ,
    	[Deferred_Taxation] [money] NULL ,
    	[Retirement_Benefit_Obligations] [money] NULL ,
    	[Trade_and_Other_Payables] [money] NULL ,
    	[Taxation] [money] NULL ,
    	[Dividend_Declared] [money] NULL ,
    	[Bank_Overdraft] [money] NULL ,
    	[Overdraft_Facility] [money] NULL ,
    	[Current_portion_of_Interest_Bearing_Borrowings] [money] NULL ,
    	[Warranty_Provision] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Bankers] (
    	[AC_History_Bankers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Banks_ID] [smallint] NULL ,
    	[Bank_Branch] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Branch_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Bank_Codes_ID] [tinyint] NULL ,
    	[Bank_Code_Amount] [money] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Banker_Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Opened] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Bonds] (
    	[AC_History_Bonds_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Bond_Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Holder] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Amount] [money] NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	[Repayment_Period] [decimal](3, 0) NULL ,
    	[Repayment_Amount] [money] NULL ,
    	[Effective_Date] [datetime] NULL ,
    	[Date_Registered] [datetime] NULL ,
    	[Collateral_Provider] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Credit_Limits] (
    	[AC_History_Credit_Limits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Sys_AC_Credit_Term_Types_ID] [int] NULL ,
    	[New_Limit] [money] NULL ,
    	[Limit_Reason] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Changed] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Default] (
    	[AC_History_Default_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Adverse_Reasons_ID] [int] NULL ,
    	[Adverse_Source] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Reported] [datetime] NULL ,
    	[Dispute_Amount] [money] NULL ,
    	[Days_Overdue] [int] NULL ,
    	[Adverse_Comments] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_ITCScores] (
    	[AC_History_ITCScores_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_ITC_Scores_ID] [smallint] NULL ,
    	[Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,    	
    	[Effective_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Income_Statements] (
    	[AC_History_Income_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Statement_Date] [datetime] NULL ,
    	[Revenue] [money] NULL ,
    	[Cost_of_Sales] [money] NULL ,
    	[Other_Income] [money] NULL ,
    	[Fleet_Rental] [money] NULL ,
    	[Distribution_Expenses] [money] NULL ,
    	[Auditors_Remuneration] [money] NULL ,
    	[Depreciation] [money] NULL ,
    	[Prepayments] [money] NULL ,
    	[Profit_Loss_on_disposal_of_Assets] [money] NULL ,
    	[Permanent_decline_in_value_of_Investment_Property] [money] NULL ,
    	[Fees_for_Services] [money] NULL ,
    	[Rental_on_Operating_Leases] [money] NULL ,
    	[Forex_Gains_Losses] [money] NULL ,
    	[Staff_Costs] [money] NULL ,
    	[Other_Long_Term_Employee_Benefits] [money] NULL ,
    	[Directors_Emoluments] [money] NULL ,
    	[Other_Expenses] [money] NULL ,
    	[Financing_Costs] [money] NULL ,
    	[Financing_Costs_Capitalized] [money] NULL ,
    	[Taxation] [money] NULL ,
    	[Extraordinary_Items] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Info_Reports] (
    	[AC_History_Info_Reports_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Info_Report_Types_ID] [smallint] NULL ,
    	[Report_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Judgements] (
    	[AC_History_Judgements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Nature_Of_Action_ID] [smallint] NULL ,
    	[Slu_AW_Courts_ID] [smallint] NULL ,
    	[Defendant_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Plaintiff_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Judgement_Amount] [money] NULL ,
    	[Case_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Of_Judgement] [datetime] NULL ,
    	[Default_Judgement] [bit] NULL ,
    	[Date_Rescinded] [datetime] NULL ,
    	[Rescindment_Reason] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Abandoned] [datetime] NULL ,
    	[Abandonment_Reason] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_KIScores] (
    	[AC_History_KIScores_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_KI_Scores_ID] [smallint] NULL ,
    	[Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Effective_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Motion_Roll] (
    	[AC_History_Motion_Roll_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Nature_Of_Action_ID] [smallint] NULL ,
    	[Slu_AW_Lawsuit_Types_ID] [smallint] NULL ,
    	[Slu_AW_Courts_ID] [smallint] NULL ,
    	[Respondent_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Applicant] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Application_Amount] [money] NULL ,
    	[Case_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Item_Number] [tinyint] NULL ,
    	[Hearing_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Notarial_Bonds] (
    	[AC_History_Notarial_Bonds_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Bond_Holder] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Amount] [money] NULL ,
    	[Effective_date] [datetime] NULL ,
    	[Date_Registered] [datetime] NULL ,
    	[Collateral_Provider] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Principal_Properties] (
    	[AC_History_Principal_Properties_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[AC_History_Principals_ID] [int] NULL ,
    	[Description] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registered_Owner] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Title_Deed_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Property_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Purchased] [datetime] NULL ,
    	[Purchase_Price] [money] NULL ,
    	[Address1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Principals] (
    	[AC_History_Principals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[ID_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Principal_Types_ID] [smallint] NULL ,
    	[Home_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[E_Mail] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Appointed] [datetime] NULL ,
    	[Date_Terminated] [datetime] NULL ,
    	[Primary_Function] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Comments] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status_Ind] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Properties] (
    	[AC_History_Properties_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	[Description] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Title_Deed_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registered_Owner] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Property_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Purchased] [datetime] NULL ,
    	[Purchase_Price] [money] NULL ,
    	[Address1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_RD_Cheques] (
    	[AC_History_RD_Cheques_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Date_Reported] [datetime] NULL ,
    	[Cheque_Amount] [money] NULL ,
    	[Comments] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Ratings] (
    	[AC_History_Ratings_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Ratings_ID] [smallint] NULL ,
    	[Rating_Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Effective_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Shareholders] (
    	[AC_History_Shareholders_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Shareholder_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Interest_Percent] [decimal](7, 2) NULL ,
    	[Number_Of_Shares] [int] NULL ,
    	[Slu_AC_Shareholding_Types_ID] [smallint] NULL ,
    	[Members_Contribution] [money] NULL ,
    	[Par_Value_Of_Holding] [money] NULL ,
    	[Estimated_Valuation] [money] NULL ,
    	[Controlling_Shareholder] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Parent_Company] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Holding_Company] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Status] (
    	[AC_History_Status_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Sys_AC_Account_Status_ID] [smallint] NULL ,
    	[Status_Reason] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Changed] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Trade_References] (
    	[AC_History_Trade_References_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Security_Types_ID] [smallint] NULL ,
    	[Date_of_Reference] [datetime] NULL ,
    	[Supplier_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Position] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Telephone_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Fax_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Period_Known] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Average_per_Month] [money] NULL ,
    	[Reference_Comments] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Highest_Amount] [money] NULL ,
    	[Account_Limit] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Terms_Given] [smallint] NULL ,
    	[Terms_Taken] [smallint] NULL ,
    	[Current_Balance] [money] NULL ,
    	[Days_30] [money] NULL ,
    	[Days_60] [money] NULL ,
    	[Days_90] [money] NULL ,
    	[Days_120] [money] NULL ,
    	[Days_150] [money] NULL ,
    	[Days_180] [money] NULL ,
    	[Past_Due_Amount] [money] NULL ,
    	[Limit_Of_Guarantee] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Detail] (
    	[AC_Periodic_Billing_Detail_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Periodic_Billing_Header_ID] [int] NOT NULL ,
    	[Post] [bit] NOT NULL ,
    	[Transaction_Date] [datetime] NOT NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Notes] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Detail_Splits] (
    	[AC_Periodic_Billing_Detail_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Periodic_Billing_Header_ID] [int] NOT NULL ,
    	[AC_Periodic_Billing_Detail_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Header] (
    	[AC_Periodic_Billing_Header_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Posting_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Posted] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Slu_AW_Years_ID] [smallint] NOT NULL ,
    	[Import_Filename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statement_Details] (
    	[AC_Statement_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Statements_ID] [int] NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL     	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statement_Details_Temp] (
    	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Statements_Temp_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statements] (
    	[AC_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statements_Temp] (
    	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AW_Comments] (
    	[AW_Comments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Actor_ID] [int] NULL ,
    	[Sys_AT_Actor_Types_ID] [int] NULL ,
    	[Comment] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Log_AC_Master_Controller] (
    	[Log_AC_Master_Controller_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Actor_ID] [int] NOT NULL ,
    	[Sys_AT_Actor_Types_ID] [int] NOT NULL ,
    	[AW_Messages_ID] [int] NULL ,
    	[Message] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AC_Severity_Levels_ID] [tinyint] NULL ,
    	[Sys_AC_Message_Types_ID] [smallint] NULL ,
    	[Sys_AW_Delivery_Methods_ID] [tinyint] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Log_AC_Messages] (
    	[Log_AC_Messages_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[Message_Date] [datetime] NULL ,
    	[Dispatch_Date] [datetime] NULL ,
    	[User_CRM_ID] [int] NULL ,
    	[User_Controller_ID] [int] NULL ,
    	[Addressee] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Send_To] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Balance] [money] NULL ,
    	[Overdue] [money] NULL ,
    	[Credit_Terms] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Terms_Of_Sale] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Method] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Subject] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Messages_ID] [int] NULL ,
    	[Message] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address_List] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Errors] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_History_Auditors] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Auditors] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Auditors_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Balance_Sheets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Balance_Sheets] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Balance_Sheets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Bankers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Bankers] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Bankers_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Bonds] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Bonds] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Bonds_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Credit_Limits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Credit_Limits] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Credit_Limits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Default] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Default] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Default_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_ITCScores] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_ITCScores] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_ITCScores_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Income_Statements] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Income_Statements] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Income_Statements_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Info_Reports] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Info_Reports] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Info_Reports_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_KIScores] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_KIScores] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_KIScores_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Ratings] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Ratings] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Ratings_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Status] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Status] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Status_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Trade_References] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Trade_References] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Trade_References_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Detail_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Detail_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Detail_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Header] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Header] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Header_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AW_Comments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Comments] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Comments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Log_AC_Master_Controller] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Log_AC_Master_Controller] PRIMARY KEY  CLUSTERED 
    	(
    		[Log_AC_Master_Controller_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Log_AC_Messages] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Log_AC_Messages] PRIMARY KEY  CLUSTERED 
    	(
    		[Log_AC_Messages_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_Customer_Assets] ON [dbo].[AC_Assets]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AC_Contract_Customers_Products] ON [dbo].[AC_Contract_Prices]([AC_Customers_ID], [AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Ageing_Temp] ON [dbo].[AC_Enterprise_Ageing_Temp]([Filter], [FullName], [Customer_Number]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Customer_Ageing] ON [dbo].[AC_Enterprise_Customer_Ageing]([Filter], [Customer], [CustNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statement_Details] ON [dbo].[AC_Statement_Details]([AC_Statement_Details_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statement_Details_Temp] ON [dbo].[AC_Statement_Details_Temp]([AC_Statement_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statements_ID] ON [dbo].[AC_Statements]([AC_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statements_Temp] ON [dbo].[AC_Statements_Temp]([AC_Statements_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Assets] ADD 
    	CONSTRAINT [PK_AC_Assets] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Assets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Contract_Prices] ADD 
    	CONSTRAINT [PK_AC_Contract_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Contract_Prices_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_Contract_Prices_Customers_ID] ON [dbo].[AC_Contract_Prices]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Enterprise_Ageing_Temp] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Ageing_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Enterprise_Customer_Ageing] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Customer_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Customer_Ageing_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Associates] ADD 
    	CONSTRAINT [PK_AC_History_Associates] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Associates_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Judgements] ADD 
    	CONSTRAINT [PK_AC_History_Judgements] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Judgements_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Motion_Roll] ADD 
    	CONSTRAINT [PK_AC_History_Motion_Roll] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Motion_Roll_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Notarial_Bonds] ADD 
    	CONSTRAINT [PK_AC_History_Notarial_Bonds] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Notarial_Bonds_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Principal_Properties] ADD 
    	CONSTRAINT [PK_AC_History_Principal_Properties] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Principal_Properties_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Principals] ADD 
    	CONSTRAINT [PK_AC_History_Principals] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Principals_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Properties] ADD 
    	CONSTRAINT [PK_AC_History_Properties] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Properties_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_RD_Cheques] ADD 
    	CONSTRAINT [PK_AC_History_RD_Cheques] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_RD_Cheques_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Shareholders] ADD 
    	CONSTRAINT [PK_AC_History_Shareholders] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Shareholders_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AC_Statement_Details_Key] ON [dbo].[AC_Statement_Details]([AC_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AC_Statements_Customers_ID] ON [dbo].[AC_Statements]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser

    --Defaults AC_Assets
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Assets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Assets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Assets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Assets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Contract_Prices
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Contract_Prices].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Contract_Prices].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Contract_Prices].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Contract_Prices].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Discount_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Discount_Perc]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Contract_Prices].[Pack_Size]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Unit_Price]'
   
    setuser

    
    setuser
    --Defaults AC_Enterprise_Ageing_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Enterprise_Ageing_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Enterprise_Ageing_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Payment]'   
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Account_Balance]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Current]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[30Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[90Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[180+Days]'  
    
    setuser

    
    setuser
    --Defaults AC_Enterprise_Customer_Ageing
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Enterprise_Customer_Ageing].[CompanyID]'

    setuser

    
    setuser
    --Defaults AC_History_Associates
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Associates].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Associates].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Associates].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Associates].[Slu_AW_Active_ID]'
    
    setuser

   
    setuser
    --Defaults AC_History_Auditors
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Auditors].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Auditors].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Auditors].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Auditors].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Balance_Sheets
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Balance_Sheets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Balance_Sheets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Balance_Sheets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Balance_Sheets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Bankers
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Bankers].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Bankers].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Bankers].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Bankers].[Slu_AW_Active_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_History_Bankers].[Bank_Code_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_History_Bankers].[Slu_AC_Bank_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_History_Bankers].[Slu_AW_Credit_Terms_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Bonds
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Bonds].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Bonds].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Bonds].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Bonds].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Credit_Limits
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Credit_Limits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Credit_Limits].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Credit_Limits].[AW_User_Companies_ID]'
   
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Credit_Limits].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Default
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Default].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Default].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Default].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Default].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_ITCScores
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_ITCScores].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_ITCScores].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_ITCScores].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_ITCScores].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Income_Statements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Income_Statements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Income_Statements].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Income_Statements].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Income_Statements].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
    --Defaults AC_History_Info_Reports
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Info_Reports].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Info_Reports].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Info_Reports].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Info_Reports].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Judgements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Judgements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Judgements].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Judgements].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Judgements].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_KIScores
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_KIScores].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_KIScores].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_KIScores].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_KIScores].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Motion_Roll
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Motion_Roll].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Motion_Roll].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Motion_Roll].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Motion_Roll].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Notarial_Bonds
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Notarial_Bonds].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Notarial_Bonds].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Notarial_Bonds].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Notarial_Bonds].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Principal_Properties
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Principal_Properties].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Principal_Properties].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Principal_Properties].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Principal_Properties].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Principals
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Principals].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Principals].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Principals].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Principals].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Properties
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Properties].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Properties].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Properties].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Properties].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_RD_Cheques
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_RD_Cheques].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_RD_Cheques].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_RD_Cheques].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_RD_Cheques].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Ratings
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Ratings].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Ratings].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Ratings].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Ratings].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Shareholders
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Shareholders].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Shareholders].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Shareholders].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Shareholders].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Status
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Status].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Status].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Status].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Status].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Trade_References
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Trade_References].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Trade_References].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Trade_References].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Trade_References].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Detail
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Detail].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Detail].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Detail].[Slu_AW_Active_ID]'
    
        

    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[AC_Customers_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Comment]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Email]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Notes]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Ref_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Periodic_Billing_Detail].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[Sys_AW_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail].[Transaction_Date]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Detail_Splits
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail_Splits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Detail_Splits].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Detail_Splits].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Detail_Splits].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail_Splits].[AP_Products_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail_Splits].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Periodic_Billing_Detail_Splits].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Unit_Price]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Header
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Header].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Header].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Header].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Header].[Slu_AW_Active_ID]'    

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Header].[Date_Posted]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Header].[Import_Filename]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Header].[Posting_Type]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AC_Periodic_Billing_Header].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AC_Periodic_Billing_Header].[Slu_AW_Years_ID]'
    
    setuser


    setuser
    --Defaults AC_Statement_Details
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details].[Payment]'
    
    setuser

    
    setuser
    --Defaults AC_Statement_Details_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details_Temp].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Payment]'
    
    setuser

    
    setuser
    --Defaults AC_Statements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Statements_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements_Temp].[Date_Captured]'
   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements_Temp].[User_ID]' 
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements_Temp].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Payment]'

	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Current]'
	
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Account_Balance]'
	
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[30Days]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[90Days]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[180+Days]'
    
    setuser

    
    setuser
    --Defaults AW_Comments
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Comments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Comments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Comments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Comments].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults Log_AC_Master_Controller
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Log_AC_Master_Controller].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Log_AC_Master_Controller].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Log_AC_Master_Controller].[AW_User_Companies_ID]'

      
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Log_AC_Master_Controller].[Sys_AC_Message_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Log_AC_Master_Controller].[Sys_AW_Delivery_Methods_ID]'

    setuser

    
    setuser
    --Defaults Log_AC_Messages
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Log_AC_Messages].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Log_AC_Messages].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Log_AC_Messages].[AW_User_Companies_ID]'
    
    setuser

  
    SET @ReturnValue = 1
 
RETURN @ReturnValue

SET NOCOUNT OFF    

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   : sp_AW_9970
--Purpose       : Wipe all FACTORY Transaction tables
--Date          : 2011/05/15 (2004.5.1)
--Authors       : TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9970]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

    BEGIN
    
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Job_Tickets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Job_Tickets]    

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Job_Tickets_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Job_Tickets_Deleted]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Waybills]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Waybills]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Waybills_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Waybills_Deleted]

        
        CREATE TABLE [dbo].[AF_Job_Tickets] (
        	[AF_Job_Tickets_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Post] [bit] NULL ,
        	[Job_No] [int] NULL ,
        	[Job_Date] [datetime] NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[Order_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[AP_Products_ID] [int] NULL ,
        	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
        	[Serial_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AF_Instructions_ID] [smallint] NULL ,
        	[Job_User_ID] [int] NULL ,
        	[AF_Waybills_ID] [int] NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Waybill_Date] [datetime] NULL ,
        	[Waybill_User_ID] [int] NULL ,
        	[AO_GRV_ID] [int] NULL ,
        	[GRV_Date] [datetime] NULL ,
        	[Invoice_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Retread_Cost] [money] NULL ,
        	[Repair_Cost] [money] NULL ,
        	[Other_Cost] [money] NULL ,
        	[AP_Repair_Products_ID] [int] NULL ,
        	[AP_Other_Products_ID] [int] NULL ,
        	[Lup_AP_Fail_Reasons_ID] [smallint] NULL ,
        	[GRV_User_ID] [int] NULL ,
        	[AS_Transactions_ID] [int] NULL ,
        	[Billing_Date] [datetime] NULL ,
        	[Billing_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Retread_Price] [money] NULL ,
        	[Repair_Price] [money] NULL ,
        	[Other_Price] [money] NULL ,
        	[Amount] [money] NULL ,
        	[Tax] [money] NULL ,
        	[Total] [money] NULL ,
        	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Billing_User_ID] [int] NULL ,
        	[AP_Inventory_Adjustments_ID] [int] NULL ,
        	[Adjustment_Date] [datetime] NULL ,
        	[AP_Stock_Products_ID] [int] NULL ,
        	[Casing_Credit] [money] NULL ,
        	[Stock_Cost] [money] NULL ,
        	[Adjustment_User_ID] [int] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
    
        
        CREATE TABLE [dbo].[AF_Waybills] (
        	[AF_Waybills_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Waybill_Date] [datetime] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
    
   
	CREATE TABLE [dbo].[AF_Job_Tickets_Deleted](
		[AF_Job_Tickets_ID] [int] NULL,
		[Post] [bit] NULL,
		[Job_No] [int] NULL,
		[Job_Date] [datetime] NULL,
		[AC_Customers_ID] [int] NULL,
		[Order_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[AP_Products_ID] [int] NULL,
		[Lup_AP_Product_Manufacturers_ID] [int] NULL,
		[Serial_No] [varchar](13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Lup_AF_Instructions_ID] [smallint] NULL,
		[Job_User_ID] [int] NULL,
		[AF_Waybills_ID] [int] NULL,
		[AO_Suppliers_ID] [int] NULL,
		[Waybill_Date] [datetime] NULL,
		[Waybill_User_ID] [int] NULL,
		[AO_GRV_ID] [int] NULL,
		[GRV_Date] [datetime] NULL,
		[Invoice_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Retread_Cost] [money] NULL,
		[Repair_Cost] [money] NULL,
		[Other_Cost] [money] NULL,
		[AP_Repair_Products_ID] [int] NULL,
		[AP_Other_Products_ID] [int] NULL,
		[Lup_AP_Fail_Reasons_ID] [smallint] NULL,
		[GRV_User_ID] [int] NULL,
		[AS_Transactions_ID] [int] NULL,
		[Billing_Date] [datetime] NULL,
		[Billing_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Retread_Price] [money] NULL,
		[Repair_Price] [money] NULL,
		[Other_Price] [money] NULL,
		[Amount] [money] NULL,
		[Tax] [money] NULL,
		[Total] [money] NULL,
		[Comment] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Billing_User_ID] [int] NULL,
		[AP_Inventory_Adjustments_ID] [int] NULL,
		[Adjustment_Date] [datetime] NULL,
		[AP_Stock_Products_ID] [int] NULL,
		[Casing_Credit] [money] NULL,
		[Stock_Cost] [money] NULL,
		[Adjustment_User_ID] [int] NULL,
		[Date_Captured] [datetime] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		[Action_Date] [datetime] NULL,
		[Action_User_ID] [int] NULL
	) ON [PRIMARY]

	CREATE TABLE [dbo].[AF_Waybills_Deleted](
		[AF_Waybills_ID] [int] NULL,
		[AO_Suppliers_ID] [int] NULL,
		[Waybill_Date] [datetime] NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		[Action_Date] [datetime] NULL,
		[Action_User_ID] [int] NULL
	) ON [PRIMARY]


        ALTER TABLE [dbo].[AF_Job_Tickets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AF_Job_Tickets] PRIMARY KEY  CLUSTERED 
        	(
        		[AF_Job_Tickets_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
    
        
        ALTER TABLE [dbo].[AF_Waybills] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AF_Waybills] PRIMARY KEY  CLUSTERED 
        	(
        		[AF_Waybills_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Factory_ID] ON [dbo].[AF_Job_Tickets]([AO_Suppliers_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Job_No] ON [dbo].[AF_Job_Tickets]([Job_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Customer_ID] ON [dbo].[AF_Job_Tickets]([AC_Customers_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Waybill_No] ON [dbo].[AF_Job_Tickets]([AF_Waybills_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Invoice_No] ON [dbo].[AF_Job_Tickets]([Invoice_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Billing_No] ON [dbo].[AF_Job_Tickets]([Billing_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_GRV_ID] ON [dbo].[AF_Job_Tickets]([AO_GRV_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Product_ID] ON [dbo].[AF_Job_Tickets]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_AS_Transactions_ID] ON [dbo].[AF_Job_Tickets]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Waybills_AO_Suppliers_ID] ON [dbo].[AF_Waybills]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AF_Job_Tickets].[Lup_AP_Fail_Reasons_ID]'    
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AF_Job_Tickets].[Post]'
    
		EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AF_Job_Tickets].[Date_Captured]'
		
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AF_Job_Tickets].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AF_Job_Tickets].[Slu_AW_Active_ID]'
            
        setuser
    
        
        setuser    
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AF_Waybills].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AF_Waybills].[User_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AF_Waybills].[AW_User_Companies_ID]'
        
		EXEC sp_bindefault N'[dbo].[df_Active]', N'[AF_Waybills].[Slu_AW_Active_ID]'
        
        setuser
    
        
        SET @ReturnValue = 1
        
    END

RETURN @ReturnValue

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9980
--Purpose       :RE-LINK PRODUCTS & SUPPLIERS (AP_Products_Suppliers)
--              :
--Parameters    :
--Date          :2002/08/02
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AW_9980]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Suppliers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Products_Suppliers]

        
        CREATE TABLE [dbo].[AP_Products_Suppliers] (
        	[AP_Products_Suppliers_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AP_Products_ID] [int] NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Lead_Time] [smallint] NULL ,
        	[Trade_Disc_Perc] [decimal](5, 2) NULL ,
        	[Trade_Disc_Date] [datetime] NULL ,
        	[Start_Date] [datetime] NULL ,
        	[AW_Trade_Discount_Formula_ID] [smallint] NULL ,
        	[AW_Rebate_Discount_Formula_ID] [smallint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [int] NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AP_Products_Suppliers_AP_Products_ID] ON [dbo].[AP_Products_Suppliers]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Products_Suppliers] ADD 
        	CONSTRAINT [PK_AP_Products_Suppliers] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Products_Suppliers_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

        
         CREATE  INDEX [IX_AP_Products_Suppliers_AO_Suppliers_ID] ON [dbo].[AP_Products_Suppliers]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Rebate_Discount_Formula_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Trade_Discount_Formula_ID]'
                                   
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[Lead_Time]'
                       
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Suppliers].[Trade_Disc_Perc]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Suppliers].[Date_Captured]'
        
		EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Suppliers].[User_ID]'
		
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Suppliers].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Suppliers].[Slu_AW_Active_ID]'        
        
        setuser
    
    
        ------------------------------------------------------------------------------------
        --INSERT AP_Products_Suppliers
        ------------------------------------------------------------------------------------
        INSERT AP_Products_Suppliers
            (
        	AP_Products_ID,
        	AO_Suppliers_ID,
        --	Lead_Time,    --IS NOW A DEFAULT OF 1
        	Start_Date
            )
        SELECT
            ap_products_id,
            Default_Supplier_ID,
        --  1,
            getdate()
        FROM ap_products
        WHERE Default_Supplier_ID IS NOT NULL


        SET @ReturnValue = 1
        
    END

RETURN @ReturnValue

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



---------------------------------------------------------------------------
-- NB NB NB NB NB NB ******************************************************
---------------------------------------------------------------------------

-- TRIGGER [dbo].[Ins_Lup_AP_Commission_Groups_ID]
-- TRIGGER [dbo].[Ins_Lup_AP_Product_Groups_ID]

-- MUST BE INSERTED MANUALLY BECAUSE IT CANNOT BE INSERTED IN A STORED PROC

---------------------------------------------------------------------------
-------------------------------------------------------------------------------
--Description   :sp_AW_9990
--Purpose       :Wipe all Products and Product Lookup table contents
--Tables        :     [AP_Inventory_Adjustments]
--              :     [AP_Inventory_Valuations]
--              :     [AP_Month_Sales_Actuals]
--              :     [AP_Month_Sales_Budgets]
--              :     [AP_Product_Selling_Prices]
--              :     [AP_Products]
--              :     [AP_Products_Assemblies]
--              :     [AP_Products_History]
--              :     [AP_Products_Stock_Takes]
--              :     [AP_Products_Suppliers]
--              :     [Lup_AP_Commission_Groups]
--              :     [Lup_AP_Discount_Groups]
--              :     [Lup_AP_Product_Departments]
--              :     [Lup_AP_Product_Groups]
--              :     [Lup_AP_Product_Locations]
--              :     [Lup_AP_Product_Manufacturers]
--              :     [Lup_AP_Product_Types]
--Parameters    :
--Date          :2002/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :07/01/03 - Refreshed with latest table defs
--              :18/10/03 - Refreshed with latest table defs
--              :20/12/03 - Refreshed with latest table defs
--              :14/01/04 - Refreshed with latest table defs
--              :09/03/04 - Refreshed with latest table defs - ADV2004 - RC4
--              :20/07/04 - Refreshed with latest table defs - 2004.1.0
--2004.3.7      :29/08/07 - Refreshed with latest table defs - 2004.3.7
--2004.3.8      :04/05/08 - Refreshed with latest table defs - 2004.3.8
-------------------------------------------------------------------------------

CREATE                              PROCEDURE [dbo].[sp_AW_9990]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

BEGIN



    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Departments]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Departments

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Groups]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Groups

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Lup_AP_Product_Locations]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products] DROP CONSTRAINT FK_AP_Products_Lup_AP_Product_Locations

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Variable_Lup_AP_Product_Locations]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Variable] DROP CONSTRAINT FK_AP_Products_Variable_Lup_AP_Product_Locations

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Manufacturers]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Manufacturers

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Types]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Types

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Ins_Lup_AP_Commission_Groups_ID]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
    drop trigger [dbo].[Ins_Lup_AP_Commission_Groups_ID]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Ins_Lup_AP_Discount_Groups_ID]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
    drop trigger [dbo].[Ins_Lup_AP_Discount_Groups_ID]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Slow_Moving_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Slow_Moving_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Filter]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Filter]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Valuation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Valuation]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Adjustments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Adjustments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Valuations]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Valuations]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Month_Sales_Actuals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Month_Sales_Actuals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Month_Sales_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Month_Sales_Budgets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Product_Selling_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Product_Selling_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Assemblies]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Assemblies]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_History]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_History]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Inventory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Inventory]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Static]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Static]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Stock_Takes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Stock_Takes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Suppliers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Suppliers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Variable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Variable]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Exchange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Exchange]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Take_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Take_Procedures]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Commission_Groups]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Commission_Groups]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Discount_Groups]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Discount_Groups]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_PLU_Tabs]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_PLU_Tabs]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Product_Departments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Product_Departments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Product_Groups]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Product_Groups]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Product_Locations]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Product_Locations]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Product_Manufacturers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Product_Manufacturers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Product_Types]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Product_Types]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Lup_AP_Purchase_Categories]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Lup_AP_Purchase_Categories]

    
    CREATE TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] (
    	[AP_Enterprise_Slow_Moving_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock] (
    	[AP_Enterprise_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Filter] (
    	[AP_Enterprise_Stock_Filter_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Valuation] (
    	[AP_Enterprise_Stock_Valuation_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Adjustments] (
    	[AP_Inventory_Adjustments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Sys_AP_Adjustment_Types_ID] [tinyint] NULL ,
    	[Previous_Last_Cost] [money] NOT NULL ,
    	[Previous_Average_Cost] [money] NULL ,
    	[Previous_On_Hand] [decimal](9, 3) NULL ,
    	[Previous_Job_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Quote_Reserved] [decimal](9, 3) NULL ,
    	[New_Last_Cost] [money] NULL ,
    	[New_Average_Cost] [money] NULL ,
    	[New_On_Hand] [decimal](9, 3) NULL ,
    	[New_Job_Reserved] [decimal](9, 3) NULL ,
    	[New_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[New_Quote_Reserved] [decimal](9, 3) NULL ,
    	[Note] [varchar] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Valuations] (
    	[AP_Inventory_Valuations_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Qty_On_Hand] [money] NULL ,
    	[Date_Captured] [smalldatetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Month_Sales_Actuals] (
    	[AP_Month_Sales_Actuals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Calender_Year] [smallint] NOT NULL ,
    	[January] [money] NULL ,
    	[February] [money] NULL ,
    	[March] [money] NULL ,
    	[April] [money] NULL ,
    	[May] [money] NULL ,
    	[June] [money] NULL ,
    	[July] [money] NULL ,
    	[August] [money] NULL ,
    	[September] [money] NULL ,
    	[October] [money] NULL ,
    	[November] [money] NULL ,
    	[December] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Month_Sales_Budgets] (
    	[AP_Month_Sales_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Calender_Year] [smallint] NOT NULL ,
    	[January] [money] NULL ,
    	[February] [money] NULL ,
    	[March] [money] NULL ,
    	[April] [money] NULL ,
    	[May] [money] NULL ,
    	[June] [money] NULL ,
    	[July] [money] NULL ,
    	[August] [money] NULL ,
    	[September] [money] NULL ,
    	[October] [money] NULL ,
    	[November] [money] NULL ,
    	[December] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Product_Selling_Prices] (
    	[AP_Product_Selling_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Prev_Price1_Effective_Date] [datetime] NULL ,
    	[Prev_Price1_Price1] [money] NULL ,
    	[Prev_Price1_Price2] [money] NULL ,
    	[Prev_Price2_Effective_Date] [datetime] NULL ,
    	[Prev_Price2_Price1] [money] NULL ,
    	[Prev_Price2_Price2] [money] NULL ,
    	[New_Price1_Effective_Date] [datetime] NULL ,
    	[New_Price1_Price1] [money] NULL ,
    	[New_Price1_Price2] [money] NULL ,
    	[New_Price2_Effective_Date] [datetime] NULL ,
    	[New_Price2_Price1] [money] NULL ,
    	[New_Price2_Price2] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products] (
    	[AP_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Print_Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SKU_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Measure] [decimal](9, 3) NULL ,
    	[Slu_AP_Units_Of_Measure_ID] [int] NULL ,
    	[Manufacturer_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Manufacturer_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_YesNo_Self_Managed] [tinyint] NULL ,
    	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
    	[Default_Supplier_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Lup_AP_Product_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NULL ,
    	[Lup_AP_Sell_By_Codes_ID] [int] NULL ,
    	[Alternate_Code1] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Alternate_Code2] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supercession] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Last_Cost] [money] NOT NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Standard_Disc1] [decimal](7, 2) NULL ,
    	[Standard_Disc2] [decimal](7, 2) NULL ,
    	[Average_Markup] [decimal](8, 4) NULL ,
    	[Price1_Effective_Date] [datetime] NULL ,
    	[Price1_Price1] [money] NULL ,
    	[Price1_Price2] [money] NULL ,
    	[Price2_Effective_Date] [datetime] NULL ,
    	[Price2_Price1] [money] NULL ,
    	[Price2_Price2] [money] NULL ,
    	[Lup_AP_Rounding_Codes_ID] [int] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Lup_AP_Discount_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Commission_Groups_ID] [smallint] NULL ,
    	[Pack_Volume] [decimal](9, 3) NULL ,
    	[Lup_AP_Mass_Codes_ID] [int] NULL ,
    	[Pack_Mass] [decimal](9, 3) NULL ,
    	[Strength] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Quote_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Slu_AW_YesNo_Assembly] [tinyint] NULL ,
    	[Serial_Number] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Show_Image] [bit] NULL ,
    	[Image_File_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_YesNo_Edit_Price] [tinyint] NULL ,
    	[Slu_AW_YesNo_Edit_Discount] [tinyint] NULL ,
    	[Max_Discount_Perc] [decimal](5, 2) NULL ,
    	[Slu_AW_YesNo_Max_Discount_Perc] [tinyint] NULL ,
    	[Memo] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Keywords] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[PLU_Tab] [tinyint] NULL ,
    	[Slu_AW_YesNo_Non_Stock_Item] [tinyint] NULL ,
    	[GL_Purchases_ID] [int] NULL ,
    	[GL_Sales_ID] [int] NULL ,
    	[GL_COS_ID] [int] NULL ,
    	[Lup_AP_Purchase_Categories_ID] [int] NULL ,
    	[Lup_AP_Markup_Groups_ID] [smallint] NULL ,
    	[Slu_AW_YesNo_Cost_Plus_Item] [tinyint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Assemblies] (
    	[AP_Products_Assemblies_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Parent_Product_ID] [int] NULL ,
    	[AP_Child_Product_ID] [int] NULL ,
    	[Units] [smallint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_History] (
    	[AP_Products_History_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Inventory] (
    	[AP_Products_Inventory_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_Static_ID] [int] NOT NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NOT NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Date_Updated] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Static] (
    	[AP_Products_Static_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Print_Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Keywords] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SKU_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Measure] [decimal](9, 3) NULL ,
    	[Slu_AP_Units_Of_Measure_ID] [int] NULL ,
    	[Manufacturer_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Manufacturer_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Lup_AP_Product_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Alternate_Code1] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Alternate_Code2] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supercession] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Volume] [decimal](9, 3) NULL ,
    	[Lup_AP_Mass_Codes_ID] [int] NULL ,
    	[Pack_Mass] [decimal](9, 3) NULL ,
    	[Strength] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Memo] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Date_Updated] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Stock_Takes] (
    	[AP_Products_Stock_Takes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[Count1] [decimal](9, 3) NULL ,
    	[Count2] [decimal](9, 3) NULL ,
    	[Count3] [decimal](9, 3) NULL ,
    	[Count4] [decimal](9, 3) NULL ,
    	[Total_Count] AS (isnull([Count1],0) + isnull([Count2],0) + isnull([Count3],0) + isnull([Count4],0)) ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Suppliers] (
    	[AP_Products_Suppliers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Lead_Time] [smallint] NULL ,
    	[Trade_Disc_Perc] [decimal](5, 2) NULL ,
    	[Trade_Disc_Date] [datetime] NULL ,
    	[Start_Date] [datetime] NULL ,
    	[AW_Trade_Discount_Formula_ID] [smallint] NULL ,
    	[AW_Rebate_Discount_Formula_ID] [smallint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Variable] (
    	[AP_Products_Variable_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_Static_ID] [int] NOT NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NULL ,
    	[Default_Supplier_ID] [int] NULL ,
    	[Lup_AP_Sell_By_Codes_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Average_Markup] [decimal](8, 4) NULL ,
    	[Price1_Effective_Date] [datetime] NULL ,
    	[Price1_Price1] [money] NULL ,
    	[Price1_Price2] [money] NULL ,
    	[Price2_Effective_Date] [datetime] NULL ,
    	[Price2_Price1] [money] NULL ,
    	[Price2_Price2] [money] NULL ,
    	[Lup_AP_Rounding_Codes_ID] [int] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Lup_AP_Discount_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Commission_Groups_ID] [smallint] NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Quote_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Slu_AW_YesNo_Assembly] [tinyint] NULL ,
    	[Serial_Number] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Show_Image] [bit] NULL ,
    	[Image_File_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_YesNo_Edit_Price] [tinyint] NULL ,
    	[Slu_AW_YesNo_Edit_Discount] [tinyint] NULL ,
    	[Max_Discount_Perc] [decimal](5, 2) NULL ,
    	[Slu_AW_YesNo_Max_Discount_Perc] [tinyint] NULL ,
    	[PLU_Tab] [tinyint] NULL ,
    	[Slu_AW_YesNo_Non_Stock_Item] [tinyint] NULL ,
    	[Slu_AW_YesNo_Self_Managed] [tinyint] NULL ,
    	[GL_Purchases_ID] [int] NULL ,
    	[GL_Sales_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Date_Updated] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Exchange] (
    	[AP_Stock_Exchange_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[NodeName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[On_Order] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Count_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Take_Procedures] (
    	[AP_Stock_Take_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AW_Period_Procedure_Types_ID] [int] NULL ,
    	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Month] [tinyint] NULL ,
    	[Year] [smallint] NULL ,
    	[Month_End_Date] [datetime] NULL ,
    	[Year_End_Date] [datetime] NULL ,
    	[Stock_Valuation] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Transfers] (
    	[AP_Stock_Transfers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Transfer_Date] [datetime] NULL ,
    	[Note] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Commission_Groups] (
    	[Lup_AP_Commission_Groups_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Discount_Groups] (
    	[Lup_AP_Discount_Groups_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_PLU_Tabs] (
    	[Lup_AP_PLU_Tabs_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Tab_No] [tinyint] NULL ,
    	[Description] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Product_Departments] (
    	[Lup_AP_Product_Departments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Min_GP_Percentage] [decimal](7, 2) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Product_Groups] (
    	[Lup_AP_Product_Groups_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Product_Locations] (
    	[Lup_AP_Product_Locations_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Product_Manufacturers] (
    	[Lup_AP_Product_Manufacturers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Default_Supplier_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Product_Types] (
    	[Lup_AP_Product_Types_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Purchase_Categories] (
    	[Lup_AP_Purchase_Categories_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Inventory_Adjustments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Adjustments] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Adjustments_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Valuations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Valuations] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Valuations_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Month_Sales_Actuals] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Month_Sales_Actuals] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Month_Sales_Actuals_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Month_Sales_Budgets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Month_Sales_Budgets] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Month_Sales_Budgets_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_History_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Inventory] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Inventory] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Inventory_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Static] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Static] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Static_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Stock_Takes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Stock_Takes] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Stock_Takes_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Variable] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Variable] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Variable_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Exchange] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Exchange] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Exchange_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Take_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Take_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Take_Procedures_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Transfers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Transfers] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Transfers_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Commission_Groups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_Commission_Groups] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Commission_Groups_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Discount_Groups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_Discount_Groups] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Discount_Groups_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_PLU_Tabs] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_PLU_Tabs] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_PLU_Tabs_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Departments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Departments] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Departments_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Groups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Groups] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Groups_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Locations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Locations] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Locations_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Manufacturers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_Product_Manufacturers] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Manufacturers_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Types] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Types] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Types_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Purchase_Categories] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Purchase_Categories] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Purchase_Categories_ID]
    	)  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Slow_Moving_Stock_Search] ON [dbo].[AP_Enterprise_Slow_Moving_Stock]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Search] ON [dbo].[AP_Enterprise_Stock]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Filter_Search] ON [dbo].[AP_Enterprise_Stock_Filter]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Valuation_Search] ON [dbo].[AP_Enterprise_Stock_Valuation]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Product_Selling_Prices] ON [dbo].[AP_Product_Selling_Prices]([AP_Products_ID]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Products_Assemblies_AP_Child_Product_ID] ON [dbo].[AP_Products_Assemblies]([AP_Child_Product_ID]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Products_Suppliers_AP_Products_ID] ON [dbo].[AP_Products_Suppliers]([AP_Products_ID]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Slow_Moving_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Slow_Moving_Stock_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Filter] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Filter] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Filter_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Valuation] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Valuation] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Valuation_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Inventory_Adjustments_AP_Products_ID] ON [dbo].[AP_Inventory_Adjustments]([AP_Products_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Product_Selling_Prices] ADD 
    	CONSTRAINT [PK_AP_Product_Selling_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Product_Selling_Prices_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_AP_Products_Types_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Types_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_AP_Product_Manufacturers_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Manufacturers_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Mass_Codes_ID] ON [dbo].[AP_Products]([Lup_AP_Mass_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AW_Tax_Codes_ID] ON [dbo].[AP_Products]([Sys_AW_Tax_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Rounding_Codes_ID] ON [dbo].[AP_Products]([Lup_AP_Rounding_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Sell_By_Codes_ID] ON [dbo].[AP_Products]([Lup_AP_Sell_By_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Product_Locations_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Locations_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Product_Departments_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Departments_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Product_Groups_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Units_Of_Measure_ID] ON [dbo].[AP_Products]([Slu_AP_Units_Of_Measure_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Discount_Groups_ID] ON [dbo].[AP_Products]([Lup_AP_Discount_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Product_Code] ON [dbo].[AP_Products]([Product_Code]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Products_Assemblies] ADD 
    	CONSTRAINT [PK_AP_Products_Assemblies] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Products_Assemblies_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_Assemblies_AP_Parent_Product_ID] ON [dbo].[AP_Products_Assemblies]([AP_Parent_Product_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_History_AP_Products_ID] ON [dbo].[AP_Products_History]([AP_Products_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_AP_Products_Static_ID] ON [dbo].[AP_Products_Inventory]([AP_Products_Static_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_Date_Updated] ON [dbo].[AP_Products_Inventory]([Date_Updated]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Product_Code] ON [dbo].[AP_Products_Static]([Product_Code]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Description] ON [dbo].[AP_Products_Static]([Description]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_AP_Product_Manufacturers_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Manufacturers_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Manufacturer_Code] ON [dbo].[AP_Products_Static]([Manufacturer_Code]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Lup_AP_Product_Departments_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Departments_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Lup_AP_Product_Groups_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_AP_Products_Static_Lup_AP_Product_Types_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Types_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Date_Updated] ON [dbo].[AP_Products_Static]([Date_Updated]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Stock_Takes_AP_Products_ID] ON [dbo].[AP_Products_Stock_Takes]([AP_Products_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Products_Suppliers] ADD 
    	CONSTRAINT [PK_AP_Products_Suppliers] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Products_Suppliers_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_Suppliers_AO_Suppliers_ID] ON [dbo].[AP_Products_Suppliers]([AO_Suppliers_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_AP_Products_Static_ID] ON [dbo].[AP_Products_Variable]([AP_Products_Static_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AW_Tax_Codes_ID] ON [dbo].[AP_Products_Variable]([Sys_AW_Tax_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Rounding_Codes_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Rounding_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Sell_By_Codes_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Sell_By_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Product_Locations_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Product_Locations_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Discount_Groups_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Discount_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Date_Updated] ON [dbo].[AP_Products_Variable]([Date_Updated]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IDX_Product_Code_NodeName] ON [dbo].[AP_Stock_Exchange]([Product_Code], [NodeName]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Stock_Exchange_AP_Products_ID] ON [dbo].[AP_Stock_Exchange]([AP_Products_ID]) ON [PRIMARY]

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Slow_Moving_Stock].[Pack_Size]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock].[Pack_Size]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Filter].[Pack_Size]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Valuation].[Pack_Size]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Adjustments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Adjustments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Adjustments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Sys_AP_Adjustment_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Adjustments].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Qty_On_Hand]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[April]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[August]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Month_Sales_Actuals].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[Calender_Year]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Month_Sales_Actuals].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[December]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[February]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[January]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[July]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[June]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[March]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[May]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[November]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[October]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[September]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Month_Sales_Actuals].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Month_Sales_Actuals].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[April]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[August]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Month_Sales_Budgets].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[Calender_Year]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Month_Sales_Budgets].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[December]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[February]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[January]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[July]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[June]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[March]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[May]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[November]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[October]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[September]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Month_Sales_Budgets].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Month_Sales_Budgets].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Product_Selling_Prices].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price1_Effective_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price2_Effective_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price1_Effective_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price2_Effective_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Product_Selling_Prices].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Product_Selling_Prices].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Average_Markup]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Default_Supplier_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Description]', N'[AP_Products].[Description]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[GL_COS_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[GL_Purchases_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[GL_Sales_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Commission_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Discount_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Markup_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Mass_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Departments_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Locations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Manufacturers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Purchase_Categories_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Rounding_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Sell_By_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Measure]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Pack_Mass]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Pack_Size]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Pack_Volume]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price1_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price1_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price2_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price2_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Service_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Show_Image]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Slu_AP_Units_Of_Measure_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Assembly]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Cost_Plus_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Slu_AW_YesNo_Edit_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Slu_AW_YesNo_Edit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Non_Stock_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Self_Managed]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Standard_Disc1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Standard_Disc2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Assemblies].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Assemblies].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Assemblies].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Assemblies].[Units]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Assemblies].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_History].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_History].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Inventory].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Inventory].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Products_Inventory].[Date_Updated]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Inventory].[Lup_AP_Product_Locations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Inventory].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Inventory].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Inventory].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Static].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Static].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Products_Static].[Date_Updated]'

    
    EXEC sp_bindefault N'[dbo].[df_Description]', N'[AP_Products_Static].[Description]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Mass_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Departments_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Manufacturers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Static].[Measure]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Static].[Pack_Mass]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Pack_Size]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Static].[Pack_Volume]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Slu_AP_Units_Of_Measure_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Static].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Static].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count3]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count4]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Rebate_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Trade_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Suppliers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Suppliers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[Lead_Time]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Suppliers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Suppliers].[Trade_Disc_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Suppliers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Average_Markup]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Variable].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Variable].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Default_Supplier_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Commission_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Discount_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Product_Locations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Rounding_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Sell_By_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price1_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price1_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price2_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price2_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Service_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Show_Image]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Variable].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Assembly]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Slu_AW_YesNo_Edit_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Slu_AW_YesNo_Edit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Non_Stock_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Self_Managed]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Variable].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Exchange].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Exchange].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Order]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Exchange].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Take_Procedures].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Take_Procedures].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Take_Procedures].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Take_Procedures].[Stock_Valuation]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Take_Procedures].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Stock_Transfers].[AB_Accounts_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Quantity]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Transfers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Commission_Groups].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Commission_Groups].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Commission_Groups].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Commission_Groups].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Discount_Groups].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Discount_Groups].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Discount_Groups].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Discount_Groups].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_PLU_Tabs].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_PLU_Tabs].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_PLU_Tabs].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_PLU_Tabs].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Departments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Departments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[Lup_AP_Product_Departments].[Min_GP_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Departments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Departments].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Groups].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Groups].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Groups].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Groups].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Locations].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Locations].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Locations].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Locations].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Manufacturers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Manufacturers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Lup_AP_Product_Manufacturers].[Default_Supplier_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Manufacturers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Manufacturers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Types].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Types].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Types].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Types].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Purchase_Categories].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Purchase_Categories].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Purchase_Categories].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Purchase_Categories].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AP_Products] ADD 
    	CONSTRAINT [FK_AP_Products_AW_User_Companies] FOREIGN KEY 
    	(
    		[AW_User_Companies_ID]
    	) REFERENCES [dbo].[AW_User_Companies] (
    		[AW_User_Companies_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Mass_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Mass_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Mass_Codes] (
    		[Lup_AP_Mass_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Product_Locations] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Locations_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Locations] (
    		[Lup_AP_Product_Locations_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Rounding_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Rounding_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Rounding_Codes] (
    		[Lup_AP_Rounding_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Sell_By_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Sell_By_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Sell_By_Codes] (
    		[Lup_AP_Sell_By_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Unit_Types] FOREIGN KEY 
    	(
    		[Slu_AP_Units_Of_Measure_ID]
    	) REFERENCES [dbo].[Slu_AP_Units_Of_Measure] (
    		[Slu_AP_Units_Of_Measure_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AW_Tax_Codes] FOREIGN KEY 
    	(
    		[Sys_AW_Tax_Codes_ID]
    	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
    		[Sys_AW_Tax_Codes_ID]
    	)

    
    ALTER TABLE [dbo].[AP_Products_Static] ADD 
    	CONSTRAINT [FK_AP_Products_Static_AW_User_Companies] FOREIGN KEY 
    	(
    		[AW_User_Companies_ID]
    	) REFERENCES [dbo].[AW_User_Companies] (
    		[AW_User_Companies_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Mass_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Mass_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Mass_Codes] (
    		[Lup_AP_Mass_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Departments] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Departments_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Departments] (
    		[Lup_AP_Product_Departments_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Groups] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Groups_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Groups] (
    		[Lup_AP_Product_Groups_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Manufacturers] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Manufacturers_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Manufacturers] (
    		[Lup_AP_Product_Manufacturers_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Types] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Types_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Types] (
    		[Lup_AP_Product_Types_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Slu_AP_Units_Of_Measures] FOREIGN KEY 
    	(
    		[Slu_AP_Units_Of_Measure_ID]
    	) REFERENCES [dbo].[Slu_AP_Units_Of_Measure] (
    		[Slu_AP_Units_Of_Measure_ID]
    	)

    
    ALTER TABLE [dbo].[AP_Products_Variable] ADD 
    	CONSTRAINT [FK_AP_Products_Variable_AW_User_Companies] FOREIGN KEY 
    	(
    		[AW_User_Companies_ID]
    	) REFERENCES [dbo].[AW_User_Companies] (
    		[AW_User_Companies_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AP_Product_Locations] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Locations_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Locations] (
    		[Lup_AP_Product_Locations_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AP_Rounding_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Rounding_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Rounding_Codes] (
    		[Lup_AP_Rounding_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AP_Sell_By_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Sell_By_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Sell_By_Codes] (
    		[Lup_AP_Sell_By_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AW_Tax_Codes] FOREIGN KEY 
    	(
    		[Sys_AW_Tax_Codes_ID]
    	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
    		[Sys_AW_Tax_Codes_ID]
    	)

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)

    
    SET QUOTED_IDENTIFIER ON 

    SET ANSI_NULLS ON 

    
    
    
    
    -- -------------------------------------------------------------------------------
    -- --Description   : Ins_Lup_AP_Commission_Groups_ID
    -- --Purpose       : Cartesian Product Insert
    -- --              : for a newly added Lup_AP_Commission_Groups record into
    -- --              : AS_Commission_Categories_Groups
    -- --Functionality : Tables: Lup_AP_Commission_Groups_ID, Lup_AS_Commission_Categories_ID
    -- --Parameters    : 
    -- --Date          : 2002/02/04
    -- --Authors       : TB
    -- --Version       : 1.0.0
    -- -------------------------------------------------------------------------------
    -- 
    -- CREATE TRIGGER  Ins_Lup_AP_Commission_Groups_ID 
    --     ON Lup_AP_Commission_Groups
    -- 
    -- FOR INSERT
    -- 
    -- AS
    -- 
    -- SET NOCOUNT ON
    -- 
    -- 	INSERT AS_Commission_Categories_Groups
    --         (
    --             Lup_AP_Commission_Groups_ID,
    --             Lup_AS_Commission_Categories_ID
    --         )
    --     SELECT i.Lup_AP_Commission_Groups_ID,
    --            dc.Lup_AS_Commission_Categories_ID
    --     FROM Inserted i
    --         CROSS JOIN Lup_AS_Commission_Categories dc
    -- 
    -- SET NOCOUNT OFF
    -- 
    -- 
    -- 
    -- 
    -- GO
    -- SET QUOTED_IDENTIFIER OFF 
    -- GO
    -- SET ANSI_NULLS ON 
    -- GO
    -- 
    -- SET QUOTED_IDENTIFIER ON 
    -- GO
    -- SET ANSI_NULLS ON 
    -- GO
    -- 
    -- 
    -- 
    -- 
    -- 
    -- -------------------------------------------------------------------------------
    -- --Description   : Ins_Lup_AP_Discount_Groups_ID
    -- --Purpose       : Cartesian Product Insert
    -- --              : for a newly added Lup_AC_Discount_Categories record into
    -- --              : AS_Discount_Categories_Groups
    -- --Functionality : Tables: Lup_AP_Discount_Groups_ID, Lup_AC_Discount_Categories_ID
    -- --Parameters    : 
    -- --Date          : 2002/02/04
    -- --Authors       : TB
    -- --Version       : 1.0.0
    -- -------------------------------------------------------------------------------
    -- 
    -- CREATE TRIGGER  Ins_Lup_AP_Discount_Groups_ID
    --     ON Lup_AP_Discount_Groups
    -- 
    -- FOR INSERT
    -- 
    -- AS
    -- 
    -- SET NOCOUNT ON
    -- 
    -- 	INSERT AS_Discount_Categories_Groups
    --         (
    --             Lup_AP_Discount_Groups_ID,
    --             Lup_AC_Discount_Categories_ID
    --         )
    --     SELECT i.Lup_AP_Discount_Groups_ID,
    --            dc.Lup_AC_Discount_Categories_ID
    --     FROM Inserted i
    --         CROSS JOIN Lup_AC_Discount_Categories dc
    -- 
    -- SET NOCOUNT OFF
    -- 
    -- 
    -- 
    -- 
    -- 
    -- GO
    -- SET QUOTED_IDENTIFIER OFF 
    -- GO
    -- SET ANSI_NULLS ON 
    -- GO












    ---------------------------------------
    -- INSERT a RECORD into Lookups
    ---------------------------------------

    INSERT Lup_AP_Product_Departments
        (
            Description,
            Old_Code
        )
        VALUES
        (
            '<None>',
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Groups
        (
            Description
        )
        VALUES
        (
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Locations
        (
            Description
        )
        VALUES
        (
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Manufacturers
        (
            Description,
            Old_Code
        )
        VALUES
        (
            '<None>',
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Types
        (
            Description
        )
        VALUES
        (
            '<None>'
        )
    
    
    INSERT Lup_AP_Commission_Groups
        (
            Description
        )
        VALUES
        (
            '<None>'
        )


    INSERT Lup_AP_Discount_Groups
        (
            Description
        )
        VALUES
        (
            '<None>'
        )


    INSERT AP_Products
        (
            Description,
            Print_Description,
            Product_Code,
            SKU_Code
        )
        VALUES
        (
            '<None>',
            '<None>',
            '000',
            '000'
        )


    SET @ReturnValue = 1

END

RETURN @ReturnValue
SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



-------------------------------------------------------------------------------
--Description   :sp_AW_9991
--Purpose       :Wipe all General Ledger and GL Lookup table contents
--Tables        :     [AB_Accounts]
--              :     [AB_Control_Accounts]
--              :     [Lup_AB_Cost_Centers_ID]
--Parameters    :
--Date          :2002/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :26/12/02 - Added Recon_Amount field to AB_Cash_Book_Transactions
--              :27/12/02 - Replaced with 'Recurring_Number', int field with
--              :           Recurring_Reference, varchar(30) field
--              :03/01/02 - Added NEW AB_Budgets, and NEW columns to AB_Accounts
--              :07/01/03 - Refreshed with latest table defs
--              :14/01/04 - Refreshed with latest table defs
--              :09/03/04 - Refreshed with latest table defs - ADV2004 - RC4
--              :20/07/04 - Refreshed with latest table defs - 2004.1.0
--2004.3.7      :02/10/07 - Refreshed with latest table defs - 2004.3.7
--2004.3.8      :04/05/08 - Refreshed with latest table defs - 2004.3.8
-------------------------------------------------------------------------------

CREATE                                PROCEDURE [dbo].[sp_AW_9991]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

    BEGIN
    
    
    
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_End_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_End_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_Start_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_Start_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Transactions_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_GL_Transactions] DROP CONSTRAINT FK_AB_Transactions_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Prior_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Month_Account_Actuals] DROP CONSTRAINT FK_AB_Prior_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Budget_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Month_Account_Budgets] DROP CONSTRAINT FK_AB_Budget_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Tabs_AB_Generator]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Columns] DROP CONSTRAINT FK_AB_Generator_Tabs_AB_Generator

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_Generator]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_Generator

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Journals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Journals

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Recurring]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Recurring

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Accounts]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Budgets]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Batches]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Cash_Book_Batches]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Cash_Book_Transaction_Details]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Cash_Book_Transactions]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Balance_Sheet]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Income_Statement]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Management_Accounts]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Trial_Balance]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_GL_Transactions]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Generator]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Generator]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Generator_Columns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Generator_Columns]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Generator_Rows]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Generator_Rows]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journal_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Journal_Details]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Journals]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Month_Account_Actuals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Month_Account_Actuals]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Month_Account_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Month_Account_Budgets]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Recurring]

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Recurring_Details]

        
        CREATE TABLE [dbo].[AB_Accounts] (
        	[AB_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Sys_AB_Account_Categories_ID] [int] NULL ,
        	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
        	[Lup_AB_Cost_Centers_ID] [int] NULL ,
        	[Lup_AB_Account_Divisions_ID] [int] NULL ,
        	[Lup_AB_Account_Groups_ID] [int] NULL ,
        	[AB_Account_Balance] [money] NULL ,
        	[Opening_Balance] [money] NULL ,
        	[Opening_Date] [datetime] NULL ,
        	[Opening_Month] [tinyint] NULL ,
        	[Opening_Year] [int] NULL ,
        	[AW_YesNo_Controllable_ID] [tinyint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Budgets] (
        	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Accounts_ID] [int] NOT NULL ,
        	[Slu_AW_Years_ID] [int] NOT NULL ,
        	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
        	[Budget_Amount] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Cash_Book_Batches] (
        	[AB_Cash_Book_Batches_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AW_Company_Banks_ID] [int] NULL ,
        	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
        	[Slu_AW_Months_ID] [tinyint] NULL ,
        	[Slu_AW_Years_ID] [smallint] NULL ,
        	[Transaction_Date] [datetime] NULL ,
        	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[AB_Accounts_ID] [int] NULL ,
        	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
        	[Split_Amount] [money] NULL ,
        	[VAT_Amount] [money] NULL ,
        	[Net_Amount] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Cash_Book_Transaction_Details] (
        	[AB_Cash_Book_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Cash_Book_Transactions_ID] [int] NULL ,
        	[AB_Accounts_ID] [int] NULL ,
        	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
        	[Amount] [money] NULL ,
        	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
        	[Tax_Amount] [money] NULL ,
        	[Net_Amount] [money] NULL ,
        	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Cash_Book_Transactions] (
        	[AB_Cash_Book_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AW_Company_Banks_ID] [int] NULL ,
        	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
        	[Transaction_Date] [datetime] NULL ,
        	[Slu_AW_Months_ID] [tinyint] NULL ,
        	[Slu_AW_Years_ID] [smallint] NULL ,
        	[Reference_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Transaction_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Recon_Amount] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Enterprise_Balance_Sheet] (
        	[AB_Enterprise_Balance_Sheet_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_B1_ID] [int] NULL ,
        	[Sys_AB_B2_ID] [int] NULL ,
        	[Sys_AB_B3_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Enterprise_Income_Statement] (
        	[AB_Enterprise_Income_Statement_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_I1_ID] [int] NULL ,
        	[Sys_AB_I2_ID] [int] NULL ,
        	[Sys_AB_I3_ID] [int] NULL ,
        	[Sys_AB_I4_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL ,
        	[TCRUST] [money] NULL ,
        	[TCSTEEL] [money] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
        	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_I1_ID] [int] NULL ,
        	[Sys_AB_I2_ID] [int] NULL ,
        	[Sys_AB_I3_ID] [int] NULL ,
        	[Sys_AB_I4_ID] [int] NULL ,
        	[Sys_AB_I5_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level5] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
        	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_GL_Transactions] (
        	[AB_GL_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
        	[AB_Accounts_ID] [int] NULL ,
        	[AB_Transaction_Date] [datetime] NULL ,
        	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Slu_AW_Months_ID] [int] NULL ,
        	[Slu_AW_Years_ID] [int] NULL ,
        	[AB_Transaction_Ref] [int] NULL ,
        	[AB_Transaction_Amount] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Generator] (
        	[AB_Generator_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Report_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Heading1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Heading2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Generator_Columns] (
        	[AB_Generator_Tabs_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Generator_ID] [int] NULL ,
        	[Tab_Heading1] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Heading2] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Content_Type] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Period_Type] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Period_Extent] [tinyint] NULL ,
        	[Tab_Calc_Column1] [tinyint] NULL ,
        	[Tab_Operator] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Calc_Column2] [tinyint] NULL ,
        	[Tab_Format_Mask] [decimal](18, 0) NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Generator_Rows] (
        	[AB_Generator_Rows_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Generator_ID] [int] NULL ,
        	[Row_Option] [char] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Memo] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_AB_Start_Account_ID] [int] NULL ,
        	[Row_AB_End_Account_ID] [int] NULL ,
        	[Row_Alt_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Print_All_Accounts] [tinyint] NULL ,
        	[Row_Sum_All_Accounts] [tinyint] NULL ,
        	[Row_Calculation_Type] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Total_Level] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Total_Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Print_Total] [tinyint] NULL ,
        	[Row_Print_Percentages] [tinyint] NULL ,
        	[Row_Percentage_Types] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Print_Prior] [tinyint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Journal_Details] (
        	[AB_Journal_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Journals_ID] [int] NULL ,
        	[AB_Accounts_ID] [int] NULL ,
        	[Amount] [money] NULL ,
        	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Journals] (
        	[AB_Journals_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Journal_Date] [datetime] NULL ,
        	[Journal_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Journal_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Slu_AW_Months_ID] [int] NULL ,
        	[Slu_AW_Years_ID] [int] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Month_Account_Actuals] (
        	[AB_Actuals_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Accounts_ID] [int] NOT NULL ,
        	[Calender_Year] [smallint] NOT NULL ,
        	[January] [money] NULL ,
        	[February] [money] NULL ,
        	[March] [money] NULL ,
        	[April] [money] NULL ,
        	[May] [money] NULL ,
        	[June] [money] NULL ,
        	[July] [money] NULL ,
        	[August] [money] NULL ,
        	[September] [money] NULL ,
        	[October] [money] NULL ,
        	[November] [money] NULL ,
        	[December] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Month_Account_Budgets] (
        	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Accounts_ID] [int] NOT NULL ,
        	[Calender_Year] [smallint] NOT NULL ,
        	[January] [money] NULL ,
        	[February] [money] NULL ,
        	[March] [money] NULL ,
        	[April] [money] NULL ,
        	[May] [money] NULL ,
        	[June] [money] NULL ,
        	[July] [money] NULL ,
        	[August] [money] NULL ,
        	[September] [money] NULL ,
        	[October] [money] NULL ,
        	[November] [money] NULL ,
        	[December] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Recurring] (
        	[AB_Recurring_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Recurring_Date] [datetime] NULL ,
        	[Recurring_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Recurring_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Slu_AW_Months_ID] [int] NULL ,
        	[Slu_AW_Years_ID] [int] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        CREATE TABLE [dbo].[AB_Recurring_Details] (
        	[AB_Recurring_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Recurring_ID] [int] NULL ,
        	[AB_Accounts_ID] [int] NULL ,
        	[Amount] [money] NULL ,
        	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Accounts] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Accounts] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Accounts_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Budgets_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Cash_Book_Batches] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Cash_Book_Batches] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Cash_Book_Batches_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Cash_Book_Transaction_Details] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Cash_Book_Transaction_Details_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Cash_Book_Transactions] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Cash_Book_Transactions] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Cash_Book_Transactions_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Enterprise_Balance_Sheet] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Balance_Sheet] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Balance_Sheet_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Enterprise_Income_Statement] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Income_Statement] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Income_Statement_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Management_Accounts_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Trial_Balance_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_GL_Transactions] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Transactions] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_GL_Transactions_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Generator] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Generator] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Generator_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Generator_Columns] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Generator_Tabs] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Generator_Tabs_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Generator_Rows] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Generator_Rows] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Generator_Rows_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Journal_Details] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Journal_Details] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Journal_Details_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Journals] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Journals] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Journals_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Month_Account_Actuals] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Month_Account_Actuals] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Actuals_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Month_Account_Budgets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Month_Account_Budgets] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Budgets_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Recurring] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Recurring] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Recurring_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Recurring_Details] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Recurring_Details] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Recurring_Details_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[AB_Account_Balance]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Accounts].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[AW_YesNo_Controllable_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Accounts].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Account_Divisions_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Account_Groups_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Cost_Centers_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Balance]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Accounts].[Opening_Date]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Month]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Year]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Accounts].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Sys_AB_Account_Categories_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Sys_AW_Tax_Codes_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Accounts].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Batches].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Batches].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Net_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Batches].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Batches].[Slu_AW_Months_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Batches].[Slu_AW_Years_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Split_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Batches].[User_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[VAT_Amount]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[AB_Accounts_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transaction_Details].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transaction_Details].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Net_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transaction_Details].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Codes_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Methods_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Tax_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transaction_Details].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transactions].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transactions].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transactions].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transactions].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Transactions].[Slu_AW_Months_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Transactions].[Slu_AW_Years_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transactions].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Ref]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_GL_Transactions].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_GL_Transactions].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_GL_Transactions].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_GL_Transactions].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Generator].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Generator].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Generator].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Generator].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Generator_Columns].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Generator_Columns].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Generator_Columns].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Calc_Column1]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Calc_Column2]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Format_Mask]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Period_Extent]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Generator_Columns].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Generator_Rows].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Generator_Rows].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_All_Accounts]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_Percentages]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_Prior]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_Total]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Sum_All_Accounts]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Generator_Rows].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Generator_Rows].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Journal_Details].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journal_Details].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journal_Details].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journal_Details].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journal_Details].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journals].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journals].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journals].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journals].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[April]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[August]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Month_Account_Actuals].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[Calender_Year]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Month_Account_Actuals].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[December]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[February]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[January]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[July]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[June]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[March]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[May]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[November]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[October]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[September]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Month_Account_Actuals].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Month_Account_Actuals].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[April]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[August]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Month_Account_Budgets].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[Calender_Year]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Month_Account_Budgets].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[December]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[February]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[January]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[July]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[June]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[March]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[May]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[November]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[October]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[September]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Month_Account_Budgets].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Month_Account_Budgets].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Recurring_Details].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring_Details].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring_Details].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring_Details].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring_Details].[User_ID]'

        
        setuser

        
        ALTER TABLE [dbo].[AB_Accounts] ADD 
        	CONSTRAINT [FK_AB_Accounts_Lup_AB_Cost_Centers] FOREIGN KEY 
        	(
        		[Lup_AB_Cost_Centers_ID]
        	) REFERENCES [dbo].[Lup_AB_Cost_Centers] (
        		[Lup_AB_Cost_Centers_ID]
        	),
        	CONSTRAINT [FK_AB_Accounts_Lup_AW_Tax_Codes] FOREIGN KEY 
        	(
        		[Sys_AW_Tax_Codes_ID]
        	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
        		[Sys_AW_Tax_Codes_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] ADD 
        	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	),
        	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions] FOREIGN KEY 
        	(
        		[AB_Cash_Book_Transactions_ID]
        	) REFERENCES [dbo].[AB_Cash_Book_Transactions] (
        		[AB_Cash_Book_Transactions_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Cash_Book_Transactions] ADD 
        	CONSTRAINT [FK_AB_Cash_Book_Transactions_AW_Company_Banks] FOREIGN KEY 
        	(
        		[AW_Company_Banks_ID]
        	) REFERENCES [dbo].[AW_Company_Banks] (
        		[AW_Company_Banks_ID]
        	)

        
        ALTER TABLE [dbo].[AB_GL_Transactions] ADD 
        	CONSTRAINT [FK_AB_GL_Transactions_Lup_AB_Transaction_Types] FOREIGN KEY 
        	(
        		[Sys_AB_Transaction_Types_ID]
        	) REFERENCES [dbo].[Sys_AB_Transaction_Types] (
        		[Sys_AB_Transaction_Types_ID]
        	),
        	CONSTRAINT [FK_AB_Transactions_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Generator_Columns] ADD 
        	CONSTRAINT [FK_AB_Generator_Tabs_AB_Generator] FOREIGN KEY 
        	(
        		[AB_Generator_ID]
        	) REFERENCES [dbo].[AB_Generator] (
        		[AB_Generator_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Generator_Rows] ADD 
        	CONSTRAINT [FK_AB_Generator_Rows_AB_End_Accounts] FOREIGN KEY 
        	(
        		[Row_AB_End_Account_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	),
        	CONSTRAINT [FK_AB_Generator_Rows_AB_Generator] FOREIGN KEY 
        	(
        		[AB_Generator_ID]
        	) REFERENCES [dbo].[AB_Generator] (
        		[AB_Generator_ID]
        	),
        	CONSTRAINT [FK_AB_Generator_Rows_AB_Start_Accounts] FOREIGN KEY 
        	(
        		[Row_AB_Start_Account_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Journal_Details] ADD 
        	CONSTRAINT [FK_AB_Journal_Details_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	),
        	CONSTRAINT [FK_AB_Journal_Details_AB_Journals] FOREIGN KEY 
        	(
        		[AB_Journals_ID]
        	) REFERENCES [dbo].[AB_Journals] (
        		[AB_Journals_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Month_Account_Actuals] ADD 
        	CONSTRAINT [FK_AB_Prior_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Month_Account_Budgets] ADD 
        	CONSTRAINT [FK_AB_Budget_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Recurring_Details] ADD 
        	CONSTRAINT [FK_AB_Recurring_Details_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	),
        	CONSTRAINT [FK_AB_Recurring_Details_AB_Recurring] FOREIGN KEY 
        	(
        		[AB_Recurring_ID]
        	) REFERENCES [dbo].[AB_Recurring] (
        		[AB_Recurring_ID]
        	)




    
    
    
    
    
    
    
        ---------------------------------------
        -- INSERT a RECORD into Lookups
        ---------------------------------------
    
        INSERT Lup_AB_Cost_Centers
            (
                Description
            )
            VALUES
            (
                '<None>'
            )
    
    
        INSERT AB_Accounts
            (
                Description,
                Account_Number
            )
            VALUES
            (
                '<Select An Account>',
                '000-000'
            )
    
    
        ------------------------------------------------------------
        --Set ALL Control Accounts to the only record in AB_Accounts
        ------------------------------------------------------------
        UPDATE AB_Control_Accounts
        SET AB_Accounts_ID = 1
        ------------------------------------------------------------
    
    
    
        SET @ReturnValue = 1
    
    END

RETURN @ReturnValue
SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



-------------------------------------------------------------------------------
--Description   :sp_AW_9992
--Purpose       :Wipe Option table contents
--Tables        :     [Sys_AW_Options]
--Parameters    :
--Date          :2002/09/29
--Authors       :TB
--Version       :1.0.0
--MODS          :18/10/03 - Increased Control_Value to 250
--              :14/01/04 - Refreshed with latest table defs
--              :09/03/04 - Refreshed with latest table defs - ADV2004 - RC4
--              :20/07/04 - Refreshed with latest table defs - 2004.1.0
--2004.3.8      :04/05/08 - Refreshed with latest table defs - 2004.3.8
-------------------------------------------------------------------------------

CREATE                           PROCEDURE [dbo].[sp_AW_9992]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

BEGIN




    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Sys_AW_Options]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Sys_AW_Options]

    
    CREATE TABLE [dbo].[Sys_AW_Options] (
    	[Sys_AW_Options_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Control_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Control_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Control_Index] [smallint] NULL ,
    	[Control_Value] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[Sys_AW_Options] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Sys_AW_Options] PRIMARY KEY  CLUSTERED 
    	(
    		[Sys_AW_Options_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Sys_AW_Options].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Sys_AW_Options].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Sys_AW_Options].[User_ID]'

    
    setuser











    SET @ReturnValue = 1

END

RETURN @ReturnValue



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Accountant_Status
--Purpose       :Select if User = Supervisor
--Functionality :User MUST BE IsAccountant to authorise
--Date          :2005/10/06
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Check_Accountant_Status
	(
        @Password varchar(20),
		@AccountantID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @AccountantID = 0

	SELECT TOP 1 @AccountantID = AW_Users_ID
	FROM AW_Users
    WHERE IsAccountant = 1 AND
          Slu_AW_Active_ID = 1 AND
          [Password] = @Password



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Product_Bin_Status
--Purpose       :Select if User = Product Bin Supervisor
--Functionality :User MUST BE IsBinSuper to authorise
--Date          :2016-05-02
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Check_Product_Bin_Status]
	(
        @Password varchar(20),
		@BinSuperID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @BinSuperID = 0

	SELECT TOP 1 @BinSuperID = AW_Users_ID
	FROM AW_Users
    WHERE IsBinSuper = 1 AND
          Slu_AW_Active_ID = 1 AND
          [Password] = @Password

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Supervisor_Status
--Purpose       :Select if User = Supervisor
--Functionality :User MUST BE IsSupervisor to authorise
--Date          :2004/01/25
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Check_Supervisor_Status
	(
        @Password varchar(20),
		@SupervisorID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @SupervisorID = 0

	SELECT TOP 1 @SupervisorID = AW_Users_ID
	FROM AW_Users
    WHERE IsSupervisor = 1 AND
          Slu_AW_Active_ID = 1 AND
          [Password] = @Password



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Till_Supervisor_Status
--Purpose       :Select if User = Supervisor
--Functionality :User MUST BE IsTillPayout to authorise
--Date          :2017/10/19
--Authors       :RL
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Check_Till_Supervisor_Status]
	(
        @Password varchar(20),
		@TillSupervisor int OUTPUT
	)
AS

SET NOCOUNT ON

    SET @TillSupervisor = 0

	SELECT TOP 1 @TillSupervisor = AW_Users_ID
	FROM AW_Users
    WHERE IsTillPayout = 1 AND
          Slu_AW_Active_ID = 1 AND
          [Password] = @Password

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Clear_Site_Manager
--Purpose       :Drop and ALTER  AW_Remote_Access table
--Date          :19 OCT 2008
--Authors       :TB
--MODS          :
--2004.4.3      :13/02/09 - Modified @DataServName increased size from 20 to 50
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AW_Clear_Site_Manager

AS

SET NOCOUNT ON


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Remote_Access]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Remote_Access]

    
    CREATE TABLE [dbo].[AW_Remote_Access] (
    	[AW_Remote_Access_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[NodeName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Network_Identity] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WinUserName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WinPassword] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Trusted_Connection] [tinyint] NULL ,
    	[DataServName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DataServIP1] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DataServIP2] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DataServIP3] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DataServIP4] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DBUserName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DBPassword] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DBCatalog] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebServName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebServIP1] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebServIP2] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebServIP3] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebServIP4] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebSiteURL] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[DSNName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Default_Connection] [tinyint] NULL ,
    	[Port] [varchar] (4) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[WebServURL] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Countries_ID] [smallint] NULL ,
    	[Area_Code] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Modem_Tel_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SQLQuery] [varchar] (2000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_Address1] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_Address2] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_Address3] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_TelNo] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_FaxNo] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_VATNo] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Billing_RegNo] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Address1] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Address2] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Address3] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AW_Remote_Access] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Remote_Access] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Remote_Access_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Remote_Access].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Remote_Access].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Remote_Access].[Default_Connection]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Remote_Access].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Country]', N'[AW_Remote_Access].[Slu_AW_Countries_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Remote_Access].[Trusted_Connection]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Remote_Access].[User_ID]'

    
    setuser








SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :Save the Comments here
--Purpose       :The actortype is Customer, User etc
--Functionality :
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       : 1
------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AW_Comments_Insert_Update
    (
        @CommentID int =NULL,
        @ActorTypeID int = NULL,
        @ActorID int = NULL,
        @Comment varchar(500) = NULL,
        @CompanyID int = NULL,
        @UserID int = NULL
    )

AS

SET NOCOUNT ON

    IF NOT @CommentID IS NULL
        UPDATE AW_Comments
        SET Sys_AT_Actor_Types_ID = @ActorTypeID,
            Actor_ID = @ActorID,
            Comment = @Comment,
            AW_User_Companies_ID = @CompanyID,
            [User_ID] = @UserID,
            Date_Captured = getdate()
		WHERE AW_Comments_ID = @CommentID			
	ELSE
		BEGIN	
			INSERT AW_Comments 
            	(
            		Sys_AT_Actor_Types_ID,
            		Actor_ID,
            		Comment,
            		AW_User_Companies_ID,
            		[User_ID],
            		Date_Captured
            	)
            VALUES
            	(
            		@ActorTypeID,
            		@ActorID,
            		@Comment,
            		@CompanyID ,
            		@UserID,
            		getdate()
            	)

			SELECT @CommentID = Scope_Identity()
			
		END

	RETURN @CommentID


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





--Description   : Select comments 
--Purpose       : Used at POS
--Functionality : 
--Parameters    : 
--Date          : 2001/07/19
--Authors       : GL
--Version       : 1
-------------------------------------------------------------------------------
CREATE PROCEDURE sp_AW_Comments_Select
	(
		@ActorID int,
		@ActorTypeID smallint = -1  --Customer
	)
AS
    SET NOCOUNT ON
    SELECT 
		AW_Comments_ID 			as CommentID, 
		Sys_AT_Actor_Types_ID 	as ActorTypeID, 
		Actor_ID 					as ActorID, 
		Comment 					as Comment,
		AW_User_Companies_ID 	as CompanyID,
		User_ID 					as UserID
	FROM AW_Comments
	WHERE Sys_AT_Actor_Types_ID = @ActorTypeID AND
			Actor_ID = @ActorID





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AW_Company_Info
--Purpose       :Retrieve Month-End Company Data
--              :
--Parameters    :
--Date          :2002/03/04
--Authors       :TB
--Version       :1.0.0
--MODS          :18/11/03 - Added ISNULL validation for each field
--              :02/06/04 - Added Company_Registration_Number field
-------------------------------------------------------------------------------


CREATE      PROCEDURE sp_AW_Company_Info
    (
    	@CompanyID int,
    	@Name varchar(50) OUTPUT,
    	@Address1 varchar(50) OUTPUT,
    	@Address2 varchar(50) OUTPUT,
    	@City varchar(50) OUTPUT,
    	@PostalCode varchar(10) OUTPUT,
    	@TelNo varchar(20) OUTPUT,
    	@FaxNo varchar(20) OUTPUT,
    	@Email varchar(50) OUTPUT,
    	@RegNo varchar(16) OUTPUT
    )

AS

SET NOCOUNT ON



   SELECT TOP 1
      --AW_User_Companies_ID, 
      @Name = ISNULL(Company_Name, ''), 
      @Address1 = ISNULL(Company_Addr1, ''), 
      @Address2 = ISNULL(Company_Addr2, ''), 
      @City = ISNULL(Company_City, ''), 
      @PostalCode = ISNULL(Company_Post_Code, ''), 
      @TelNo = ISNULL(Tel_No, ''), 
      @FaxNo = ISNULL(Fax_No, ''), 
      @Email = ISNULL(E_Mail, ''),
      @RegNo = ISNULL(Company_Registration_Number, '')
   FROM AW_User_Companies
   WHERE AW_User_Companies_ID = @CompanyID

   SELECT TOP 1
        AW_User_Companies_ID, 
        Company_Name, 
        Company_Addr1, 
        Company_Addr2, 
        Company_City, 
        Company_Post_Code, 
        Tel_No,
        Fax_No,
        E_Mail,
        Company_Registration_Number
   FROM AW_User_Companies
   WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AW_Currency_Formula
--Purpose       : 
--Functionality : 
--Parameters    :
--Date          :2002/02/18
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE   PROC sp_AW_Currency_Formula
    (
        @TransactionType tinyint = 1,
        @FormulaID int = 0,
        @Formula varchar(1000) ='',
        @Description varchar(50) = ''
    --    @NewID int OUTPUT
    )

AS

SET NOCOUNT ON

    IF @TransactionType = 1 
        SELECT 
            AW_Currency_Formulas_ID AS [ID],
            [Description],
            Formula
        FROM AW_Currency_Formulas
        WHERE AW_Currency_Formulas_ID = @FormulaID

    ELSE
    IF @FormulaID = 0
        BEGIN
            INSERT AW_Currency_Formulas
                (
                    Formula,
                    [Description]
                )
                VALUES
                (
                    @Formula,
                    @Description
                )
  --          SET @NewID = @@Identity
        END
    ELSE     
    IF EXISTS ( SELECT AW_Currency_Formulas_ID
                FROM AW_Currency_Formulas
                WHERE AW_Currency_Formulas_ID = @FormulaID )
        
        BEGIN
            UPDATE AW_Currency_Formulas 
            SET [Description] = @Description, Formula = @Formula
            WHERE AW_Currency_Formulas_ID = @FormulaID
--            SET @NewID = @FormulaID
        END
    ELSE
        INSERT AW_Currency_Formulas
                (
                    Formula,
                    [Description]
                )
            VALUES
                (
                    @Formula,
                    @Description
                )
--        SET @NewID = @@Identity    


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------------
--Description   : sp_AW_Delete_Cashier_Till
--Purpose       : Deletes a selected Cashier Till
--Date          : 2004/01/13
--Authors       : TB
--Version       : 1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Delete_Cashier_Till
    (
        @UserTillID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AW_Users_Tills_ID
            FROM AW_Users_Tills
            WHERE AW_Users_Tills_ID = @UserTillID
        )
        BEGIN

            DELETE AW_Users_Tills
            WHERE AW_Users_Tills_ID = @UserTillID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AW_Delete_Last_Period_Procedure
--Purpose       :DELETES DUPLIDATED CUSTOMER PERIOD PROCEDURE
--Functinality  :Deletes Statement and Details using a CURSOR
--Date          :2005/04/30
--Authors       :TB
--MODS          :
--2004.3.4      :07/03/07 - Added @ProcedureTypeID input parameter
--              :07/03/07 - Added Delete Suppliers Period Procedure
--2004.3.8      :26/04/08 - Added @UserID input parameter
--              :26/04/08 - Added INSERT INTO AW_Period_Procedures_Deleted LOG
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Delete_Last_Period_Procedure
	(
        @CompanyID int,
        @UserID int,
        @ProcedureID int,
        @ProcedureTypeID int
	)

AS

SET NOCOUNT ON


    DECLARE @StatementID int,
            @MEDescription varchar(500),
            @MEMonthID tinyint,
            @MEYearID smallint,
            @MEMonthEndDate datetime,
            @MEYearEndDate datetime,
            @MEStockValuation money,
            @ReturnValue int


    SET @ReturnValue = 0


    ------------------------------------------------------------
    --> INSERT INTO AW_Period_Procedures_Deleted LOG
    ------------------------------------------------------------
    SELECT @MEDescription = Description,
           @MEMonthID = [Month],
           @MEYearID = [Year],
           @MEMonthEndDate = Month_End_Date,
           @MEYearEndDate = Year_End_Date,
           @MEStockValuation = Stock_Valuation
    FROM AW_Period_Procedures
    WHERE AW_Period_Procedures_ID = @ProcedureID AND
          AW_User_Companies_ID = @CompanyID

    ---------------------------------------

    INSERT AW_Period_Procedures_Deleted
        (
            AW_Period_Procedures_ID,
            Sys_AW_Period_Procedure_Types_ID,
            Description,
            Month_ID,
            Year_ID,
            Month_End_Date,
            Year_End_Date,
            Stock_Valuation,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
        )
    VALUES
        (
            @ProcedureID,
            @ProcedureTypeID,
            @MEDescription,
            @MEMonthID,
            @MEYearID,
            @MEMonthEndDate,
            @MEYearEndDate,
            @MEStockValuation,
            getdate(),
            @UserID,
            @CompanyID
        )
    ------------------------------------------------------------


    IF @ProcedureTypeID = 1        -- Customers
        BEGIN
            IF EXISTS
                (
                    SELECT AW_Period_Procedures_ID
                    FROM AW_Period_Procedures
                    WHERE AW_Period_Procedures_ID = @ProcedureID AND
                          AW_User_Companies_ID = @CompanyID
        
                )
                BEGIN
        
                	DECLARE Customer_Cursor CURSOR FOR
                        (
                            SELECT AC_Statements_ID
                            FROM AC_Statements
                            WHERE AW_Period_Procedures_ID = @ProcedureID AND
                                  AW_User_Companies_ID = @CompanyID
                        )
                
                	OPEN Customer_Cursor
            
                    	FETCH NEXT FROM Customer_Cursor 
                    	INTO
                            @StatementID
                    	
                    	WHILE @@FETCH_STATUS = 0
                    	BEGIN
            
                            DELETE AC_Statement_Details
                            WHERE AC_Statements_ID = @StatementID
            
            
                            DELETE AC_Statements
                            WHERE AC_Statements_ID = @StatementID
            
            
                        	FETCH NEXT FROM Customer_Cursor 
                        	INTO
                                @StatementID
                
                    	END
                	
                	CLOSE Customer_Cursor
                
                	DEALLOCATE Customer_Cursor
            
            
                    DELETE AW_Period_Procedures
                    WHERE AW_Period_Procedures_ID = @ProcedureID AND
                          AW_User_Companies_ID = @CompanyID
        
                    SET @ReturnValue = 1
        
                END
        END

    ELSE
    IF @ProcedureTypeID = 6        -- Suppliers
        BEGIN
            IF EXISTS
                (
                    SELECT AW_Period_Procedures_ID
                    FROM AW_Period_Procedures
                    WHERE AW_Period_Procedures_ID = @ProcedureID AND
                          AW_User_Companies_ID = @CompanyID
        
                )
                BEGIN
        
                	DECLARE Supplier_Cursor CURSOR FOR
                        (
                            SELECT AO_Statements_ID
                            FROM AO_Statements
                            WHERE AW_Period_Procedures_ID = @ProcedureID AND
                                  AW_User_Companies_ID = @CompanyID
                        )
                
                	OPEN Supplier_Cursor
            
                    	FETCH NEXT FROM Supplier_Cursor 
                    	INTO
                            @StatementID
                    	
                    	WHILE @@FETCH_STATUS = 0
                    	BEGIN
            
                            DELETE AO_Statement_Details
                            WHERE AO_Statements_ID = @StatementID
            
            
                            DELETE AO_Statements
                            WHERE AO_Statements_ID = @StatementID
            
            
                        	FETCH NEXT FROM Supplier_Cursor 
                        	INTO
                                @StatementID
                
                    	END
                	
                	CLOSE Supplier_Cursor
                
                	DEALLOCATE Supplier_Cursor
            
            
                    DELETE AW_Period_Procedures
                    WHERE AW_Period_Procedures_ID = @ProcedureID AND
                          AW_User_Companies_ID = @CompanyID
        
                    SET @ReturnValue = 1
        
                END
        END



RETURN @ReturnValue










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AW_Delete_Marquee_Message
--Purpose       :Deletes a selected Marquee Message
--Functionality :
--Parameters    :
--Date          :2003/08/17
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Delete_Marquee_Message
    (
        @Option tinyint,
        @MessageID int
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF @Option = 0
        BEGIN
            IF EXISTS
                (
                    SELECT AW_Training_Messages_ID
                    FROM AW_Training_Messages
                    WHERE AW_Training_Messages_ID = @MessageID
        
                )
                BEGIN
                    DELETE AW_Training_Messages
                    WHERE AW_Training_Messages_ID = @MessageID
        
                    SET @ReturnValue = 1
        
                END
        END

    ELSE
    IF @Option = 1
        BEGIN
            IF EXISTS
                (
                    SELECT AW_Motivational_Messages_ID
                    FROM AW_Motivational_Messages
                    WHERE AW_Motivational_Messages_ID = @MessageID
        
                )
                BEGIN
                    DELETE AW_Motivational_Messages
                    WHERE AW_Motivational_Messages_ID = @MessageID
        
                    SET @ReturnValue = 1
        
                END
        END



RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AW_Delete_Year_End_Procedure
--Purpose       :DELETES GL YEAR-END PROCEDURE
--Functinality  :Deletes Statement and Details using a CURSOR
--Date          :2006/09/13
--Authors       :TB
--MODS          :
--2004.3.8      :26/04/08 - Added @UserID input parameter
--              :26/04/08 - Added INSERT INTO AW_Period_Procedures_Deleted LOG
--2004.4.8      :16/07/10 - Replaced DELETE the Year-End GL Transactions with
--              :           CURSOR procedure to UPDATE of GL Account Balance
--              :           GL Account Balance WAS NOT UPDATED BEFORE !!!!!!!!
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AW_Delete_Year_End_Procedure
	(
        @CompanyID int,
        @UserID int,
        @ProcedureID int
	)

AS

SET NOCOUNT ON

    DECLARE @Date DateTime,
            @MonthID int,
            @YearID int,
            @JournalID int,
            @StartPeriod varchar(6),
            @EndPeriod varchar(6),
            @MEDescription varchar(500),
            @MEMonthID tinyint,
            @MEYearID smallint,
            @MEMonthEndDate datetime,
            @MEYearEndDate datetime,
            @MEStockValuation money,
            @MEProcedureTypeID int,
            @GLTranID int,
            @GLAccountID int,
            @OrigGLAmount money,
            @NewGLAmount money,
            @ReturnValue int


    SET @ReturnValue = 0


    ------------------------------------------------------------
    --> INSERT INTO AW_Period_Procedures_Deleted LOG
    ------------------------------------------------------------
    SELECT @MEDescription = Description,
           @MEProcedureTypeID = Sys_AW_Period_Procedure_Types_ID,
           @MEMonthID = [Month],
           @MEYearID = [Year],
           @MEMonthEndDate = Month_End_Date,
           @MEYearEndDate = Year_End_Date,
           @MEStockValuation = Stock_Valuation
    FROM AW_Period_Procedures
    WHERE AW_Period_Procedures_ID = @ProcedureID AND
          AW_User_Companies_ID = @CompanyID

    ---------------------------------------

    INSERT AW_Period_Procedures_Deleted
        (
            AW_Period_Procedures_ID,
            Sys_AW_Period_Procedure_Types_ID,
            Description,
            Month_ID,
            Year_ID,
            Month_End_Date,
            Year_End_Date,
            Stock_Valuation,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
        )
    VALUES
        (
            @ProcedureID,
            @MEProcedureTypeID,
            @MEDescription,
            @MEMonthID,
            @MEYearID,
            @MEMonthEndDate,
            @MEYearEndDate,
            @MEStockValuation,
            getdate(),
            @UserID,
            @CompanyID
        )
    ------------------------------------------------------------

    
    SELECT @Date = Month_End_Date,
           @MonthID = ISNULL([Month], 0),
           @YearID = ISNULL([Year], 0)
    FROM AW_Period_Procedures
    WHERE AW_Period_Procedures_ID = @ProcedureID AND
          Sys_AW_Period_Procedure_Types_ID = 5


    IF @MonthID <> 0 AND @YearID <> 0
        BEGIN
            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID + 1, @YearID - 1)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

            ----------------------------------------------------------------


--             --> DELETE the Year-End Journal's GL Transactions !!! No UPDATE of GL Account Balance !!!
--             DELETE
--             FROM AB_GL_Transactions
--             WHERE Sys_AB_Transaction_Types_ID = 16 AND
--                   Slu_AW_Months_ID = @MonthID AND
--                   Slu_AW_Years_ID = @YearID


            --> Define a CURSOR for Income and Expense accounts
            DECLARE Accounts_Cursor CURSOR FOR
                    SELECT AB_GL_Transactions_ID,
                           AB_Accounts_ID,
                           ISNULL(AB_Transaction_Amount, 0)
                    FROM AB_GL_Transactions
                    WHERE Sys_AB_Transaction_Types_ID = 16 AND
                          Slu_AW_Months_ID = @MonthID AND
                          Slu_AW_Years_ID = @YearID
        
        	OPEN Accounts_Cursor
        
            	FETCH NEXT FROM Accounts_Cursor 
            	INTO
                    @GLTranID,
                    @GLAccountID,
                    @OrigGLAmount
            	
            	WHILE @@FETCH_STATUS = 0
                	BEGIN
                        SET @NewGLAmount = @OrigGLAmount * -1


                        --> Update AB_Accounts Balance
                    	UPDATE AB_Accounts 
                    	SET AB_Account_Balance = ISNULL(AB_Account_Balance, 0) + ISNULL(@NewGLAmount, 0)
                    	WHERE AB_Accounts_ID = @GLAccountID


                        --> DELETE the Year-End GL Transaction
                        DELETE
                        FROM AB_GL_Transactions
                        WHERE AB_GL_Transactions_ID = @GLTranID


                    	FETCH NEXT FROM Accounts_Cursor 
                    	INTO
                            @GLTranID,
                            @GLAccountID,
                            @OrigGLAmount
            
                	END
        	
            CLOSE Accounts_Cursor
            
            DEALLOCATE Accounts_Cursor


            ----------------------------------------------------------------
            
            --> RE-ENABLE Income & Expense Account Transactions
            UPDATE a
            SET a.Slu_AW_Active_ID = 1    -- 1 = Enabled
            FROM AB_GL_Transactions a
                INNER JOIN AB_Accounts b
                    ON a.AB_Accounts_ID = b.AB_Accounts_ID
                INNER join Sys_AB_Account_Categories c
                    ON b.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID
            WHERE c.Sys_AB_I1_ID = 1 AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= @EndPeriod AND
                  a.AW_User_Companies_ID = @CompanyID AND
                  a.Slu_AW_Active_ID = 2
            
            ----------------------------------------------------------------
            
            SELECT @JournalID = AB_Journals_ID
            FROM AB_Journals
            WHERE Journal_Date = @Date AND
                  Slu_AW_Months_ID = @MonthID AND
                  Slu_AW_Years_ID = @YearID
            
            
            DELETE
            FROM AB_Journal_Details
            WHERE AB_Journals_ID = @JournalID
            
            
            DELETE
            FROM AB_Journals
            WHERE AB_Journals_ID = @JournalID
            
            
            DELETE
            FROM AW_Period_Procedures
            WHERE AW_Period_Procedures_ID = @ProcedureID
            
            ----------------------------------------------------------------

            SET @ReturnValue = 1

        END


RETURN @ReturnValue












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AW_Formula
--Purpose       : 
--Functionality : 
--Parameters    :
--Date          :2002/02/18
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE     PROCEDURE sp_AW_Formula
    (
--        @TransactionType tinyint = 1,
        @FormulaID int = 0,
        @Formula varchar(1000) ='',
        @Description varchar(50) = '',
        @Fractions varchar (500) = '',
        @Expression varchar (500) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @NewFormulaID int

    IF EXISTS ( SELECT AW_Formulas_ID
                FROM AW_Formulas
                WHERE AW_Formulas_ID = @FormulaID )
        
        BEGIN
            UPDATE AW_Formulas 
            SET [Description] = @Description,
                 Formula = @Formula,
                 Fractions = @Fractions,
                 Expression = @Expression
            WHERE AW_Formulas_ID = @FormulaID
        END
    ELSE
        BEGIN

            INSERT AW_Formulas
                    (
                        [Description],
                        Formula,
                        Fractions,
                        Expression
                    )
                VALUES
                    (
                        @Description,
                        @Formula,
                        @Fractions,
                        @Expression
                    )

            SET @NewFormulaID = scope_identity()

            RETURN @NewFormulaID

        END

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_Generic_IF_EXISTS
--Purpose       :Generic VALIDATE IF VALUE IN ROW EXISTS
--Date          :2004/12/10
--Authors       :TB
--MODS          :06/03/05 - Added User Catalog validate if User Name EXISTS
--              :08/05/05 - Added Stock Receipts validate if Document_Number EXISTS
--2004.4.2      :08/05/05 - Added POS validate if Customer_Reference EXISTS
--2004.5.2      :09/07/11 - Added Option 5 Supplier Transaction Type = 9 validation
--V6.3	RL		:2017/09/27 - Added Option 6 Customer sales order validation
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Generic_IF_EXISTS]
    (
        @Option tinyint,
        @FieldValue varchar(1000),
        @ActorID int,
        @CompanyID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

    IF @Option = 1
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Product_Code(@FieldValue, @ActorID, @CompanyID)
        END

    ELSE
    IF @Option = 2
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_User_Name(@FieldValue)
        END

    ELSE
    IF @Option = 3
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Supplier_Invoice(@FieldValue, @ActorID, @CompanyID)
        END

    ELSE
    IF @Option = 4
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Customer_Reference(@FieldValue, @ActorID, @CompanyID)
        END

    ELSE
    IF @Option = 5
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Supplier_Refund(@FieldValue, @ActorID, @CompanyID)
        END
	ELSE
    IF @Option = 6
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_SO_Customer_Reference(@FieldValue, @ActorID, @CompanyID)
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Accounting_Period_From_Date
--Purpose       :Get the Accounting Period from a date
--Date          :2010/04/18
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AW_Get_Accounting_Period_From_Date
    (
        @Date datetime,
        @MonthID tinyint OUTPUT,
        @YearID smallint OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @Year smallint

    IF ISDATE(@Date) > 0
        BEGIN
            SET @MonthID = CONVERT(tinyint, DATEPART(mm, @Date))
            SET @Year  = CONVERT(smallint, DATEPART(yyyy, @Date))

            SELECT @YearID = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE Description = @Year
        END
    ELSE
        BEGIN
            SET @MonthID = CONVERT(tinyint, DATEPART(mm, getdate()))
            SET @Year  = CONVERT(smallint, DATEPART(yyyy, getdate()))

            SELECT @YearID = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE Description = @Year
        END



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_AW_Get_Company_Email_Address
--Date          :2004/07/27
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Company_Email_Address
   (        
        @CompanyID int,
        @EMail varchar(80) OUTPUT
    )

AS


SET NOCOUNT OFF

	SELECT @EMail = ISNULL(E_Mail, '')
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Company_Message_Settings
--Purpose       :Retrieve the message setting for a specific Company
--Notes         :Initializing column values in SELECT is REQUIRED to
--              :avoid the 'Invalid use of NULL' ADO error in SpSDBA
--Parameters    :
--Date          :2004/01/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------


CREATE              PROCEDURE sp_AW_Get_Company_Message_Settings
    (
    	@CompanyID int,
        @TakeOnPhase tinyint OUTPUT,
        @Contact1Email varchar(30) OUTPUT,
        @Contact1Active tinyint OUTPUT,
        @Contact2Email varchar(30) OUTPUT,
        @Contact2Active tinyint OUTPUT,
        @CRMID int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TakeOnPhase = ISNULL(Take_On_Phase, 1),
           @Contact1Email = ISNULL(Contact1_Email, ''),
           @Contact1Active = ISNULL(Contact1_Active, 0),
           @Contact2Email = ISNULL(Contact2_Email, ''),
           @Contact2Active = ISNULL(Contact2_Active, 0),
           @CRMID = ISNULL(User_CRM_ID, 1)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














----------------------------------------------------------------------------
--Description   :sp_AW_Get_Company_Name
--Date          :2006/03/11
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Company_Name
   (        
        @CompanyID int,
        @CompanyName varchar(80) OUTPUT
    )

AS


SET NOCOUNT OFF

	SELECT @CompanyName = ISNULL(Company_Name, '')
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AW_Get_DBServer_Date
--Purpose       :Return SERVER DATE as YYYY/MM/DD, SERVER TIME as HH:MM:SS
--Date          :2005/06/26
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_DBServer_Date
	(
        @Date char(10) OUTPUT,
        @Time char(8) OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @Year char(4),
            @Month char(2),
            @Day char(2),
            @Hour char(2),
            @Minute char(2),
            @Second char(2)


    SELECT @Year = CONVERT(char(4), DATEPART(yy, getdate())),
           @Month = CONVERT(char(2), DATEPART(mm, getdate())),
           @Day = CONVERT(char(2), DATEPART(dd, getdate())),
           @Hour = CONVERT(char(2), DATEPART(hh, getdate())),
           @Minute = CONVERT(char(2), DATEPART(mi, getdate())),
           @Second = CONVERT(char(2), DATEPART(ss, getdate()))


    IF LEN(@Month) = 1
        SET @Month = '0' + @Month

    IF LEN(@Day) = 1
        set @Day = '0' + @Day

    SET @Date = @Year + '/' + @Month + '/' + @Day


    IF LEN(@Hour) = 1
        SET @Hour = '0' + @Hour

    IF LEN(@Minute) = 1
        set @Minute = '0' + @Minute

    IF LEN(@Second) = 1
        set @Second = '0' + @Second

    SET @Time = @Hour + ':' + @Minute + ':' + @Second




SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Default_CompanyID
--Purpose       :Retrieve the ID for the first (default) Company
--Parameters    :
--Date          :2004/09/26
--Authors       :TB
--MODS          :
--2004.3.8      :03/05/08 - Added @CountryRegionCode and @CountryDateFormat
--2004.3.9      :04/07/08 - Added assign English(South Africa) regional defaults
--              :           if @CountryRegionCode or @CountryDateFormat is empty
--2004.4.5      :23/07/09 - Added @SpiralID
--              :04/08/09 - Moved @SpiralID to the LAST parameter position to prevent
--              :           "Country Region/Date Format error" when App/DB version not in sync
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AW_Get_Default_CompanyID
    (
        @CompanyID int OUTPUT,
        @CountryRegionCode varchar(250) OUTPUT,
        @CountryDateFormat varchar(250) OUTPUT,
        @SpiralID int OUTPUT
    )

AS

SET NOCOUNT ON

    SET @CompanyID = 0
    SET @CountryRegionCode = ''
    SET @CountryDateFormat = ''

    SELECT TOP 1 @CompanyID = AW_User_Companies_ID,
                 @SpiralID = ISNULL(Sp_Account_ID, 0)
    FROM AW_User_Companies
	ORDER BY AW_User_Companies_ID ASC


    SELECT @CountryRegionCode = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCountryRegionCode' AND
          Control_Index = 0


    SELECT @CountryDateFormat = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCountryDateFormat' AND
          Control_Index = 0


    IF @CountryRegionCode IS NULL OR @CountryRegionCode = ''
        BEGIN
            SET @CountryRegionCode = '27'
        END


    IF @CountryDateFormat IS NULL OR @CountryDateFormat = ''
        BEGIN
            SET @CountryDateFormat = 'yyyy/MM/dd'
        END



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








CREATE Procedure sp_AW_Get_Inflections 
(
	@SearchString varchar(100)
)
AS
	SELECT Alt1 as Inflection 
	FROM Lup_Inflections 
	WHERE Alt2 = @SearchString
 UNION 
	SELECT Alt2 
	FROM Lup_Inflections
	WHERE Alt1 = @SearchString







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AW_Get_Initial_Catalog_Version
--Purpose       :Return Initial Catalog Version
--Date          :2005/10/01
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_Initial_Catalog_Version
	(
        @Release varchar(10) OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT TOP 1 @Release = Release
    FROM AA_Release
    ORDER BY Date_Updated DESC


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description	:sp_AW_Get_Inventory_Valuation_Method
--Purpose       :Gets Inventory Valuation Method parameter
--Date			:2007/03/25
--Authors		:TB
--MODS          :
--2004.4.2      :25/10/08 - Added new Standard Cost Inventory Valuation method
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Get_Inventory_Valuation_Method
	(
        @CompanyID int,
        @Method smallint OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @ControlIndex smallint


    SELECT @ControlIndex = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


    SET @Method = @ControlIndex


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description	:sp_AW_Get_Is_DB_WAN_Application_Enabled
--Purpose       :Gets Module Enabled for WAN Applications parameter
--Date			:2010/06/26
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Get_Is_DB_WAN_Application_Enabled]
	(
        @CompanyID int,
        @ControlIndex smallint,
        @WANEnabled tinyint OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @ControlValue varchar(250)

    SET @WANEnabled = 0

    SELECT @ControlValue = RTRIM(LTRIM(ISNULL(Control_Value, '0')))
    FROM Sys_AW_Options
    WHERE Control_Type = 'CheckBox' AND
          Control_Name = 'chkEnterpriseEnabled' AND
          Control_Index = @ControlIndex AND
          AW_User_Companies_ID = @CompanyID


    SET @WANEnabled = CONVERT(tinyint, @ControlValue)


RETURN @WANEnabled

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AW_Get_Last_Day_End_Date
--Purpose       :Retrieves last 1 DayEnd Date
--Parameters    :
--Date          :2004/11/27
--Authors       :TB
--MODS          :
--2004.4.5      :19/06/09 - Replaced using AS_Transactions to using AS_Day_Ends
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_Last_Day_End_Date
	(
        @CompanyID int,
        @LastDayEndDate Datetime OUTPUT
	)

AS

SET NOCOUNT ON


-- 	SELECT DISTINCT TOP 1 @LastDayEndDate = Day_End
--     FROM AS_Transactions
--     WHERE AW_User_Companies_ID = @companyID AND
--             NOT Day_End IS NULL
--     ORDER BY Day_End DESC

	SELECT TOP 1 @LastDayEndDate = Day_End
    FROM AS_Day_Ends
    WHERE AW_User_Companies_ID = @companyID
    ORDER BY Day_End DESC


	IF @LastDayEndDate IS NULL 
        BEGIN
            SET @LastDayEndDate = '1899/12/31 23:59:59'
        END



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :sp_AW_Get_Last_Period_Procedure_Date
--Purpose       :Retrieves last 1 Period Procedure Date
--Parameters    :
--Date          :2004/11/19
--Authors       :TB
--MODS          :27/11/04 - Changed default @LastMonthEndDate value
--2004.4.3      :12/02/09 - Reworked with IF EXISTS struct because returns or sets
--              :           NOTHING is table EMPTY or no row found
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Get_Last_Period_Procedure_Date
	(
        @ProcedureTypeID int,
        @CompanyID int,
        @LastMonthEndDate Datetime OUTPUT
	)

AS

SET NOCOUNT ON


--     SELECT TOP 1 @LastMonthEndDate = Month_End_Date
--     FROM  AW_Period_Procedures
--     WHERE AW_User_Companies_ID = @CompanyID AND
--           Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
--     ORDER BY Month_End_Date DESC
-- 
-- 
--     IF @LastMonthEndDate IS NULL
--         BEGIN
--             SET @LastMonthEndDate = '1899/12/31 23:59:59'
--         END


    IF EXISTS
        (
            SELECT TOP 1 AW_Period_Procedures_ID
            FROM  AW_Period_Procedures
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID

        )
        BEGIN
            SELECT TOP 1 @LastMonthEndDate = Month_End_Date
            FROM  AW_Period_Procedures
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
            ORDER BY Month_End_Date DESC
        END
    ELSE
        BEGIN
            SET @LastMonthEndDate = '1899/12/31 23:59:59'
        END


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AW_Get_Last_Period_Procedure_ID
--Purpose       :Retrieves Top 1 last 1 AW_Period_Procedures_ID
--Parameters    :
--Date          :2005/04/30
--Authors       :TB
--MODS          :
--2004.4.3      :12/02/09 - Reworked with IF EXISTS struct because returns or sets
--              :           NOTHING is table EMPTY or no row found
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_Last_Period_Procedure_ID
	(
        @ProcedureTypeID int,
        @CompanyID int,
        @LastProcedureID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @LastProcedureID = 0

--     SELECT TOP 1 @LastProcedureID = AW_Period_Procedures_ID
--     FROM  AW_Period_Procedures
--     WHERE AW_User_Companies_ID = @CompanyID AND
--           Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
--     ORDER BY Month_End_Date DESC
-- 
-- 
--     IF @LastProcedureID IS NULL
--         BEGIN
--             SET @LastProcedureID = 0
--         END


    IF EXISTS
        (
            SELECT TOP 1 AW_Period_Procedures_ID
            FROM  AW_Period_Procedures
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID

        )
        BEGIN
            SELECT TOP 1 @LastProcedureID = AW_Period_Procedures_ID
            FROM  AW_Period_Procedures
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
            ORDER BY Month_End_Date DESC
        END
    ELSE
        BEGIN
            SET @LastProcedureID = 0
        END



SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AW_Get_Last_Period_Procedure_Period
--Purpose       :Retrieves last 1 Period Procedure Accounting Period
--Parameters    :
--Date          :2004/07/23
--Authors       :TB
--Version       :1.0.0
--MODS          :19/11/04 - Added ORDER BY DESCENDING clause
--2004.3.4      :08/03/07 - Added conditional SELECT by @ProcedureTypeID
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Get_Last_Period_Procedure_Period
	(
        @ProcedureTypeID int,
        @CompanyID int,
        @MonthID tinyint OUTPUT,
        @YearID smallint OUTPUT
	)

AS

SET NOCOUNT ON


    IF @ProcedureTypeID = 1        --Customers Period Procedures
        BEGIN
            SELECT TOP 1 @MonthID = [Month],
                         @YearID = [Year]
            FROM  AW_Period_Procedures
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
                  Month_End_Date < getdate()
            ORDER BY Month_End_Date DESC
        END

    ELSE                            --ALL other Period Procedures
        BEGIN
            SELECT TOP 1 @MonthID = [Month],
                         @YearID = [Year]
            FROM  AW_Period_Procedures
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
            ORDER BY dbo.fn_AB_Get_Ending_GL_Period([Month], [Year]) DESC
        END



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AW_Get_Last_Period_Procedure_Year_End_Date
--Purpose       :Retrieves last Year End Period Procedure Date
--Parameters    :
--Date          :2004/11/27
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Last_Period_Procedure_Year_End_Date
	(
        @ProcedureTypeID int,
        @CompanyID int,
        @LastYearEndDate Datetime OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @YearID int,
            @MonthID int,
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @Year smallint


        SELECT @MonthID = DATEPART(m, getdate()),
               @Year = DATEPART(yy, getdate())
    
        SELECT @YearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        WHERE [Description] = CONVERT(varchar(10), @Year)

        EXEC sp_AB_Get_Fiscal_Span
                            @CompanyID,
                            @YearEndMonthID OUTPUT,
                            @StartMonthID OUTPUT,
                            @StartYearID OUTPUT,
                            @MonthID OUTPUT,
                            @YearID OUTPUT

        SELECT TOP 1 @LastYearEndDate = Month_End_Date
        FROM AW_Period_Procedures
        WHERE AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
             [Month] = @YearEndMonthID AND
             [Year] = @StartYearID


        IF @LastYearEndDate IS NULL
            BEGIN
                SET @LastYearEndDate = '1899/12/31 23:59:59'
            END



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AW_Get_Last_Period_Procedure_Year_End_ID
--Purpose       :Gets last Year End Period Procedure ID for a specific Period
--Parameters    :Year-End = @ProcedureTypeID = 5
--Date          :2005/03/05
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Last_Period_Procedure_Year_End_ID
	(
        @ProcedureTypeID int,
        @MonthID tinyint,
        @YearID int,
        @CompanyID int,
        @LastYearEndID int OUTPUT,
        @LastYearEndDate datetime OUTPUT
        
	)

AS

SET NOCOUNT ON

        SELECT TOP 1 @LastYearEndID = AW_Period_Procedures_ID,
                     @LastYearEndDate = Year_End_Date
        FROM AW_Period_Procedures
        WHERE AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
              [Month] = @MonthID AND
              [Year] = @YearID
        ORDER BY Year_End_Date DESC



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Local_Franchise
--Purpose       :Get the Franchise Number from User Companies
--Date          :2004/03/02
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Get_Local_Franchise_Number
    (
        @CompanyID int,
        @FranchiseNo varchar(20) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @FranchiseNo = RTRIM(LTRIM(ISNULL(Network_Identity_Number, '')))
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Local_Host_Network_Identifier
--Purpose       :Get the Local Host connection Network_Identifier from AW_Remote_Access_ID
--Date          :2003/10/13
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Local_Host_Network_Identifier
    (
        @CompanyID int,
        @RemoteID int,
        @NetworkIdentifier varchar(20) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @NetworkIdentifier = ISNULL(Network_Identity, '')
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          AW_Remote_Access_ID = @RemoteID



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Local_Host_Node_Name
--Purpose       :Get the Local Host connection Node_Name
--Date          :2004/01/13
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Get_Local_Host_Node_Name
    (
        @CompanyID int,
        @RemoteID int OUTPUT,
        @NodeName varchar(30) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT TOP 1 @RemoteID = AW_Remote_Access_ID,
                 @NodeName = ISNULL(NodeName, '')
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          Default_Connection = 1


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Local_Host_Remote_Access_ID
--Purpose       :Get the Local Host connection AW_Remote_Access_ID (one only)
--Date          :2003/10/13
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Local_Host_Remote_Access_ID
    (
        @CompanyID int,
        @RemoteID int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          Default_Connection = 1



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Message
--Purpose       :Retrieve the message for a specific @MessageID
--              :
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Message
    (
        @MessageID int,
    	@Message varchar(500) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @Message = [Description]
    FROM AW_Messages
    WHERE AW_Messages_ID = @MessageID


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Message_Severity_Setting
--Purpose       :Retrieve the Severity setting for a specific Message
--              :
--Parameters    :
--Date          :2004/01/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Get_Message_Severity_Setting
    (
    	@MessageID int,
        @SeverityID tinyint OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @SeverityID = ISNULL(Sys_AC_Severity_Levels_ID, 1)
    FROM AW_Messages
    WHERE AW_Messages_ID = @MessageID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :sp_AW_Get_Module
--Purpose       :Fetch Specific Module
--              :
--Parameters    :
--Date          :2003/07/24
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Module
    (
        @ModuleID int,
        @ModuleName varchar(50) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @ModuleName = ISNULL([Description], '')
    FROM Sys_AW_Modules
    WHERE Sys_AW_Modules_ID = @ModuleID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Motivational_Count
--Purpose       :
--Date          :2003/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :09/08/04 - Added WHERE clause select only if message is active
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Motivational_Count

AS

SET NOCOUNT ON


    DECLARE @RowCount int

    SELECT @RowCount = count(*)
    FROM AW_Motivational_Messages
    WHERE Slu_AW_Active_ID = 1

    RETURN @RowCount


SET NOCOUNT OFF























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Motivational_Message
--Purpose       :
--Date          :2003/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Motivational_Message
    (
        @MessageID int,
        @Message varchar(250) OUTPUT,
        @Source varchar(100) OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @Message = ISNULL(Message, ''),
           @Source = ISNULL(Source, '')
    FROM AW_Motivational_Messages
    WHERE AW_Motivational_Messages_ID = @MessageID AND
          Slu_AW_Active_ID = 1













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Next_SCM_File_Number
--Purpose       :Inserts the next SCM File number
--Date          :2009/05/28
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Get_Next_SCM_File_Number
    (
        @CompanyID int,
        @FileNo int OUTPUT,
        @LastDate datetime OUTPUT
    )

AS


    SELECT @FileNo = ISNULL(Sp_Sales_File_Count, 0),
           @LastDate = ISNULL(Sp_Sales_File_Date, CONVERT(datetime, DATEADD(dd, 0, ROUND(CONVERT(float, GETDATE()), 0, 1))))
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Next_Transaction_Number
--Purpose       :Inserts the next transaction number
--Date          :2002/01/07
--Authors       :TB
--Version       :1.0.0
--MODS          :25/11/04 - Renamed parameters
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Next_Transaction_Number
    (
        @TranTypeID int, 
        @CompanyID int,
        @TranNo varchar(15) OUTPUT
    )

AS

    DECLARE @Num int

    SELECT @Num = ISNULL(Last_Number, 0) 
    FROM Sys_AW_Transaction_Numbers
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Transaction_Types_ID = @TranTypeID
    
    
    UPDATE Sys_AW_Transaction_Numbers
    SET Last_Number = @Num + 1 
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Transaction_Types_ID = @TranTypeID


    SET @TranNo = CONVERT(varchar(15), @Num + 1) 









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AW_Get_Period_Procedure_Date
--Purpose       :Returns Period Procedures Month_End_Date from @ProcedureID
--              :for Customer Statement E-mails
--Date          :2006/03/11
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Period_Procedure_Date
	(
        @ProcedureID int,
        @ProcedureDate datetime OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @ProcedureDate = Month_End_Date
    FROM AW_Period_Procedures 
    WHERE AW_Period_Procedures_ID = @ProcedureID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AW_Get_Period_Procedure_Period
--Purpose       :Retrieves Period Procedure Accounting Period from ProcedureID
--Date          :2006/03/26
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Period_Procedure_Period
	(
        @ProcedureID int,
        @CompanyID int,
        @MonthID tinyint OUTPUT,
        @YearID smallint OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @MonthID = [Month],
           @YearID = [Year]
    FROM  AW_Period_Procedures
    WHERE AW_User_Companies_ID = @CompanyID AND
          AW_Period_Procedures_ID = @ProcedureID


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















------------------------------------------------------------------------------
--Description   :sp_AW_Get_Prev_Period_Procedure_Date
--Purpose       :Retrieves last 1 + 1 Period Procedure Date
--Parameters    :
--Date          :2010/04/14
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_AW_Get_Prev_Period_Procedure_Date
	(
        @ProcedureTypeID int,
        @CompanyID int,
        @LastMonthEndDate Datetime OUTPUT,
        @LastMonth varchar(10) OUTPUT,
        @PriorMonthEndDate Datetime OUTPUT,
        @PriorMonth varchar(10) OUTPUT,
        @PrevMonthEndDate Datetime OUTPUT,
        @PrevMonth varchar(10) OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @MonthDesc varchar(10),
            @YearDesc varchar(10)


    SET @MonthDesc = ''
    SEt @YearDesc = ''


    SELECT TOP 1 @LastMonthEndDate = p.Month_End_Date,
                 @MonthDesc = m.Description,
                 @YearDesc = CONVERT(varchar(10), y.Description)
    FROM  AW_Period_Procedures p
        INNER JOIN Slu_AW_Months m
            ON m.Slu_AW_Months_ID = p.[Month]
        INNER JOIN Slu_AW_Years y
            ON y.Slu_AW_Years_ID = p.[Year]
    WHERE p.AW_User_Companies_ID = @CompanyID AND
          p.Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
    ORDER BY p.Month_End_Date DESC

    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @LastMonthEndDate IS NULL 
        BEGIN
    		SET @LastMonthEndDate = '1899/12/31 23:59:59'
        END

    SET @LastMonth = RTRIM(LTRIM(@MonthDesc)) + ' ' + RTRIM(LTRIM(@YearDesc))


    SET @MonthDesc = ''
    SEt @YearDesc = ''


    --> Get the date of the PRIOR CUSTOMER MONTH-END done
	SELECT TOP 1 @PriorMonthEndDate = p.Month_End_Date,
                 @MonthDesc = m.Description,
                 @YearDesc = CONVERT(varchar(10), y.Description)
	FROM AW_Period_Procedures p
        INNER JOIN Slu_AW_Months m
            ON m.Slu_AW_Months_ID = p.[Month]
        INNER JOIN Slu_AW_Years y
            ON y.Slu_AW_Years_ID = p.[Year]
	WHERE p.AW_User_Companies_ID = @CompanyID AND
          p.Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
          p.Month_End_Date <> @LastMonthEndDate
	ORDER BY p.Month_End_Date DESC

    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PriorMonthEndDate IS NULL 
        BEGIN
    		SET @PriorMonthEndDate = '1899/12/31 23:59:59'
        END

    SET @PriorMonth = RTRIM(LTRIM(@MonthDesc)) + ' ' + RTRIM(LTRIM(@YearDesc))


    SET @MonthDesc = ''
    SEt @YearDesc = ''


    --> Get the date of the PREV CUSTOMER MONTH-END done
	SELECT TOP 1 @PrevMonthEndDate = p.Month_End_Date,
                 @MonthDesc = m.Description,
                 @YearDesc = CONVERT(varchar(10), y.Description)
	FROM AW_Period_Procedures p
        INNER JOIN Slu_AW_Months m
            ON m.Slu_AW_Months_ID = p.[Month]
        INNER JOIN Slu_AW_Years y
            ON y.Slu_AW_Years_ID = p.[Year]
	WHERE p.AW_User_Companies_ID = @CompanyID AND
          p.Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
          p.Month_End_Date <> @LastMonthEndDate AND
          p.Month_End_Date <> @PriorMonthEndDate
	ORDER BY p.Month_End_Date DESC

    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PrevMonthEndDate IS NULL 
        BEGIN
    		SET @PrevMonthEndDate = '1899/12/31 23:59:59'
        END

    SET @PrevMonth = RTRIM(LTRIM(@MonthDesc)) + ' ' + RTRIM(LTRIM(@YearDesc))



SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_AccessID
--Purpose       :Get AW_Remote_Access_ID from @NetworkIdentity
--Date          :2003/10/12
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_Remote_Access_ID
    (
        @CompanyID int,
        @NetworkIdentity varchar(20),
        @RemoteID int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
    FROM AW_Remote_Access
    WHERE AW_User_Companies_ID = @CompanyID AND
          Network_Identity = @NetworkIdentity



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description   :sp_AW_Get_SP_Account_ID
--Date          :2009/03/31
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_SP_Account_ID
   (        
        @CompanyID int,
        @AccountID int OUTPUT
    )

AS


SET NOCOUNT OFF

	SELECT @AccountID = ISNULL(Sp_Account_ID, 0)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















----------------------------------------------------------------------------
--Description   :sp_AW_Get_SP_Web_Password
--Date          :2010/01/16
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Get_SP_Web_Password
   (        
        @CompanyID int,
        @WebPW varchar(20) OUTPUT
    )

AS


SET NOCOUNT OFF

	SELECT @WebPW = ISNULL(Sp_Web_Password, '')
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-----------------------------------------------------------------------------------
--Description   :sp_AW_Get_Single_Value
--Purpose       :Generic SQL query
--Date          :2004/07/06
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------------


CREATE           Procedure sp_AW_Get_SQL
    (
        @FieldName varchar(4000),
        @TableName varchar(1000),
        @WhereField varchar(2000),
        @WhereValue varchar(1000)
    )

AS

SET NOCOUNT ON

    DECLARE @SQL varchar(8000)

    SET @SQL = ' SELECT ' + @FieldName +
               ' FROM ' + @TableName +
               ' WHERE ' + @WhereField + ' = ''' + @WhereValue + ''''



    EXEC (@SQL)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-----------------------------------------------------------------------------
--Description   :sp_AW_Get_SQL_Server_Properties
--Purpose       :Returns version, level, and edition of installed SQL Server
--Date          :2011/05/20
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_SQL_Server_Properties
	(
        @Version varchar(100) OUTPUT,
        @Level varchar(100) OUTPUT,
        @Edition varchar(100) OUTPUT
	)

AS

SET NOCOUNT ON

SELECT @Version = CONVERT(varchar(100), SERVERPROPERTY('productversion')),
       @Level = CONVERT(varchar(100), SERVERPROPERTY ('productlevel')),
       @Edition = CONVERT(varchar(100), SERVERPROPERTY ('edition'))










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-----------------------------------------------------------------------------------
--Description   :sp_AW_Get_Single_Value
--Purpose       :Generic SQL query
--Date          :2004/07/06
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------------


CREATE            Procedure sp_AW_Get_Single_Value
    (
        @FieldName varchar(4000),
        @TableName varchar(1000),
        @WhereField varchar(2000),
        @WhereValue varchar(1000)
    )

AS

SET NOCOUNT ON

    DECLARE @SQL varchar(8000)

    SET @SQL = ' SELECT ' + @FieldName +
               ' FROM ' + @TableName +
               ' WHERE ' + @WhereField + ' = ''' + @WhereValue + ''''


print @SQL


EXEC (@SQL)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AW_Get_TakeOnPhase_Setting
--Purpose       :Retrieve the TakeOnPhase setting for a specific Company
--              :Also used to Block Credit Manager Messages
--Parameters    :
--Date          :2004/01/04
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_TakeOnPhase_Setting
    (
    	@CompanyID int,
        @TakeOnPhase tinyint OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TakeOnPhase = ISNULL(Take_On_Phase, 1)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Tax_Rate
--Purpose       :Get the Tax Rate for the selected Tax Code
--Date          :2004/08/07
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Tax_Rate
    (
        @TaxCode char(1),
        @TaxRate decimal(5,2) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0
    SET @TaxRate = 0

    IF EXISTS
        (
            SELECT Tax_Rate
            FROM Sys_AW_Tax_Codes
            WHERE Tax_Code = @TaxCode
        )
        BEGIN
            SELECT @TaxRate = ISNULL(Tax_Rate, 0)
            FROM Sys_AW_Tax_Codes
            WHERE Tax_Code = @TaxCode

            SET @ReturnValue = 1

        END


RETURN @ReturnValue

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Tax_Rate_From_ID
--Purpose       :Get the Tax Rate from Sys_AW_Tax_Codes_ID
--Date          :2009/05/10
--Authors       :TB
--MODS          : 
---------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_Tax_Rate_From_ID
    (
        @TaxCodeID tinyint,
        @TaxRate decimal(5,2) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0
    SET @TaxRate = 0

    IF EXISTS
        (
            SELECT Sys_AW_Tax_Codes_ID
            FROM Sys_AW_Tax_Codes
            WHERE Sys_AW_Tax_Codes_ID = @TaxCodeID
        )
        BEGIN
            SELECT @TaxRate = ISNULL(Tax_Rate, 0)
            FROM Sys_AW_Tax_Codes
            WHERE Sys_AW_Tax_Codes_ID = @TaxCodeID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description   :sp_AW_Get_Terms_Conditions
--Date          :2011/06/20
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Get_Terms_Conditions
    (        
        @TermsID int
    )

AS


SET NOCOUNT OFF

	SELECT Sys_AW_Terms_Conditions_ID AS [ID],
           Terms
    FROM Sys_AW_Terms_Conditions
    WHERE Sys_AW_Terms_Conditions_ID = @TermsID


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















---------------------------------------------------------------------------------
--Description   :sp_AW_Get_Trade_Style
--Purpose       :Get the Trading Name for E-Mail Marketing
--Date          :2004/07/16
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AW_Get_Trade_Style
    (
        @CompanyID int,
        @TradeName varchar(50) OUTPUT,
        @Email varchar(80) OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @TradeName = ISNULL(Company_Trading_Name, ''),
           @Email = ISNULL(E_Mail, '')
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    IF RTRIM(LTRIM(@TradeName)) = ''
        BEGIN
            SELECT @TradeName = ISNULL(Company_Name, ''),
                   @Email = ISNULL(E_Mail, '')
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID
        END


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Training_Count
--Purpose       :
--Date          :2003/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :09/08/04 - Added WHERE clause select only if message is active
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Training_Count

AS

SET NOCOUNT ON


    DECLARE @RowCount int

    SELECT @RowCount = count(*)
    FROM AW_Training_Messages
    WHERE Slu_AW_Active_ID = 1

    RETURN @RowCount


SET NOCOUNT OFF























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Training_Message
--Purpose       :
--Date          :2003/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Get_Training_Message
    (
        @MessageID int,
        @Message varchar(250) OUTPUT,
        @Source varchar(100) OUTPUT
	)

AS

SET NOCOUNT ON

    SELECT @Message = ISNULL(Message, ''),
           @Source = ISNULL(Source, '')
    FROM AW_Training_Messages
    WHERE AW_Training_Messages_ID = @MessageID AND
          Slu_AW_Active_ID = 1













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description	:sp_AW_Get_Transaction_Allocation_Status
--Purpose       :Returns Customer/Supplier Transaction allocation status
--Date			:2008/11/03
--Authors		:TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Get_Transaction_Allocation_Status
	(
        @TableID tinyint,
        @TranID int,
        @Amount money,
        @AllocStatus tinyint OUTPUT
    )

AS

    SELECT @AllocStatus = dbo.fn_AW_Get_Allocation_Status(@TableID, @TranID, @Amount)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AW_Get_User_Email_Address
--Date          :2004/06/22
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Get_User_Email_Address
   (        
        @UserID int,
        @UserEMail varchar(50) OUTPUT
    )

AS


SET NOCOUNT OFF

	SELECT @UserEMail = ISNULL(User_Email, '')
    FROM AW_Users
    WHERE AW_Users_ID = @UserID

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AW_Get_Value_From_Generic_Table
--Purpose       :Retrieves data with DATA DEFINITION variables
--              :
--Parameters    :
--Date          :2003/04/16
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE           Procedure sp_AW_Get_Value_From_Generic_Table
    (
        @FieldName varchar(100),
        @TableName varchar(100),
        @WhereField varchar(100),
        @WhereValue varchar(100)
    )

AS

SET NOCOUNT ON

    DECLARE @SQL varchar(1000)

    SET @SQL = 'SELECT ' + @FieldName + ' FROM ' + @TableName + ' WHERE ' +
                           @WhereField + ' = ''' + @WhereValue + ''''

PRINT @SQL


EXEC (@SQL)














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











----------------------------------------------------------------------------
--Description   :sp_AW_Insert_Apps_Per_Role
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/17
--Authors       :TB
--Version       :1.0.0
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Insert_Apps_Per_Role
    (
    	@User_Role_ID int,
    	@AW_Applications_ID smallint,
    	@Company_ID int,
    	@User_ID int
    )

AS

SET NOCOUNT ON

	INSERT INTO AW_Applications_Per_Role
        (
            AW_Roles_ID,
            Sys_AW_Applications_ID,
            AW_User_Companies_ID,
            User_ID
        )
	VALUES
        (
            @User_Role_ID,
            @AW_Applications_ID,
            @Company_ID,
            @User_ID
        )










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























-------------------------------------------------------------------------------
--Description   :sp_AW_Insert_Or_Update_Terms
--Purpose       :Insert or Update Terms of Sale
--Date          :2011/06/20
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Insert_Or_Update_Terms
    (
        @TermsID int,
        @Terms varchar(8000),
    	@UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @RetCode int


    SET @RetCode = 0

    IF @TermsID > 0
        BEGIN
            UPDATE Sys_AW_Terms_Conditions
            SET Terms = @Terms,
                User_ID = @UserID
            WHERE Sys_AW_Terms_Conditions_ID = @TermsID

            SET @RetCode = 1
        END
    ELSE
        BEGIN
            INSERT Sys_AW_Terms_Conditions
                (
                    Terms,
                    User_ID
                )
            VALUES
                (
                    @Terms,
                    @UserID
                )

            SET @RetCode = 2
        END

RETURN @RetCode















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











----------------------------------------------------------------------------
--Description   :sp_AW_Insert_Remote_Access
--Purpose       :Inserts an empty Node into the Remote Access Catalog
--Date          :2003/09/15
--Authors       :TB
--Version       :2004
--MODS          :
----------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Insert_Remote_Access
    (
        @UserID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

    INSERT AW_Remote_Access
        (
            NodeName,
            [User_ID],
            AW_User_Companies_ID
        )

    VALUES
        (
            'New Remote Node',
            @UserID,
            @CompanyID
        )


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














----------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Access
--Purpose       :Inserts one Site Manager
--Date          :2008/10/19
--Authors       :TB
--MODS          :
--2004.4.3      :13/02/09 - Modified @DataServName increased size from 20 to 50
----------------------------------------------------------------------------

CREATE                      PROCEDURE sp_AW_Insert_Site_Manager
    (
        @CompanyID int,
        @NodeName varchar(30),
        @Network_Identity varchar(20),
        @WinUserName varchar(20),
        @WinPassword varchar(20),
        @Trusted_Connection tinyint,
        @DataServName varchar(50),
        @DataServIP1 varchar(200),
        @DataServIP2 varchar(3),
        @DataServIP3 varchar(3),
        @DataServIP4 varchar(3),
        @DBUserName varchar(20),
        @DBPassword varchar(20),
        @DBCatalog varchar(30),
        @WebServName varchar(20),
        @WebServIP1 varchar(200),
        @WebServIP2 varchar(3),
        @WebServIP3 varchar(3),
        @WebServIP4 varchar(3),
        @WebSiteURL varchar(30),
        @DSNName varchar(20),
        @Default_Connection tinyint,
        @Port varchar(4),
        @WebServURL varchar(30),
        @intCountryID smallint,
        @Area_Code varchar(6),
        @Modem_Tel_No varchar(10),
        @Email varchar(30),
        @SQLQuery varchar(2000),
        @Billing_Name varchar(50),
        @Billing_Address1 varchar(40),
        @Billing_Address2 varchar(40),
        @Billing_Address3 varchar(40),
        @Billing_Post_Code varchar(10),
        @Billing_TelNo varchar(16),
        @Billing_FaxNo varchar(16),
        @Billing_VATNo varchar(16),
        @Billing_RegNo varchar(16),
        @Delivery_Name varchar(50),
        @Delivery_Address1 varchar(40),
        @Delivery_Address2 varchar(40),
        @Delivery_Address3 varchar(40),
        @Delivery_Post_Code varchar(10)
    )

AS

SET NOCOUNT ON

	INSERT AW_Remote_Access
        (
            NodeName,
            Network_Identity,
            WinUserName,
            WinPassword,
            Trusted_Connection,
            DataServName,
            DataServIP1,
            DataServIP2,
            DataServIP3,
            DataServIP4,
            DBUserName,
            DBPassword,
            DBCatalog,
            WebServName,
            WebServIP1,
            WebServIP2,
            WebServIP3,
            WebServIP4,
            WebSiteURL,
            DSNName,
            Default_Connection,
            Port,
            WebServURL,
            Slu_AW_Countries_ID,
            Area_Code,
            Modem_Tel_No,
            Email,
            SQLQuery,
            Billing_Name,
            Billing_Address1,
            Billing_Address2,
            Billing_Address3,
            Billing_Post_Code,
            Billing_TelNo,
            Billing_FaxNo,
            Billing_VATNo,
            Billing_RegNo,
            Delivery_Name,
            Delivery_Address1,
            Delivery_Address2,
            Delivery_Address3,
            Delivery_Post_Code,
            AW_User_Companies_ID
        )
    VALUES
        (
            @NodeName,
            @Network_Identity,
            @WinUserName,
            @WinPassword,
            @Trusted_Connection,
            @DataServName,
            @DataServIP1,
            @DataServIP2,
            @DataServIP3,
            @DataServIP4,
            @DBUserName,
            @DBPassword,
            @DBCatalog,
            @WebServName,
            @WebServIP1,
            @WebServIP2,
            @WebServIP3,
            @WebServIP4,
            @WebSiteURL,
            @DSNName,
            @Default_Connection,
            @Port,
            @WebServURL,
            @intCountryID,
            @Area_Code,
            @Modem_Tel_No,
            @Email,
            @SQLQuery,
            @Billing_Name,
            @Billing_Address1,
            @Billing_Address2,
            @Billing_Address3,
            @Billing_Post_Code,
            @Billing_TelNo,
            @Billing_FaxNo,
            @Billing_VATNo,
            @Billing_RegNo,
            @Delivery_Name,
            @Delivery_Address1,
            @Delivery_Address2,
            @Delivery_Address3,
            @Delivery_Post_Code,
            @CompanyID
        )    











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AW_Insert_Users_Per_Role
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE      PROCEDURE sp_AW_Insert_Users_Per_Role
    (
    	@User_Role_ID smallint,
    	@AW_Users_ID int,
    	@Company_ID int,
    	@User_ID int
    )

AS

SET NOCOUNT ON

	INSERT INTO AW_Users_Per_Role
        (
    		AW_Roles_ID,
    		AW_Users_ID,
    		AW_User_Companies_ID,
    		[User_ID]
        )

	VALUES
        (
            @User_Role_ID,
            @AW_Users_ID,
            @Company_ID,
            @User_ID
        )

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AW_Lookup_Editor_Data_Select
--Purpose       :Selects Lookup table data for Lookup Editor
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Mods          :18/06/02 - Added Slu_AB_Account_Categories definition fields
--              :11/07/02 - Added Sys_AW_Tax_Codes
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table and its new columns
--              :09/07/03 - Added Sys_AW_Payment_Methods table (Autowiel !!)
--              :08/01/04 - Added System Lookups for Credit Manager
--              :29/02/04 - Added Lup_AS_CBilling_Types
--              :29/02/04 - Added Lup_AP_Fail_Reasons
--              :01/03/04 - Removed Date_Captured & User_ID from Inflections
--              :04/03/04 - Added Server, User and Password to Lup_AS_CBilling_Types
--              :09/03/04 - Added Lup_AP_Claim_Codes
--              :15/07/04 - Added Lup_AC_Customer_Groups
--2004.2.4      :31/05/05 - Added Terms_Value AS [Terms Days] in Slu_AW_Credit_Terms
--2004.2.7      :19/03/06 - Added Slu_AW_SMS_Messages
--2004.2.10     :19/03/06 - Added ORDER BY in @Choice = 'Sys_AB_Account_Categories'
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories
--2004.3.7      :23/07/07 - Added Lup_AC_Markup_Categories and Lup_AP_Markup_Groups
--              :23/09/07 - Added Lup_AB_Account_Groups
--              :28/09/07 - Added Lup_AB_Account_Divisions
--2004.3.8      :24/01/08 - Added Lup_AO_Supplier_Groups and Lup_AO_Supplier_Types
--              :04/05/08 - Added ORDER BY [Description] to most Lookups
--              :10/05/08 - Removed Min GP% field from Lup_AP_Product_Departments
--2004.3.9      :22/06/08 - Added Slu_AW_Shipping_Rates
--2004.4.0      :09/07/08 - Added Slu_AS_Volume_Discounts
--2004.4.1      :08/09/08 - Added Sys_AB_B2, Sys_AB_B3, Sys_AB_I3, Sys_AB_I4
--2004.4.3      :08/03/09 - Re-Indented ALL Lookups
--              :17/03/09 - Added Slu_AC_Statement_Messages
--2004.4.5      :29/05/09 - Added AW_Messages for Credit Manager Messages
--              :16/06/09 - Added Lup_AS_Procurement_Providers for Procurement Providers
--2004.4.8      :19/02/10 - Added Lup_AB_Transaction_Type_Maps for Bank Transaction Types Mapping
--2004.4.9      :07/09/10 - Added Lup_AP_Shipping_Agents for Shipping Agents
--2004.5.1      :18/05/11 - Added Lup_AF_Instructions for Factory Casing Tracking system
--2004.5.7-RGL  :2012-09-17 - Added Country_Dialing_Code column to Slu_AW_Countries
--2004.5.7-RGL  :2012-09-17 - Added Slu_AW_Countries_Mobile
--2004.5.7-RGL  :2012-10-12 - Added Slu_AW_Weight
--2015.6.2-RGL  :2015-11-12 - Added Lup_AP_Product_Bins
--2015.6.2-RGL  :2016-06-24 - Added Lup_AB_Account_Departments
------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AW_Lookup_Editor_Data_Select]
	(
		@Choice varchar(50),
		@CompanyID int
	)
AS
    IF @Choice = 'Sys_AB_Account_Categories'
    	SELECT Sys_AB_Account_Categories_ID as [ID],
               Description as [Description],
               Sys_AB_B1_ID as [BS1],
               Sys_AB_B2_ID as [BS2],
               Sys_AB_B3_ID as [BS3],
               Sys_AB_I1_ID as [IS1],
               Sys_AB_I2_ID as [IS2],
               Sys_AB_I3_ID as [IS3],
               Sys_AB_I4_ID as [IS4],
               Sys_AB_Account_Types_ID as [Type],
               Notes
    	FROM Sys_AB_Account_Categories
        ORDER BY Sys_AB_B1_ID,
                 Sys_AB_B2_ID,
                 Sys_AB_B3_ID,
                 Sys_AB_I1_ID,
                 Sys_AB_I2_ID,
                 Sys_AB_I3_ID,
                 Sys_AB_I4_ID
    ELSE
    IF @Choice = 'Slu_AW_Active'
    	SELECT Slu_AW_Active_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User] 
    	FROM Slu_AW_Active
    ELSE
    IF @Choice = 'Lup_AC_Asset_Types'
    	SELECT Lup_AC_Asset_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Asset_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Banks'
    	SELECT Slu_AW_Banks_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Banks
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Branch_Codes'
    	SELECT Lup_AW_Branch_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Branch_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AS_Card_Institutions'
    	SELECT Slu_AS_Card_Institutions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Card_Institutions
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Cashiers'
    	SELECT Lup_AS_Cashiers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Cashiers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Commission_Categories'
    	SELECT Lup_AS_Commission_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Commission_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Commission_Groups'
    	SELECT Lup_AP_Commission_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Commission_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Cost_Centers'
    	SELECT Lup_AB_Cost_Centers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Cost_Centers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Countries'
    	SELECT Slu_AW_Countries_ID as [ID],
               Description as [Description],
               Country_Code2 as [Country Code2],
               Country_Code3 as [Country Code3],
               Country_Number as [Country Number],
               Country_Dialing_Code as [Country Dialing Code],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Countries
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Credit_Terms'
    	SELECT Slu_AW_Credit_Terms_ID as [ID],
               Description as [Description],
               Terms_Value AS [Terms Days],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Credit_Terms
    ELSE
    IF @Choice = 'Slu_AW_Currencies'
    	SELECT Slu_AW_Currencies_ID as [ID],
               Description as [Description],
               Exchange_Rate as [Exchange Rate],
               Rate_Date as [Rate Date],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Currencies
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Types'
    	SELECT Lup_AC_Customer_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Discount_Categories'
    	SELECT Lup_AC_Discount_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Discount_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Discount_Groups'
    	SELECT Lup_AP_Discount_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Discount_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Inflections'
    	SELECT Slu_AW_Inflections_ID as [ID],
               Alternate1 as [Alternate1],
               Alternate2 as [Alternate2],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Inflections
        ORDER BY [Alternate1]
    ELSE
    IF @Choice = 'Slu_AW_Languages'
    	SELECT Slu_AW_Languages_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
        FROM Slu_AW_Languages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Mass_Codes'
    	SELECT Lup_AP_Mass_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Mass_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Months'
    	SELECT Slu_AW_Months_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Months
    ELSE
    IF @Choice = 'Lup_AP_PLU_Tabs'
    	SELECT Lup_AP_PLU_Tabs_ID as [ID],
               Tab_No as [Tab No],Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_PLU_Tabs
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
   ELSE 
   IF @Choice = 'Lup_AP_Product_Departments'
    	SELECT Lup_AP_Product_Departments_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Departments
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Groups'
    	SELECT Lup_AP_Product_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Locations'
    	SELECT Lup_AP_Product_Locations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Locations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Purchase_Categories'
    	SELECT Lup_AP_Purchase_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Purchase_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Manufacturers'
    	SELECT Lup_AP_Product_Manufacturers_ID as [ID],
               Description as [Description],
               Old_Code as [Old Code],
               Default_Supplier_ID as [Default Supplier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Manufacturers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Types'
    	SELECT Lup_AP_Product_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Provinces'
    	SELECT Slu_AW_Provinces_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Provinces
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Purchase_Price_Types'
    	SELECT Lup_AO_Purchase_Price_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Purchase_Price_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Reps'
    	SELECT Lup_AS_Reps_ID as [ID],
               Description as [Description],
               Lup_AS_Commission_Categories_ID as [Commission Category],
        	   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Reps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Rounding_Codes'
    	SELECT Lup_AP_Rounding_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Rounding_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Sales_Areas'
    	SELECT Lup_AC_Sales_Areas_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Sales_Areas
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AP_Sell_By_Codes'
    	SELECT Lup_AP_Sell_By_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Sell_By_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Stores'
    	SELECT Lup_AW_Stores_ID as [ID],
               Description as [Description],
               Slu_AW_Countries_ID as [Country],
               Slu_AW_Provinces_ID as [Province],
               City as [City],Suburb as [Suburb],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Stores
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Switch2_Types'
    	SELECT Lup_AP_Switch2_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Switch2_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Tills'
    	SELECT Lup_AS_Tills_ID as [ID],
               Description as [Description],
               Till_Float as [Till Float],
               Cashier_ID as [Cashier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Tills
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Titles'
    	SELECT Slu_AW_Titles_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Titles
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Transaction_Profiles'
    	SELECT Lup_AS_Transaction_Profiles_ID as [ID],
               KeyCode as [KeyCode],
               Description as [Description],
               Sequence as [Sequence],
               Activated as [Activated],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Transaction_Profiles
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AP_Units_Of_Measure'
    	SELECT Slu_AP_Units_Of_Measure_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AP_Units_Of_Measure
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Workstations'
    	SELECT Lup_AW_Workstations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Workstations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Years'
    	SELECT Slu_AW_Years_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Years
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_YesNo'
    	SELECT Slu_AW_YesNo_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_YesNo
    ELSE
    IF @Choice = 'Sys_AW_Tax_Codes'
    	SELECT Sys_AW_Tax_Codes_ID as [ID],
               Description as [Description],
               Tax_Code as [Tax Code],
               Tax_Rate as [Tax Rate]
    	FROM Sys_AW_Tax_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Sys_AW_Payment_Methods'
    	SELECT Sys_AW_Payment_Methods_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Sys_AW_Payment_Methods
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Adverse_Reasons'
    	SELECT Slu_AC_Adverse_Reasons_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Adverse_Reasons
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Association_Types'
    	SELECT Slu_AC_Association_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Association_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Auditor_Rankings'
    	SELECT Slu_AC_Auditor_Rankings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Auditor_Rankings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bank_Codes'
    	SELECT Slu_AC_Bank_Codes_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Bank_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bond_Types'
    	SELECT Slu_AC_Bond_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Bond_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Business_Types'
    	SELECT Slu_AC_Business_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Business_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_ITC_Scores'
    	SELECT Slu_AC_ITC_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_ITC_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_KI_Scores'
    	SELECT Slu_AC_KI_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_KI_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Principal_Types'
    	SELECT Slu_AC_Principal_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Principal_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Profession_Types'
    	SELECT Slu_AC_Profession_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Profession_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Ratings'
    	SELECT Slu_AC_Ratings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Ratings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Security_Types'
    	SELECT Slu_AC_Security_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Security_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Shareholding_Types'
    	SELECT Slu_AC_Shareholding_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Shareholding_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Courts'
    	SELECT Slu_AW_Courts_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Courts
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Industry_Categories'
    	SELECT Slu_AW_Industry_Categories_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Industry_Categories
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Info_Report_Types'
    	SELECT Slu_AW_Info_Report_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Info_Report_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Lawsuit_Types'
    	SELECT Slu_AW_Lawsuit_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Lawsuit_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Nature_Of_Action'
    	SELECT Slu_AW_Nature_Of_Action_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Nature_Of_Action
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_CBilling_Providers'
    	SELECT Lup_AS_CBilling_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_CBilling_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Fail_Reasons'
    	SELECT Lup_AP_Fail_Reasons_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Fail_Reasons
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Claim_Codes'
    	SELECT Lup_AP_Claim_Codes_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Claim_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Groups'
    	SELECT Lup_AC_Customer_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               [User_ID] as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_SMS_Messages'
    	SELECT Slu_AW_SMS_Messages_ID as [ID],
               English as [English],
               Afrikaans as [Afrikaans],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_SMS_Messages
        ORDER BY [English]
    ELSE
    IF @Choice = 'Lup_AC_Markup_Categories'
    	SELECT Lup_AC_Markup_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Markup_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Markup_Groups'
    	SELECT Lup_AP_Markup_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Markup_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Groups'
    	SELECT Lup_AB_Account_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Divisions'
    	SELECT Lup_AB_Account_Divisions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Divisions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Groups'
    	SELECT Lup_AO_Supplier_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Types'
    	SELECT Lup_AO_Supplier_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Shipping_Rates'
        SELECT Slu_AW_Shipping_Rates_ID as [ID],
                Post_Code as [Post Code],
                Description as [Description],
                Location as [Locality],
                Rate_Per_Kg as [Rate/Kg],
                Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Shipping_Rates
        ORDER BY [Post Code], [Description]
    ELSE
    IF @Choice = 'Slu_AS_Volume_Discounts'
    	SELECT Slu_AS_Volume_Discounts_ID as [ID],
               Description as [Description],
               Sales_Qty as [Sales Qty],
               Discount_Perc as [Discount %],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Volume_Discounts
    ELSE
    IF @Choice = 'Sys_AB_B2'
    	SELECT Sys_AB_B2_ID as [BS2],
               Description as [Description]
    	FROM Sys_AB_B2
    ELSE
    IF @Choice = 'Sys_AB_B3'
    	SELECT Sys_AB_B3_ID as [BS3],
               Description as [Description]
    	FROM Sys_AB_B3
    ELSE
    IF @Choice = 'Sys_AB_I3'
    	SELECT Sys_AB_I3_ID as [IS3],
               Description as [Description]
    	FROM Sys_AB_I3
    ELSE
    IF @Choice = 'Sys_AB_I4'
    	SELECT Sys_AB_I4_ID as [IS4],
               Description as [Description]
    	FROM Sys_AB_I4
    ELSE
    IF @Choice = 'Slu_AC_Statement_Messages'
    	SELECT Slu_AC_Statement_Messages_ID as [ID],
               Description as [Description],
               Message as [Message],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Statement_Messages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'AW_Messages'
    	SELECT AW_Messages_ID as [ID],
               Description as [Description]
    	FROM AW_Messages
        ORDER BY [ID]
    ELSE
    IF @Choice = 'Lup_AS_Procurement_Providers'
    	SELECT Lup_AS_Procurement_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Procurement_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Transaction_Type_Maps'
    	SELECT Lup_AB_Transaction_Type_Maps_ID as [ID],
               Slu_AW_Banks_ID as [Bank],
               Sys_AB_Transaction_Types_ID as [Transaction Type],
               Mapping_CSV as [Mapping CSV List],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Transaction_Type_Maps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Bank], [Mapping CSV List]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agents'
    	SELECT Lup_AP_Shipping_Agents_ID as [ID],
               Description as [Description],
               Customer_Code as [Customer Code],
               Warehouse_No as [Warehouse No],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agents
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agent_Files'
    	SELECT Lup_AP_Shipping_Agent_Files_ID as [ID],
               Lup_AP_Shipping_Agents_ID as [Shipping Agent],
               Description as [Description],
               Server_Name as [Server Name],
               Login_Name as [Login Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agent_Files
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AF_Instructions'
    	SELECT Lup_AF_Instructions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AF_Instructions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Slu_AW_Countries_Mobile'
    	SELECT Slu_AW_Countries_Mobile_ID as [ID],
               Slu_AW_Countries_ID as [Country],
               Description as [Description],
               Mobile_Dialing_Code as [Mobile Code],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Slu_AW_Countries_Mobile
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AP_AW_Weight'
    	SELECT Lup_AP_AW_Weight_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AP_AW_Weight
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AP_Product_Bins'
    	SELECT Lup_AP_Product_Bins_ID as [ID],
               Description as [Description],
               Email As [Email],
               Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AP_Product_Bins
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AB_Account_Departments'
    	SELECT Lup_AB_Account_Departments_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AB_Account_Departments
        ORDER BY [Description]


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_AW_Lookup_Editor_Lookups_Select
--Purpose       :Select the Lookups used in the Lookup Editor
--Parameters    :
--Date          :2002/01/09
--Authors       :TB
--Mods          :
--2004.4.8      :19/02/10 - Added Slu_AW_Banks as [Bank]
--              :19/02/10 - Added Sys_AB_Transaction_Types_ID (Cashbook Only) as [Type]
--2004.4.9      :08/09/10 - Added Lup_AP_Shipping_Agents as [Shipping Agent]
------------------------------------------------------------------------------

CREATE        PROCEDURE sp_AW_Lookup_Editor_Lookups_Select
    (
        @Choice varchar(50) = ''
    )

AS

	IF @Choice = 'Suppliers'
		SELECT
			AO_Suppliers_ID as [ID],
			Supplier_Name as [Description]
		FROM AO_Suppliers

    ELSE
	IF @Choice = 'YesNo'
		SELECT 
			[Slu_AW_YesNo_ID] as [ID], 
			[Description]
		FROM [Slu_AW_YesNo]

    ELSE
	IF @Choice = 'Cashiers'
		SELECT [Lup_AS_Cashiers_ID] as [ID], 
			[Description]   
		FROM [Lup_AS_Cashiers]

    ELSE
	IF @Choice = 'Provinces'
		SELECT [Slu_AW_Provinces_ID] as [ID], 
			[Description]
		FROM [Slu_AW_Provinces]

    ELSE
	IF @Choice = 'Countries'
		SELECT 
			[Slu_AW_Countries_ID] as [ID], 
			[Description]  
		FROM [Slu_AW_Countries]

    ELSE
	IF @Choice = 'Commission Categories'
		SELECT 
			[Lup_AS_Commission_Categories_ID] as [ID], 
			[Description]
		FROM [Lup_AS_Commission_Categories]

    ELSE
	IF @Choice = 'Active'
		SELECT 
			[Slu_AW_Active_ID] as [ID], 
			[Description]
		FROM [Slu_AW_Active]

    ELSE
	IF @Choice = 'KeyCodes'
		SELECT 
			[Sys_AS_Numeric_Keys_ID] as [ID], 
			[Description]
		FROM [Sys_AS_Numeric_Keys]

    ELSE
	IF @Choice = 'Transaction Categories'
		SELECT 
			[Sys_AB_Transaction_Categories_ID] as [ID], 
			[Description]
		FROM [Sys_AB_Transaction_Categories]

    ELSE
	IF @Choice = 'Bank'
		SELECT 
			[Slu_AW_Banks_ID] as [ID], 
			[Description] as [Bank]
		FROM [Slu_AW_Banks]

    ELSE
	IF @Choice = 'Transaction Type'
    	SELECT
            [Sys_AB_Transaction_Types_ID] as [ID], 
              [Description] AS [Transaction Type] 
    	FROM Sys_AB_Transaction_Types
    	WHERE Sys_AB_Transaction_Categories_ID = 3

    ELSE
	IF @Choice = 'Shipping Agent'
    	SELECT
            [Lup_AP_Shipping_Agents_ID] as [ID], 
              [Description] AS [Shipping Agent] 
    	FROM Lup_AP_Shipping_Agents









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










---------------------------------------------------------------------------
--Description	:sp_AW_Lookup_Table_Names_Select
--Purpose	    :Selects LookUp tables from Sys_AW_Lookup_Editor
--Functionality	: 
--Parameters	: 
--Date		    :21/01/2002
--Authors	    :TB
--Version	    :1.0.0
--MODS          :28/07/03 - Inserted and Validate for ACTIVE lookups only 
---------------------------------------------------------------------------

CREATE        PROCEDURE sp_AW_Lookup_Table_Names_Select

AS

SET NOCOUNT ON

    SELECT SYS_AW_Lookup_Editor_ID as [ID],
            TableName,
            Caption,
            ColumnWidths
    FROM Sys_AW_Lookup_Editor
    WHERE Slu_AW_Active_ID = 1
    ORDER BY Caption


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-----------------------------------------------------------------------------
--Description   :sp_AW_Modules_Applications_Per_User_Select
--Purpose       :Build Modules and Applications for user role at login
--              :
--Parameters    :
--Date          :2001/12/10
--Authors       :TB
--Version       :1.0.0
--MODS          :13/12/01 - Only load Active Apps from Sys_AW_Applications
--              :20/03/02 - Add ALL existing users for a newly created Company
-----------------------------------------------------------------------------

CREATE        PROCEDURE sp_AW_Modules_Applications_Per_User_Select
	(
		@UserID int,
		@CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT DISTINCT
            m.Sys_AW_Modules_ID AS [ModID], 
            m.[Description] AS [Module],
            a.Sys_AW_Applications_ID AS [AppID], 
            a.[Description] AS [Application],  
            a.Form_Name AS [FormName],
            '' as [LargeIcon],
            '' as [SmallIcon],
            m.Module_Seq,
            a.Application_Seq
    FROM AW_Users_Per_Role upr
        INNER JOIN AW_Roles r
            ON upr.AW_Roles_ID = r.AW_Roles_ID
        INNER JOIN AW_Applications_Per_Role apr
            ON r.AW_Roles_ID = apr.AW_Roles_ID
        INNER JOIN Sys_AW_Applications a
            ON apr.Sys_AW_Applications_ID = a.Sys_AW_Applications_ID
        INNER JOIN Sys_AW_Modules m
            ON a.Sys_AW_Modules_ID = m.Sys_AW_Modules_ID
    WHERE upr.AW_Users_ID = @UserID AND
--> TB added 20/03/02
--          (upr.AW_User_Companies_ID = @CompanyID) AND
--> TB added 13/12/01
          a.Slu_AW_Active_ID = 1
    ORDER BY  m.Module_Seq, a.Application_Seq  




--> Return Value = Startup APP ID (glngUserStartupApp)
	RETURN (SELECT Sys_AW_Applications_ID AS [User Startup App] 
			FROM AW_Users 
			WHERE AW_Users_ID = @UserID)




SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AW_Modules_Select
--Purpose       :Build Modules amd Applications for user role at login
--              :
--Parameters    :
--Date          :2002/03/10
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE       PROCEDURE sp_AW_Modules_Select

AS

SET NOCOUNT ON

    SELECT Sys_AW_Modules_ID AS [ID], 
          [Description] AS [Module]
    FROM Sys_AW_Modules
    WHERE Slu_AW_Active_ID = 1
    ORDER BY [ID]

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE  PROCEDURE sp_AW_Month_Ends_Insert
    ( @Module int, 
	@Month tinyint, 
	@Year smallint,
	@Date datetime,
	@ID int Output)
AS
	SELECT @ID = AW_Month_Ends_ID FROM AW_Month_Ends WHERE Sys_AW_Modules_ID = @Module AND
							[Month] = @Month and [Year] = @Year
	IF @ID IS NULL
		BEGIN
			INSERT AW_Month_Ends (Sys_AW_Modules_ID ,[Month] , [Year], Month_End_Date)
			VALUES                      (@Module,@Month , @Year, @Date)
	
			SELECT @ID = 	Scope_Identity()
		END
	ELSE
		SET @ID = 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AW_Next_Transaction_Number
--Purpose       :INCREMENT next available System Transaction Number
--Functionality :Tables: Sys_AW_Transaction_Numbers
--Parameters    :RETURNS next transaction number as parameter
--Date          :2009/08/08
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE        PROCEDURE sp_AW_Next_Transaction_Number
    (
        @TransactionType int, 
        @CompanyID int
    )

AS

SET NOCOUNT ON    

    DECLARE @Num int,
            @TransactionNumber varchar(15)
    
    SELECT @Num = ISNULL(Last_Number, 0)
    FROM Sys_AW_Transaction_Numbers
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Transaction_Types_ID = @TransactionType
    
    UPDATE Sys_AW_Transaction_Numbers
    SET Last_Number = @Num + 1 
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Transaction_Types_ID = @TransactionType
    
    SET @TransactionNumber = CONVERT(varchar(15), @Num + 1)

    RETURN @TransactionNumber


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_AW_Options_Insert_Update
--Purpose       :Inserts or Updates System Options
--Date          :2002/09/16
--Authors       :TB
--Mods          :
--2004.4.5      :20/05/09 - Increased @ControlValue from varchar(100) to 250 !!
--              :20/05/09 - Added INSERT System Options Log
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Options_Insert_Update
	(
		@ControlType varchar(50),
		@ControlName varchar(50),
		@ControlIndex smallint,
		@ControlValue varchar(250),
        @UserID int,
        @CompanyID int
        
	)

AS     

SET NOCOUNT ON

    DECLARE @OptID int,
            @PrevValue varchar(250)


    SET @OptID = 0


	SELECT @OptID = ISNULL(Sys_AW_Options_ID, 0),
           @PrevValue = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = @ControlType AND
          Control_Name = @ControlName AND
          Control_Index = @ControlIndex AND
          AW_User_Companies_ID = @CompanyID


    IF @OptID > 0
        BEGIN
            --> NEW 2004.4.5 - INSERT Log
            IF @ControlValue <> @PrevValue
                BEGIN
                    INSERT Sys_AW_Options_Log
                        (
                            Control_Type,
                            Control_Name,
                            Control_Index,
                            Control_Value,
                            Date_Captured,
                            [User_ID],
                            AW_User_Companies_ID
                        )
                    VALUES
                        (
                    		@ControlType,
                    		@ControlName,
                    		@ControlIndex,
                    		@ControlValue,
                            getdate(),
                            @UserID,
                            @CompanyID
                        )
                END

        	UPDATE Sys_AW_Options
            SET Control_Value = @ControlValue,
                Date_Captured = getdate(),
                [User_ID] = @UserID
            WHERE Sys_AW_Options_ID = @OptID
        END
    ELSE
        BEGIN
            INSERT Sys_AW_Options
                (
                    Control_Type,
                    Control_Name,
                    Control_Index,
                    Control_Value,
                    Date_Captured,
                    [User_ID],
                    AW_User_Companies_ID
                )
            VALUES
                (
            		@ControlType,
            		@ControlName,
            		@ControlIndex,
            		@ControlValue,
                    getdate(),
                    @UserID,
                    @CompanyID
                )
        END




--     IF EXISTS
--        (
--         	SELECT Control_Value
--             FROM Sys_AW_Options
--             WHERE Control_Type = @ControlType AND
--                   Control_Name = @ControlName AND
--                   Control_Index = @ControlIndex AND
--                   AW_User_Companies_ID = @CompanyID
--         )
--         BEGIN
--         	UPDATE Sys_AW_Options
--             SET Control_Value = @ControlValue,
--                 Date_Captured = getdate(),
--                 [User_ID] = @UserID
--             WHERE Control_Type = @ControlType AND
--                   Control_Name = @ControlName AND
--                   Control_Index = @ControlIndex AND
--                   AW_User_Companies_ID = @CompanyID
--         END
--     ELSE
--         BEGIN
--             INSERT Sys_AW_Options
--                 (
--                     Control_Type,
--                     Control_Name,
--                     Control_Index,
--                     Control_Value,
--                     Date_Captured,
--                     [User_ID],
--                     AW_User_Companies_ID
--                 )
--             VALUES
--                 (
--                         @ControlType,
--                         @ControlName,
--                         @ControlIndex,
--                         @ControlValue,
--                         getdate(),
--                         @UserID,
--                         @CompanyID
--                 )
--         END



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_Options_Select
--Purpose       :
--Functionality :MUST return @ControlValue as a STRING
--Parameters    :
--Date          :2002/09/16
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Options_Select]
	(
		@ControlType varchar(50),
		@ControlName varchar(50),
		@ControlIndex smallint,
        @CompanyID int,
		@ControlValue varchar(250) OUTPUT
	)

AS     

SET NOCOUNT ON

	SELECT @ControlValue = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = @ControlType AND
          Control_Name = @ControlName AND
          Control_Index = @ControlIndex AND
          AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AW_Options_Select_W
--Purpose       :Return a SCALAR parameter value
--Functionality :MUST return @ControlValue as a STRING
--Parameters    :
--Date          :2003/09/21
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Options_Select_W
	(
		@ControlType varchar(50),
		@ControlName varchar(50),
		@ControlIndex smallint
	)

AS     

SET NOCOUNT ON

	SELECT Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = @ControlType AND
          Control_Name = @ControlName AND
          Control_Index = @ControlIndex

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AW_Period_Is_Pre_Month_End
--Purpose       :Is Accounting Period PRIOR TO LAST Suppliers Month-End
--Returns       :Scalar OUTPUT parameter: 0 if False or 1 if True
--Date          :2008/04/30
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Period_Is_Pre_Month_End
	(
        @CompanyID int,
    	@MonthsID tinyint, 
    	@YearsID int,
        @TypeID tinyint,
		@PreMonthEnd tinyint OUTPUT
	)

AS

    DECLARE @LastME_Month_ID tinyint,
            @LastME_Year_ID int,
            @LastMEPeriod varchar(6),
            @TranGLPeriod varchar(6)


    ---------------------------------------------------------------
    --> Suppliers Month-End
    ---------------------------------------------------------------
    IF @TypeID = 6
        BEGIN
            SET @PreMonthEnd = 0                    -- 0 = False

            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 = @TypeID
            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)


            IF @TranGLPeriod <= @LastMEPeriod
                BEGIN
                    SET @PreMonthEnd = 1            -- 1 = True
                END
        END
    ---------------------------------------------------------------



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AW_Period_Procedure_Periods_Select
--Purpose       :Retrieves last (up to) 7 Accounting Periods 6-digit integer strings
--              :into which the AGE AREA balances for each Account is inserted
--Date          :2007/03/09
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Period_Procedure_Periods_Select
	(
        @MonthID int,
        @YearID int,
	    @D1 varchar(6) OUTPUT,
	    @D2 varchar(6) OUTPUT,
	    @D3 varchar(6) OUTPUT,
	    @D4 varchar(6) OUTPUT,
	    @D5 varchar(6) OUTPUT,
	    @D6 varchar(6) OUTPUT,
	    @D7 varchar(6) OUTPUT
	)

AS

SET NOCOUNT ON

    --> CURRENT
    SELECT @D1 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @MonthID = @MonthID - 1

    IF @MonthID = 0
        BEGIN
            SET @MonthID = 12
            SET @YearID = @YearID - 1
        END


    --> 30 Days
    SELECT @D2 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @MonthID = @MonthID - 1

    IF @MonthID = 0
        BEGIN
            SET @MonthID = 12
            SET @YearID = @YearID - 1
        END


    --> 60 Days
    SELECT @D3 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @MonthID = @MonthID - 1

    IF @MonthID = 0
        BEGIN
            SET @MonthID = 12
            SET @YearID = @YearID - 1
        END


    --> 90 Days
    SELECT @D4 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @MonthID = @MonthID - 1

    IF @MonthID = 0
        BEGIN
            SET @MonthID = 12
            SET @YearID = @YearID - 1
        END


    --> 120 Days
    SELECT @D5 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @MonthID = @MonthID - 1

    IF @MonthID = 0
        BEGIN
            SET @MonthID = 12
            SET @YearID = @YearID - 1
        END


    --> 150 Days
    SELECT @D6 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    SET @MonthID = @MonthID - 1

    IF @MonthID = 0
        BEGIN
            SET @MonthID = 12
            SET @YearID = @YearID - 1
        END


    --> 180 Days
    SELECT @D7 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)




SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AW_Period_Procedures_Select
--Purpose       :Retrieves last (up to) 7 Month-Ends DATES
--              :into which the AGE AREA balances for each Account is inserted
--Parameters    :
--Date          :2002/03/04
--Authors       :TB
--Version       :1.0.0
--MODS          :11/07/02 - Replaced OLDEST Month-End date with '1900/01/01'
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Period_Procedures_Select
	(
	    @DateFrom datetime,
	    @D1 datetime OUTPUT,
	    @D2 datetime OUTPUT,
	    @D3 datetime OUTPUT,
	    @D4 datetime OUTPUT,
	    @D5 datetime OUTPUT,
	    @D6 datetime OUTPUT,
	    @D7 datetime OUTPUT,
	    @Period_Procedure_Type_ID smallint = 1,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT Top 1 @D1 = Month_End_Date
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @DateFrom AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC
    
    SELECT Top 1 @D2 = Month_End_Date 
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @D1 AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC
    
    SELECT Top 1 @D3 = Month_End_Date 
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @D2 AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC
    
    SELECT Top 1 @D4 = Month_End_Date
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @D3 AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC
    
    SELECT Top 1 @D5 = Month_End_Date
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @D4 AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC
    
    SELECT Top 1 @D6 = Month_End_Date 
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @D5 AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC
    
    SELECT Top 1 @D7 = Month_End_Date 
    FROM AW_Period_Procedures 
    WHERE Sys_AW_Period_Procedure_Types_ID = @Period_Procedure_Type_ID AND
          Month_End_Date < @D6 AND
          AW_User_Companies_ID = @CompanyID
    ORDER BY Month_End_Date DESC

	IF @D1 IS NULL
        BEGIN
    		SET @D1 =  '1900/01/01'
            RETURN
        END
	ELSE
	IF @D2 IS NULL
        BEGIN
    		SET @D2 =  '1900/01/01'
            RETURN
        END
	ELSE
	IF @D3 IS NULL
        BEGIN
    		SET @D3 =  '1900/01/01'
            RETURN
        END
	ELSE
	IF @D4 IS NULL
        BEGIN
    		SET @D4 =  '1900/01/01'
            RETURN
        END
	ELSE
	IF @D5 IS NULL
        BEGIN
    		SET @D5 =  '1900/01/01'
            RETURN
        END
	ELSE
	IF @D6 IS NULL
        BEGIN
    		SET @D6 =  '1900/01/01'
            RETURN
        END
	ELSE
--If there are >= 7 Period Procedures (over 180+ Days),
--Put the + into '180+ Days' by including ALL Transactions
--from 1900/01/01, otherwise the '180+ Days' ageing amount
--will only include transactions from that Period Procedure date
	IF @D7 IS NOT NULL
        BEGIN
    		SET @D7 =  '1900/01/01'
            RETURN
        END
	IF @D7 IS NULL
        BEGIN
		    SET @D7 =  '1900/01/01'
        END

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-----------------------------------------------------------------------------
--Description   :sp_AW_Ping_Remote_DataSource
--Purpose       :Returns SCALAR tinyint if DataSource Access failure/success
--Funtionality  :    0 = Success, 1 = Failure
--Notes         :-n Count    - specifies the number of Echo Request messages sent. Default = 4 (4 messages)
--              :-w Timeout  - specifies time in milliseconds to wait for Echo Reply message. Default = 4000 (4 seconds)
--Date          :2009/09/11
--Authors       :TB
--MODS          :
-----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Ping_Remote_DataSource
	(
        @DataSource varchar(50),
        @Timeout tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode tinyint,
            @CmdTxt varchar(100)

    SET @RetCode = 1        --1 = Fail

    SET @CmdTxt = 'ping -n 1 -w ' + CONVERT(varchar(4), @Timeout) + ' ' + ltrim(rtrim(@DataSource))
    EXEC @RetCode = master..xp_cmdshell @CmdTxt, no_output



RETURN @RetCode













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AW_Put_Next_SCM_File_Number
--Purpose       :Inserts the next SCM File number
--Date          :2009/06/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Put_Next_SCM_File_Number
    (
        @CompanyID int,
        @FileNo int,
        @LastDate datetime
    )

AS


    UPDATE AW_User_Companies
    SET Sp_Sales_File_Count = @FileNo,
        Sp_Sales_File_Date = @LastDate
    WHERE AW_User_Companies_ID = @CompanyID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_AW_Remove_Apps_Per_Role
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2001/07/22
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE   PROCEDURE sp_AW_Remove_Apps_Per_Role
    (
    	@User_Role_ID smallint,
    	@AW_Application_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	DELETE FROM AW_Applications_Per_Role
	WHERE AW_Roles_ID = @User_Role_ID AND
          Sys_AW_Applications_ID = @AW_Application_ID AND	
          AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AW_Remove_Users_Per_Role
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE     PROCEDURE sp_AW_Remove_Users_Per_Role
    (
    	@User_Role_ID smallint,
    	@AW_Users_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	DELETE FROM AW_Users_Per_Role
	WHERE AW_Roles_ID = @User_Role_ID AND
          AW_Users_ID = @AW_Users_ID AND	
          AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :sp_AW_Reset_GL_Transaction_Activity
--Purpose       :RESET Active flag of ALL De-Activated GL Transactions
--              :Used when ALL GL Year-End procedures have been deleted
--              :to enable GL Year-End procedures to be re-done
--Date          :2010/07/16
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_AW_Reset_GL_Transaction_Activity
	(
        @Option tinyint,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @DisabledCNT int

    SET @DisabledCNT = 0

    ---------------------------------------------------------------------------------
    --> PREP GL Transactions
    ---------------------------------------------------------------------------------
    IF @Option = 1
        BEGIN
            UPDATE AB_GL_Transactions
            SET Slu_AW_Active_ID = 1,
                AB_Transaction_Amount = ROUND(AB_Transaction_Amount, 2)
            WHERE AW_User_Companies_ID = @CompanyID
        END

    -----------------------------------------------------------------------------
    -- SYNC GL ACCOUNT BALANCE to GL TRAN TOTAL
    -----------------------------------------------------------------------------
    ELSE
    IF @Option = 2
        BEGIN
            UPDATE AB_Accounts
            SET AB_Account_Balance = CONVERT(money, dbo.fn_AB_SUM_GL_Account_Transactions(AB_Accounts_ID, AW_User_Companies_ID))
            WHERE AW_User_Companies_ID = @CompanyID
        END
    ---------------------------------------------------------------------------------

    ELSE
    IF @Option = 3
        SET NOCOUNT OFF

        BEGIN
            SELECT @DisabledCNT = COUNT(*)
            FROM AB_GL_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Slu_AW_Active_ID <> 1
        END




RETURN @DisabledCNT











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AW_SQL_Builder
--Purpose       :Bulds GENERIC SQL script with DATA DEFINITION input parameters
--Date          :2003/0812
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_SQL_Builder
    (
        @SelectList varchar(1000),
        @TableList varchar(1000),
        @WhereClause varchar(1000) = '',
        @OrderBy varchar(1000) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @SQL varchar(7000)

    SET @SQL = ' SELECT ' + @SelectList +
               ' FROM ' + @TableList

    IF RTRIM(LTRIM(@WhereClause)) <> ''
        BEGIN
            SET @SQL = @SQL + ' WHERE ' + @WhereClause + ' '
        END

    IF RTRIM(LTRIM(@OrderBy)) <> ''
        BEGIN
            SET @SQL = @SQL + ' ORDER BY ' + @OrderBy
        END


--PRINT @SQL

EXEC (@SQL)














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   :sp_AW_Select_Applications_Per_User
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE   PROCEDURE sp_AW_Select_Applications_Per_User
    (
    	@User_ID int    )

AS

SET NOCOUNT ON

    SELECT A.Sys_AW_Applications_ID AS [ID],
           U.AW_Users_ID AS [FK ID], 
           R.[Description] AS [Role], 
           A.[Description] AS [Application]
    FROM Sys_AW_Applications A 
    	INNER JOIN AW_Applications_Per_Role APR 
    		ON A.Sys_AW_Applications_ID = APR.Sys_AW_Applications_ID 
    	INNER JOIN AW_Roles R 
    		ON APR.AW_Roles_ID = R.AW_Roles_ID 
    	INNER JOIN AW_Users U 
    	INNER JOIN AW_Users_Per_Role UPR ON U.AW_Users_ID = UPR.AW_Users_ID ON 
    	  R.AW_Roles_ID = UPR.AW_Roles_ID
    WHERE U.AW_Users_ID = @User_ID
    ORDER BY U.AW_Users_ID


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Apps_Per_Role
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
--MODS          :15/10/02 - Select ONLY Modules and Applications
--              :                WHERE Slu_AW_Active_ID = 1
-------------------------------------------------------------------------------

CREATE    PROCEDURE sp_AW_Select_Apps_Per_Role
    (
    	@User_Role_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT
        A.Sys_AW_Applications_ID,
        ISNULL(A.[Description], '') AS [Application],
        ISNULL(M.[Description], '') AS [Module]
	FROM AW_Applications_Per_Role APR
        LEFT JOIN Sys_AW_Applications A 
	        ON APR.Sys_AW_Applications_ID = A.Sys_AW_Applications_ID
        LEFT JOIN Sys_AW_Modules M
            ON A.Sys_AW_Modules_ID = M.Sys_AW_Modules_ID
	WHERE APR.AW_Roles_ID = @User_Role_ID AND
          APR.AW_User_Companies_ID = @Company_ID AND
          A.Slu_AW_Active_ID = 1 AND
          M.Slu_AW_Active_ID = 1
	ORDER BY M.Module_Seq, A.Application_Seq ASC


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   : sp_AW_Select_Apps_Per_User
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/07/24
--Authors       : Charl
--Version       : 1.0.
-------------------------------------------------------------------------------
CREATE   PROCEDURE sp_AW_Select_Apps_Per_User
(
	@Module_ID int,
	@User_ID int,
	@Company_ID int
)

AS
    SET NOCOUNT ON

SELECT a.Sys_AW_Modules_ID AS [Module ID],
       ar.Sys_AW_Applications_ID AS [Application_ID],
       a.[Description] AS [Application],
       a.Application_Seq AS [Sequence],
	a.form_name as FormName
FROM AW_Applications_Per_Role ar
    INNER JOIN Sys_AW_Applications a
        ON ar.Sys_AW_Applications_ID = a.Sys_AW_Applications_ID
WHERE ar.AW_Roles_ID IN (
                         SELECT AW_Roles_ID
                         FROM AW_Users_Per_Role
                         WHERE AW_Users_ID = @User_ID AND
							   AW_User_Companies_ID = @Company_ID 
                            )AND
	a.Sys_AW_Modules_ID = @Module_ID
GROUP BY a.Sys_AW_Modules_ID, ar.Sys_AW_Applications_ID,a.[Description], a.Application_Seq, a.form_name
ORDER BY a.Sys_AW_Modules_ID, MAX(a.Application_Seq) ASC





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------------------------------------------------

--Description   :sp_AW_Select_Companies_Per_User
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE      PROCEDURE sp_AW_Select_Companies_Per_User
    (
    	@User_ID int    )

AS

SET NOCOUNT ON

    SELECT AW_Company_Users_ID AS [ID], 
           AW_Users_ID AS [FK ID], 
           AW_User_Companies_ID AS [Company], 
           Slu_AW_Active_ID AS [Active] 
    FROM AW_Company_Users
    WHERE AW_Users_ID = @User_ID

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











---------------------------------------------------------------------------
--Description   :sp_AW_Select_Companies_PickList
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2001/12/03
--Authors       :TB
--Version       :1.0.0
---------------------------------------------------------------------------

CREATE  PROCEDURE sp_AW_Select_Companies_PickList

AS

SET NOCOUNT ON

    SELECT AW_User_Companies_ID AS [ID], 
           Company_Name AS [Company Name]
    FROM AW_User_Companies

SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Company_Banks
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/03/13
--Authors       :TB
--MODS          :20/11/03 - Changed [User_ID] alias from [User ID] to [User]
--2004.5.0      :28/01/11 - Added [Overdraft Limit]
-------------------------------------------------------------------------------

CREATE             PROCEDURE         sp_AW_Select_Company_Banks
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    SELECT
        AW_Company_Banks_ID AS [ID], 
        AW_User_Companies_ID AS [FK ID], 
        Slu_AW_Banks_ID AS [Bank], 
        Bank_Branch AS [Branch], 
        Bank_Branch_Code AS [Bank Code], 
        Account_Number AS [Account Number], 
        Account_Name AS [Account Name], 
        Overdraft_Limit AS [Overdraft Limit],
        AB_Accounts_ID AS [GL Control Account], 
        Date_Opened AS [Date Opened], 
        Slu_AW_Active_ID AS [Active], 
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User] 
    FROM AW_Company_Banks 
    WHERE AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Company_Catalog
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/17
--Authors       :TB
--MODS          :02/11/02 - Removed the following 2 columns:
--              :               Company_Year_End_Date
--              :               Next_Month_End_Date
--              :01/01/03 - Added [YearEndMonth], [AccountingMonth] and
--              :           [AccountingYear] for display in General Ledger
--              :03/01/04 - Added [Administrator], [Contact1Email],
--              :           [Contact1Active], [Contact2Email],
--              :           [Contact2Active] for Credit Manager
--2004.4.4      :31/03/09 - Added [SpAccountID] for Spiralsoft Web Account No
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Company_Catalog
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    SELECT
        a.AW_User_Companies_ID AS [ID], 
        a.Company_Name AS [Company Name], 
        a.Company_Trading_Name AS [Trading Name], 
        a.Company_Registration_Number AS [Registration Number], 
        a.Take_On_Phase AS [TakeOn],
        a.Tel_No AS [Telephone No],
        a.Fax_No AS [Fax No],
        a.E_Mail AS [E-mail Address],
        a.Web_Home AS [Web Home Page],
        a.Company_Addr1 AS [Address 1], 
        a.Company_Addr2 AS [Address 2], 
        a.Company_City AS [City], 
        a.Company_Post_Code AS [Postal Code], 
        a.Slu_AW_Countries_ID AS [Country], 
        a.Yes_No_Default_Company AS [Default Company], 
        a.User_CRM_ID AS [CRM],
        a.Slu_AW_Active_ID AS [Active],
        a.Delivery_Addr1 AS [Del Addr 1],
        a.Delivery_Addr2 AS [Del Addr 2],
        a.Delivery_Addr3 AS [Del Addr 3],
        a.Network_Identity_Number AS [Network ID No], 
        a.Parent_ID AS [Parent Company], 
        a.TAX_Number AS [Tax Number],
        a.Year_End_Month_ID AS [Year-End Month],
        a.Slu_AW_Months_ID AS [CurrentMonth],
        a.Slu_AW_Years_ID AS [CurrentYear],
        b.Long_Description AS [YearEndMonth],
        c.[Description] AS [AccountingMonth],
        d.[Description] AS [AccountingYear],
        (
            SELECT TOP 1 ISNULL(Year_End_Date, '')
            FROM AW_Period_Procedures
            WHERE Year_End_Date IS NOT NULL
            ORDER BY Year_End_Date DESC
        ) AS [LastYearEnd],
        a.Contact1_Email AS [Contact1Email],
        a.Contact1_Active AS [Contact1Active],
        a.Contact2_Email AS [Contact2Email],
        a.Contact2_Active AS [Contact2Active],
        a.Sp_Account_ID AS [SpAccountID]
    FROM AW_User_Companies a
        LEFT JOIN Slu_AW_Months b
            ON a.Year_End_Month_ID = b.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Months c
            ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years d
            ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID
    WHERE AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Company_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/17
--Authors       :TB
--Version       :1.0.0
--MODS          :02/11/02 - Added 7 = Months & 8 = Years and changed Year-End
--              :           Month from 8 to 9
--              :20/11/03 - Added 10 - Users
--              :03/01/04 - Added 11, 12, 13, 14 - Credit Manager
--              :27/01/05 - Added ALPHA SORT for options 4 & 5
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_Company_Lups
    (
    	@Choice tinyint,
    	@Company_ID int = 0
    )

AS

SET NOCOUNT ON

    IF @Choice = 1
    	SELECT Slu_AW_Countries_ID AS [ID], 
    		[Description] AS [Country] 
    	FROM Slu_AW_Countries
    	
    ELSE
    IF @Choice = 2
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [Default Company] 
    	FROM Slu_AW_YesNo
    	
    ELSE
    IF @Choice = 3
    	SELECT Slu_AW_Active_ID AS [ID], 
    		[Description] AS [Active] 
    	FROM Slu_AW_Active
    
    ELSE
    IF @Choice = 4
    	SELECT Slu_AW_Banks_ID AS [ID], 
    		[Description] AS [Bank] 
    	FROM Slu_AW_Banks
        ORDER BY [Description]
    	
    ELSE
    IF @Choice = 5
    	SELECT AB_Accounts_ID AS [ID], 
    		[Description] AS [GL Control Account] 
    	FROM AB_Accounts
    	WHERE AW_User_Companies_ID = @Company_ID
        ORDER BY [Description]

    ELSE
    IF @Choice = 6 
    	SELECT AW_User_Companies_ID AS [ID], 
    		Company_Name AS [Parent Company] 
    	FROM AW_User_Companies

    ELSE 
    IF @Choice = 7
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Description] AS [Month]
    	FROM Slu_AW_Months

    ELSE
    IF @Choice = 8 
    	SELECT Slu_AW_Years_ID AS [ID], 
        	[Description] AS [Year]
    	FROM Slu_AW_Years
    
    ELSE 
    IF @Choice = 9
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Description] AS [Year-End Month] 
    	FROM Slu_AW_Months

    ELSE 
    IF @Choice = 10
        SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + Firstname, '') AS [Description]
        FROM AW_Users
        ORDER BY [Description]

	ELSE 
	IF @Choice = 11
		SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [CRM]
		FROM AW_Users
        WHERE IsCRM = 1
        ORDER BY [CRM]

    ELSE
    IF @Choice = 12
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [Contact1Active] 
    	FROM Slu_AW_YesNo
    	
    ELSE
    IF @Choice = 13
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [Contact2Active] 
    	FROM Slu_AW_YesNo

    ELSE
    IF @Choice = 14    --TakeOn
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [Description] 
    	FROM Slu_AW_YesNo

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









---------------------------------------------------------------------------------
--Description   :sp_AW_Select_Company_Network_ID
--Purpose       :
--Date          :2003/09/30
--Authors       :TB
--Version       :1.0.0
--MODS          : 
---------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Select_Company_Network_ID
    (
        @CompanyID int,
        @NetworkID varchar(20) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @NetworkID = ISNULL(Network_Identity_Number, '')
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Default_Country
--Purpose       :Select Default Country ID from Company Catalog
--Date          :2011/09/13
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_Default_Country
	(
        @CompanyID int,
		@DefaultCountryID smallint OUTPUT
	)

AS

    SET @DefaultCountryID = 0


	SELECT @DefaultCountryID = Slu_AW_Countries_ID
	FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


	IF @DefaultCountryID IS NULL 
        BEGIN	
    		SET @DefaultCountryID = 27
        END
		










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











--------------------------------------------------------------------------------
--Description   :sp_AW_Select_Email_Manager_Lups
--Purpose       :E-Mail Manager Lookups
--Date          :2004/06/19
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Select_Email_Manager_Lups
    (
       	@Option int
    )

AS

SET NOCOUNT ON


    IF @Option = 1	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],
               [Description] AS [Yes_No]  	
        FROM Slu_AW_YesNo

    ELSE
    IF @Option = 2	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID],
               [Description] AS [Active] 
        FROM Slu_AW_Active 



SET NOCOUNT OFF























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   : sp_AW_Select_Formula_Lookups
--Purpose       : Select AW_Formulas as LookUps
--              :
--Functionality : Tables: AW_Formulas
--Date          : 2002/02/15
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------


CREATE     PROCEDURE sp_AW_Select_Formula_Lookups
    (
        @Option varchar(20)
    )

AS

SET NOCOUNT ON

    IF @Option = 'Trade'
        SELECT AW_Formulas_ID AS [ID], [Description] AS [Trade]
        FROM AW_Formulas

    ELSE
    IF @Option = 'Rebate'
        SELECT AW_Formulas_ID AS [ID], [Description] AS [Rebate]
        FROM AW_Formulas

    ELSE
    IF @Option = 'Other'
        SELECT AW_Formulas_ID AS [ID], [Description] AS [Other]
        FROM AW_Formulas

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Formulas
--Purpose       : 
--Functionality : 
--Parameters    :
--Date          :2002/02/18
--Authors       :TB
--Version       :1.0.0
--MODS          :24/08/02 - Added ORDER BY [Description]
-------------------------------------------------------------------------------

CREATE      PROCEDURE sp_AW_Select_Formulas

AS

SET NOCOUNT ON

    SELECT 
        AW_Formulas_ID AS [ID],
        [Description],
        Formula,
        Fractions,
        Expression
    FROM AW_Formulas
    ORDER BY [Description]

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :sp_AW_Select_Last_7_Period_Procedures
--Purpose       :Retrieves latest 7 Period Procedures
--Parameters    :
--Date          :2004/06/26
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Select_Last_7_Period_Procedures
	(
        @ProcedureTypeID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON


    SELECT TOP 7 Month_End_Date as [Date]
    FROM  AW_Period_Procedures
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID AND
          Month_End_Date < getdate()
    ORDER BY Month_End_Date DESC


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Marquee_Messages
--Purpose       : 
--Functionality : 
--Date          :2003/08/17
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Select_Marquee_Messages
    (
        @Option tinyint
    )

AS

SET NOCOUNT ON

    IF @Option = 0    --Training Messages
        SELECT
            AW_Training_Messages_ID AS [ID], 
            Message AS [Message], 
            Source AS [Source], 
            Slu_AW_Active_ID AS [Active]
        FROM AW_Training_Messages
        ORDER BY Message

    ELSE
    IF @Option = 1    --Motivational Messages
        SELECT
            AW_Motivational_Messages_ID AS [ID], 
            Message AS [Message], 
            Source AS [Source], 
            Slu_AW_Active_ID AS [Active]
        FROM AW_Motivational_Messages
        ORDER BY Message



SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : sp_AW_Select_Modules_Per_User
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/07/24
--Authors       : Charl
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE  PROCEDURE sp_AW_Select_Modules_Per_User
(
	@User_ID int,
	@Company_ID int
)

AS
    SET NOCOUNT ON

SELECT M.Sys_AW_Modules_ID, 
	M.[Description],
	M.Module_Seq
FROM AW_Applications_Per_Role APR 
	INNER JOIN Sys_AW_Applications A 
		ON APR.Sys_AW_Applications_ID = A.Sys_AW_Applications_ID 
	INNER JOIN Sys_AW_Modules M 
		ON A.Sys_AW_Modules_ID = M.Sys_AW_Modules_ID 
	INNER JOIN AW_Users_Per_Role UR 
		ON APR.AW_Roles_ID = UR.AW_Roles_ID 
WHERE  (UR.AW_Users_ID = @User_ID AND
		UR.AW_User_Companies_ID = @Company_ID)
GROUP BY M.Sys_AW_Modules_ID ,M.[Description] ,M.Module_Seq
ORDER BY M.Sys_AW_Modules_ID,M.Module_Seq ASC






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--------------------------------------------------------------------------
--Description   :sp_AW_Select_Month_From_MonthID
--Purpose       :SELECT Slu_AW_Months.Description from MonthID
--Functionality :
--Parameters    : 
--Date          :2003/12/26
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Month_From_MonthID
	(
    	@MonthID tinyint,
        @MonthShort char(3) OUTPUT,
        @MonthLong varchar(10) OUTPUT
	)

AS

SET NOCOUNT ON


    SELECT @MonthShort = ISNULL([Description], ''),
           @MonthLong = ISNULL(Long_Description, '')
    FROM Slu_AW_Months
    WHERE Slu_AW_Months_ID = @MonthID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Non_Apps_Per_Role
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
--MODS          :15/10/02 - Select ONLY Applications WHERE Slu_AW_Active_ID = 1
-------------------------------------------------------------------------------
CREATE     PROCEDURE sp_AW_Select_Non_Apps_Per_Role
    (
    	@User_Role_ID smallint,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT DISTINCT
        A.Sys_AW_Applications_ID AS [ID],
        ISNULL(A.[Description], '') AS [Application],
        ISNULL(M.[Description], '') AS [Module],
        M.Module_Seq,
        A.Application_Seq
	FROM Sys_AW_Applications A
        LEFT JOIN Sys_AW_Modules M
            ON A.Sys_AW_Modules_ID = M.Sys_AW_Modules_ID
	WHERE A.Slu_AW_Active_ID = 1 AND
          A.Sys_AW_Applications_ID NOT IN
            (
                SELECT Sys_AW_Applications_ID
                FROM AW_Applications_Per_Role
                WHERE AW_Roles_ID = @User_Role_ID AND
                      AW_User_Companies_ID = @Company_ID
            )
	ORDER BY M.Module_Seq, A.Application_Seq, A.Sys_AW_Applications_ID ASC

SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Non_Users_Per_Role
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE       PROCEDURE sp_AW_Select_Non_Users_Per_Role
    (
    	@User_Role_ID smallint,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT AW_Users_ID,
        CASE WHEN FirstName IS NULL OR RTRIM(LTRIM(FirstName)) = ''
            THEN ISNULL(Surname, '')
            ELSE ISNULL(Surname, '') + ', ' + 
                 RTRIM(LTRIM(FirstName))
            END as [User]
	FROM AW_Users 
	WHERE AW_Users_ID NOT IN
            (
                SELECT AW_Users_ID
                FROM AW_Users_Per_Role
                WHERE AW_Roles_ID = @User_Role_ID AND
                      AW_User_Companies_ID = @Company_ID
            )AND
        AW_Users_ID > 0

SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Options_Log
--Purpose       :
--Date          :2009/05/20
--Authors       :TB
--Mods          :
--2015.6.2 RGL  :2015-11-12 - Removed txtNextCBFileNo - FTP file no - Clutters list
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_Options_Log]
	(
        @CompanyID int
	)

AS     

SET NOCOUNT ON

	SELECT a.Control_Type AS [Type],
           dbo.fn_AW_Split_String_To_Words(RTRIM(LTRIM(SUBSTRING(a.Control_Name, 4, (LEN(a.Control_Name) - 3))))) AS [Option],
           a.Control_Index AS [No],
           a.Control_Value AS [New Value],
           a.Date_Captured AS [Date Changed],
           ISNULL(u.FirstName + ' ', '') + ISNULL(u.Surname, '') AS [Changed by]
    FROM Sys_AW_Options_Log a
        LEFT JOIN AW_Users u
            ON u.AW_Users_ID = a.User_ID
    WHERE a.AW_User_Companies_ID = @CompanyID
    AND Control_Name <> 'txtNextCBFileNo'
    ORDER BY a.Date_Captured DESC


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











------------------------------------------------------------------------------
--Description   :sp_AW_Select_Period_Procedure_Date
--Purpose       :Retrieves selected Period Procedures Month_End_Date
--              :for Customer Statement Printing
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Period_Procedure_Date
	(
        @ProcedureID int
	)

AS

SET NOCOUNT ON

    SELECT Month_End_Date AS [PPDate]
    FROM AW_Period_Procedures 
    WHERE AW_Period_Procedures_ID = @ProcedureID


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AW_Select_Period_Procedure_List
--Purpose       :Retrieves list of Period Procedures in DESCENDING date order
--              :for Period Procedure
--Parameters    :
--Date          :2002/11/02
--Authors       :TB
--Version       :1.0.0
--MODS          :
--2004.2.9      :14/05/06 - Added Stock Valuation
--2004.3.4      :06/03/07 - Added Type 6 = Suppliers Month-End filter
--              :07/03/07 - Added [TypeID] for Procedure Delete
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_Period_Procedure_List
	(
        @CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT pp.AW_Period_Procedures_ID AS [ID],
           ISNULL(pt.[Description], '') AS [Type], 
           ISNULL(pp.[Description], '') AS [Description],
           m.[Description] AS [Month],
           y.[Description] AS [Year],
           pp.Month_End_Date AS [Procedure Date],
           pp.Stock_Valuation AS [Stock Valuation],
           pp.Date_Captured AS [Captured],
           ISNULL(u.FirstName + ' ', '') + ISNULL(Surname, '') AS [User],
           pp.Sys_AW_Period_Procedure_Types_ID AS [TypeID]
    FROM AW_Period_Procedures pp
        LEFT JOIN Sys_AW_Period_Procedure_Types pt
            ON pp.Sys_AW_Period_Procedure_Types_ID = pt.Sys_AW_Period_Procedure_Types_ID
        LEFT JOIN AW_Users u
            ON pp.[User_ID] = u.AW_Users_ID 
        LEFT JOIN Slu_AW_Months m
            ON pp.[Month] = m.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years y
            ON pp.[Year] = y.Slu_AW_Years_ID
    WHERE pp.AW_User_Companies_ID = @CompanyID AND
         (pp.Sys_AW_Period_Procedure_Types_ID = 1 OR
          pp.Sys_AW_Period_Procedure_Types_ID = 4 OR
          pp.Sys_AW_Period_Procedure_Types_ID = 6)
    ORDER BY pp.Date_Captured DESC

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_AW_Select_Period_Procedures
--Purpose       :Retrieves list of Period Procedures in DESCENDING date order
--              :for Customer Statement Printing
--Parameters    :
--Date          :2002/03/05
--Authors       :TB
--Version       :1.0.0
--MODS          :24/04/02 - Select AW_Period_Procedures_ID, not ..Types_ID
--              :07/08/02 - Select ONLY Period Procedure Type 1 (Customers)
--2004.3.4      :09/03/07 - Added @ProcedureTypeID input parameter for Supplier
--              :           Period Procedure
------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Period_Procedures
	(
        @ProcedureTypeID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT
        AW_Period_Procedures_ID AS [ID],
        Sys_AW_Period_Procedure_Types_ID AS [TypesID], 
        [Description] + ' (' + CONVERT(varchar(20), Date_Captured) + ')' AS [MonthEnd]
    FROM AW_Period_Procedures 
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Period_Procedure_Types_ID = @ProcedureTypeID
    ORDER BY Month_End_Date DESC

SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_AW_Select_Period_Procedures_Deleted
--Purpose       :Retrieves DELETED Period Procedures in DESCENDING date order
--Parameters    :
--Date          :2008/04/26
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AW_Select_Period_Procedures_Deleted
	(
        @CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON


    IF @Option = 1
        BEGIN
            SELECT pp.AW_Period_Procedures_Deleted_ID AS [ID],
                   ISNULL(pt.[Description], '') AS [Type], 
                   ISNULL(pp.[Description], '') AS [Description],
                   m.[Description] AS [Month],
                   y.[Description] AS [Year],
                   pp.Month_End_Date AS [Procedure Date],
                   pp.Date_Captured AS [Deleted],
                   ISNULL(u.FirstName + ' ', '') + ISNULL(Surname, '') AS [User],
                   pp.Year_End_Date AS [Year-End Date],
                   pp.Stock_Valuation AS [Stock Valuation],
                   pp.AW_Period_Procedures_ID AS [ProcID],
                   pp.Sys_AW_Period_Procedure_Types_ID AS [TypeID]
            FROM AW_Period_Procedures_Deleted pp
                LEFT JOIN Sys_AW_Period_Procedure_Types pt
                    ON pp.Sys_AW_Period_Procedure_Types_ID = pt.Sys_AW_Period_Procedure_Types_ID
                LEFT JOIN AW_Users u
                    ON pp.[User_ID] = u.AW_Users_ID 
                LEFT JOIN Slu_AW_Months m
                    ON pp.Month_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON pp.Year_ID = y.Slu_AW_Years_ID
            WHERE pp.AW_User_Companies_ID = @CompanyID AND
                  pp.Sys_AW_Period_Procedure_Types_ID = 1 OR
                  pp.Sys_AW_Period_Procedure_Types_ID = 6
            ORDER BY pp.Date_Captured DESC
        END


    ELSE
    IF @Option = 2
        BEGIN
            SELECT pp.AW_Period_Procedures_Deleted_ID AS [ID],
                   ISNULL(pt.[Description], '') AS [Type], 
                   ISNULL(pp.[Description], '') AS [Description],
                   m.[Description] AS [Month],
                   y.[Description] AS [Year],
                   pp.Month_End_Date AS [Procedure Date],
                   pp.Date_Captured AS [Deleted],
                   ISNULL(u.FirstName + ' ', '') + ISNULL(Surname, '') AS [User],
                   pp.Year_End_Date AS [Year-End Date],
                   pp.Stock_Valuation AS [Stock Valuation],
                   pp.AW_Period_Procedures_ID AS [ProcID],
                   pp.Sys_AW_Period_Procedure_Types_ID AS [TypeID]
            FROM AW_Period_Procedures_Deleted pp
                LEFT JOIN Sys_AW_Period_Procedure_Types pt
                    ON pp.Sys_AW_Period_Procedure_Types_ID = pt.Sys_AW_Period_Procedure_Types_ID
                LEFT JOIN AW_Users u
                    ON pp.[User_ID] = u.AW_Users_ID 
                LEFT JOIN Slu_AW_Months m
                    ON pp.Month_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON pp.Year_ID = y.Slu_AW_Years_ID
            WHERE pp.AW_User_Companies_ID = @CompanyID AND
                  pp.Sys_AW_Period_Procedure_Types_ID = 5
            ORDER BY pp.Date_Captured DESC
        END


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Access
--Purpose       :Retrieves the Network Catalog data
--Date          :2003/09/15
--Authors       :TB
--Version       :2004
--MODS          :16/09/03 - Changed 'UseDSN' to 'Default_Connection'
--              :23/09/03 - Added Trusted_Connection field
--              :12/10/03 - Added Network_Identity (from AW_User_Companies)
--              :12/10/03 - Added Billing and Delivery Addresses
--              :04/11/03 - Added Billing Tel-, Fax-, VAT- & RegNo
----------------------------------------------------------------------------

CREATE                    PROCEDURE sp_AW_Select_Remote_Access
    (
        @RemoteID int,
        @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        AW_Remote_Access_ID AS [ID], 
        NodeName AS [NodeName], 
        Network_Identity AS [NetworkIdentity], 
        WinUserName AS [WinUserName], 
        WinPassword AS [WinPassword], 
        Trusted_Connection AS [TrustedConn],
        DataServName AS [DataServName], 
        DataServIP1 AS [DataServIP1], 
        DataServIP2 AS [DataServIP2], 
        DataServIP3 AS [DataServIP3], 
        DataServIP4 AS [DataServIP4], 
        DBUserName AS [DBUserName], 
        DBPassword AS [DBPassword], 
        DBCatalog AS [DBCatalog], 
        WebServName AS [WebServName], 
        WebServIP1 AS [WebServIP1], 
        WebServIP2 AS [WebServIP2], 
        WebServIP3 AS [WebServIP3], 
        WebServIP4 AS [WebServIP4], 
        WebSiteURL AS [WebSiteURL], 
        DSNName AS [DSNName],
        Default_Connection AS [DefaultCN],
        Port AS [Port], 
        WebServURL AS [WebServURL], 
        Slu_AW_Countries_ID AS [Country], 
        Area_Code AS [AreaCode], 
        Modem_Tel_No AS [ModemTelNo], 
        Email AS [Email], 
        SQLQuery AS [SQLQuery], 
        Billing_Name AS [BillName], 
        Billing_Address1 AS [BillAddress1], 
        Billing_Address2 AS [BillAddress2], 
        Billing_Address3 AS [BillAddress3], 
        Billing_Post_Code AS [BillPostCode], 
        Billing_TelNo AS [BillTelNo], 
        Billing_FaxNo AS [BillFaxNo], 
        Billing_VATNo AS [BillVATNo], 
        Billing_RegNo AS [BillRegNo], 
        Delivery_Name AS [DelName], 
        Delivery_Address1 AS [DelAddress1], 
        Delivery_Address2 AS [DelAddress2], 
        Delivery_Address3 AS [DelAddress3], 
        Delivery_Post_Code AS [DelPostCode], 
        Date_Captured AS [Date Captured], 
        [User_ID] AS [UserID], 
        AW_User_Companies_ID AS [CompanyID],
        Slu_AW_Active_ID AS [Active]
	FROM AW_Remote_Access 
	WHERE AW_Remote_Access_ID = @RemoteID AND
	      AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Access_Lups
--Date          :2003/09/14
--Authors       :TB
--Version       :2004
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Remote_Access_Lups
    (
       	@Choice int,
    	@CompanyID int
    )

AS

BEGIN

    IF @Choice = 1	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],  Description  	
        FROM Slu_AW_YesNo

    ELSE
    IF @Choice = 2	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID], Description 
        FROM Slu_AW_Active 

    ELSE
    IF @Choice = 3	--'Countries'
        SELECT Slu_AW_Countries_ID AS [ID], Description 
        FROM Slu_AW_Countries


END   





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Access_PickList
--Date          :2003/09/15
--Authors       :TB
--MODS          :
--2004.4.1      :19/10/08 - Replaced [Modem] with [Server]
------------------------------------------------------------------------------

CREATE              Procedure sp_AW_Select_Remote_Access_PickList
    (
    	@CompanyID int
    )

AS

SET NOCOUNT ON
	
	SELECT AW_Remote_Access_ID AS [ID],
		   ISNULL(NodeName, '') AS [Network Node],
           ISNULL(DataServName, '') as [Server]
	FROM AW_Remote_Access a
	WHERE AW_User_Companies_ID = @CompanyID
	ORDER BY [Network Node]


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















----------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Sites
--Purpose       :Retrieves Remote Sites for Distributed Login
--Date          :2008/09/11
--Authors       :TB
--MODS          :
--2004.4.8      :08/06/10 - Added Area_Code AS [Timeout]
--              :23/06/10 - Added Trusted_Connection AS [LoginEnabled]
----------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_Remote_Sites
    (
        @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT AW_Remote_Access_ID AS [ID], 
           NodeName AS [NodeName], 
           Network_Identity AS [Identifier],
           Default_Connection AS [LocalHost],
           DataServName AS [ServerName], 
           DataServIP1 AS [ServerIP], 
           DBUserName AS [DBUserName], 
           DBPassword AS [DBPassword], 
           DBCatalog AS [DBCatalog], 
           Area_Code AS [Timeout],
           Trusted_Connection AS [LoginEnabled],
           Slu_AW_Active_ID AS [Active]
	FROM AW_Remote_Access 
	WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1
    ORDER BY [ServerName], [DBCatalog]


SET NOCOUNT OFF






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Sites_IP
--Purpose       :Retrieves Remote Sites Data Server and Instance Names
--Date          :2016-10-04
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_Remote_Sites_IP]
    (
		@NodeName  varchar(30),
        @CompanyID int,
        @ServerIP  varchar(250) OUTPUT 
    )

AS

SET NOCOUNT ON

	SELECT @ServerIP = DataServName + ISNULL(DataServIP1,'')
	FROM AW_Remote_Access 
	WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          NodeName = @NodeName

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Company_Catalog
--Purpose       :Select System Reports from the Reports Library
--Date          :2009/05/14
--Authors       :TB
--MODS          :
--2004.4.8      :02/10/09 - Added ORDER BY Report_No
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_AW_Select_Reports_Library
    (
        @ReportModule varchar(50),
        @TypeID tinyint,
        @Option tinyint
    )

AS

SET NOCOUNT ON

    IF @Option = 0       -- Report Module Library
        BEGIN
            SELECT
                Sys_AW_Reports_ID AS [ID], 
                Sys_AW_Modules_ID AS [ModuleID], 
                Type_ID AS [TypeID],
                Location AS [Location], 
                Report_No AS [Report], 
                Report_Name AS [Report Name], 
                Description AS [User Description], 
                Object_DLL AS [ObjectDLL], 
                Class_Name AS [ClassName], 
                Method_Name AS [MethodName]
            FROM Sys_AW_Reports
            WHERE Location = @ReportModule AND
                  Type_ID = @TypeID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Report_No
        END

    ELSE
    IF @Option = 1        -- Full Reports Library
        BEGIN
            SELECT
                Sys_AW_Reports_ID AS [ID], 
                Sys_AW_Modules_ID AS [ModuleID], 
                Type_ID AS [TypeID],
                Location AS [Location], 
                Report_No AS [Report], 
                Report_Name AS [Report Name], 
                Description AS [User Description], 
                Object_DLL AS [ObjectDLL], 
                Class_Name AS [ClassName], 
                Method_Name AS [MethodName]
            FROM Sys_AW_Reports
            WHERE Type_ID = @TypeID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Report_No
        END
          


SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Roles
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE    PROCEDURE sp_AW_Select_Roles
(
	@Choice tinyint,
	@Company_ID int,
	@AW_Roles_ID int = 0
)

AS

SET NOCOUNT ON

--> 1 = Picklist
	IF @Choice = 1
		SELECT AW_Roles_ID AS [ID],
            [Description],
            Editable 
		FROM AW_Roles		
		WHERE AW_User_Companies_ID = @Company_ID AND
              AW_Roles_ID > 1
    	
--> 2 = Active Lup
	ELSE
	IF @Choice = 2
		SELECT Slu_AW_Active_ID AS [ID],
			[Description] AS Status
		FROM Slu_AW_Active
    
--> 3 = Role Details
	ELSE
	IF @Choice = 3
		SELECT AW_Roles_ID AS [ID],
			[Description],
			Editable,
			Notes,
			Slu_AW_Active_ID AS [Status]
		FROM AW_Roles		
		WHERE AW_Roles_ID = @AW_Roles_ID AND
              AW_User_Companies_ID = @Company_ID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Top_Remote_Access_ID
--Purpose       :Select FIRST ot LAST Remote_Access_ID
--Date          :2003/09/15
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Top_Remote_Access_ID
	(
    	@CompanyID int,
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AW_Remote_Access_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AW_Remote_Access_ID
            FROM AW_Remote_Access
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AW_Remote_Access_ID
        END

    ELSE

--> Get the LAST AW_Remote_Access_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AW_Remote_Access_ID
            FROM AW_Remote_Access
            WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY AW_Remote_Access_ID DESC
        END

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Top_User_ID
--Purpose       :Select FIRST ot LAST User ID
--Functionality :
--Date          :2010/05/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_Top_User_ID
	(
        @Option tinyint
	)

AS

SET NOCOUNT ON

--> Get the FIRST AW_Users_ID
    IF @Option = 0    
        BEGIN
            SELECT TOP 1 AW_Users_ID
            FROM AW_Users
            ORDER BY AW_Users_ID
        END

    ELSE

--> Get the LAST AW_Users_ID
    IF @Option = 1
        BEGIN
            SELECT TOP 1 AW_Users_ID
            FROM AW_Users
            ORDER BY AW_Users_ID DESC
        END

SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Training_Messages
--Purpose       :
--Date          :2008/01/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Select_Training_Messages
    (
        @MsgType int = 2
    )

AS

SET NOCOUNT ON

    IF @MsgType = 1
        BEGIN
            SELECT ISNULL(Message, ''),
                   ISNULL(Source, '')
            FROM AW_Training_Messages
            WHERE Slu_AW_Active_ID = 1
        END

    ELSE
    IF @MsgType = 2
        BEGIN
            SELECT ISNULL(Message, ''),
                   ISNULL(Source, '')
            FROM AW_Motivational_Messages
            WHERE Slu_AW_Active_ID = 1
        END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Accountant_Status
--Purpose       :Select if User = Accountant
--Parameters    :
--Date          :2005/09/22
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_AW_Select_User_Accountant_Status
	(
        @UserID int,
		@Accountant tinyint OUTPUT
	)

AS

	SELECT @Accountant = IsAccountant
	FROM AW_Users
    WHERE AW_Users_ID = @UserID

	IF @Accountant IS NULL 
        BEGIN	
    		SET @Accountant = 0 
        END
		








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_CRM_Status
--Purpose       :Select if User = CRM
--Parameters    :
--Date          :2004/07/13
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Select_User_CRM_Status
	(
        @UserID int,
		@CRM tinyint OUTPUT
	)

AS

    SET @CRM = 0

	SELECT @CRM = IsCRM
	FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @CRM IS NULL 
        BEGIN	
    		SET @CRM = 0 
        END
		










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Catalog
--Date          :2001/11/17
--Authors       :TB
--MODS          :02/10/02 - Added IsCashier & IsSupervisor
--              :20/12/03 - Added IsDBAdmin
--              :03/01/03 - Added IsAdministrator, IsController
--              :22/09/05 - Added IsAccountant
--2004.3.7      :12/09/07 - Added IsDataExporter
--2004.3.8      :30/04/08 - Added IsProcurementSupervisor
--2004.5.7 RGL  :2012-10-26 - Added IsLevyController
--2004.5.9 RGL  :2013-07-15 - Added IsRecordsManager
--2015.6.2 RGL  :2015-11-12 - Added Product Bins
--2015.6.3 RGL  :2017-09-11 - Added Till Payout
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Select_User_Catalog]
    (
    	@User_ID int    )

AS

SET NOCOUNT ON

    SELECT AW_Users_ID AS [ID], 
    	Surname AS [Surname], 
    	FirstName AS [First Name], 
    	UserName AS [User Name], 
    	[Password] AS [Password], 
    	User_Home_Tel_Number AS [Home Tel No], 
        User_Cell_Number AS [Cell No], 
    	User_Email AS [E-mail Address], 
    	Activation_Date AS [Activation Date], 
    	Deactivation_Date AS [Deactivation Date], 
    	Unsuccessful_Logins AS [Unsuccessful Logins], 
    	Sys_AW_Applications_ID AS [Applications],
        Slu_AW_Active_ID AS [Active],
        IsCashier AS [IsCashier],
        IsSupervisor AS [IsSupervisor],
        IsDBAdmin AS [IsDBAdmin],
        IsCRM AS [IsCRM],
        IsController AS [IsController],
        Sys_AW_Delivery_Methods_ID AS [Delivery Method],
        IsAccountant AS [IsAccountant],
        IsDataExporter AS [IsDataExporter],
        IsProcurementSupervisor AS [IsProcureSuper],
        IsLevyController AS [IsLevyCont],
        IsRecordsManager AS [IsRecordsManager],
        Lup_AP_Product_Bins_ID AS [ProductBins],
        IsBinSuper AS [IsBinSuper],
        IsTillPayout AS [IsTillPayout]
    FROM AW_Users 
    WHERE AW_Users_ID = @User_ID

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Catalog_PickList
--Date          :2002/04/04
--Authors       :TB
--Version       :
--2004.4.5      :18/07/09 - Added ORDER BY [User] !!!
-------------------------------------------------------------------------------
CREATE     PROCEDURE sp_AW_Select_User_Catalog_PickList

AS

SET NOCOUNT ON

    SELECT AW_Users_ID AS [ID], 
        CASE WHEN FirstName IS NULL OR RTRIM(LTRIM(FirstName)) = ''
            THEN ISNULL(Surname, '')
            ELSE ISNULL(Surname, '') + ', ' + 
                 RTRIM(LTRIM(FirstName))
            END as [User]
    FROM AW_Users 
    WHERE AW_Users_ID > 0 
    ORDER BY [User]





SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Controller_Status
--Purpose       :Select if User = Controller
--Parameters    :
--Date          :2004/07/13
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_User_Controller_Status
	(
        @UserID int,
		@Controller tinyint OUTPUT
	)

AS

    SET @Controller = 0

	SELECT @Controller = IsController
	FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @Controller IS NULL 
        BEGIN	
    		SET @Controller = 0 
        END
		









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_DBAdmin_Status
--Purpose       :Select if User = DBAdmin
--Parameters    :
--Date          :2003/12/19
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_User_DBAdmin_Status
	(
        @UserID int,
		@DBAdmin tinyint OUTPUT
	)

AS

    SET @DBAdmin = 0

	SELECT @DBAdmin = IsDBAdmin
	FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @DBAdmin IS NULL 
        BEGIN	
    		SET @DBAdmin = 0 
        END
		









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_DataExport_Status
--Purpose       :Select if User = Data Exporter
--Parameters    :
--Date          :2007/09/12
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Select_User_DataExport_Status
	(
        @UserID int,
		@DataExport tinyint OUTPUT
	)

AS

    SET @DataExport = 0

	SELECT @DataExport = IsDataExporter
	FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @DataExport IS NULL 
        BEGIN	
    		SET @DataExport = 0 
        END
		










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Default_Bin
--Purpose       :Select Users default product bin
--Parameters    :
--Date          :2015-11-20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_User_Default_Bin]
	(
        @UserID int,
		@ProductBin int OUTPUT
	)

AS

    SET @ProductBin = 0

	SELECT @ProductBin = Lup_AP_Product_Bins_ID
	FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @ProductBin IS NULL 
        BEGIN	
    		SET @ProductBin = 0 
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Lups
--Purpose       :User Catalog Lups
--Functionality : 
--Parameters    : 
--Date          :2001/11/17
--Authors       :TB
--MODS          :27/09/02 - Added ORDER BY Description for Applications LUP
--              :           and reversed User FirstName, Surname order
--              :02/10/02 - Added IsCashier & IsSupervisor as Choice 5 & 6
--              :25/07/03 - Option 3: Select ONLY ACTIVE Applications
--              :03/01/04 - Added IsDBAdmin, IsCRM, IsController, Delivery Methods
--              :           as Choice 7, 8, 9 & 10 for Credit Manager
--              :22/09/05 - Added IsAccountant as Choice 11
--2004.3.7      :12/09/07 - Added IsDataExporter as Choice 12
--2004.3.8      :30/04/08 - Added IsProcurementSupervisor as Choice 13
--2004.5.7 RGL  :2012-10-26 - Added IsLevyController as Choice 14
--2015.6.2 RGL  :2015-11-12 - Added Product Bins as Choice 16
--2015.6.3 RGL  :2017-09-11 - Added Till Payout as Choice 18
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Select_User_Lups]
    (
    	@Choice int
    )
AS

SET NOCOUNT ON

    BEGIN 
    	--> Active
    	IF @Choice = 1 
    		SELECT Slu_AW_Active_ID AS [ID], 
    			[Description] AS [Active] 
    		FROM Slu_AW_Active
    
    	--> User Companies
    	ELSE
    	IF @Choice = 2
    		SELECT AW_User_Companies_ID AS [ID], 
    			Company_Name AS [Company] 
    		FROM AW_User_Companies
    
    	--> Applications
    	ELSE 
    	IF @Choice = 3
    		SELECT Sys_AW_Applications_ID AS [ID],
    			[Description] AS [Applications]
    		FROM Sys_AW_Applications
            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    	--> Users
    	ELSE 
    	IF @Choice = 4
    		SELECT AW_Users_ID AS [ID],
    			    ISNULL(Surname, '') + ISNULL(' ' + FirstName, '') AS [User]
    		FROM AW_Users 
    		WHERE AW_Users_ID <> -1
    		ORDER BY Surname, FirstName
    
    	--> IsCashiers
    	ELSE 
    	IF @Choice = 5
    		SELECT Slu_AW_YesNo_ID AS [ID],
                   ISNULL(Description, '') AS [Cashier]
    		FROM Slu_AW_YesNo 
    
    	--> IsSupervisor
    	ELSE 
    	IF @Choice = 6
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Supervisor]
    		FROM Slu_AW_YesNo 

    	--> IsDBAdmin
    	ELSE 
    	IF @Choice = 7
    		SELECT Slu_AW_YesNo_ID AS [ID],
                   ISNULL(Description, '') AS [DBAdmin]
    		FROM Slu_AW_YesNo 
    
    	--> IsCRM
    	ELSE 
    	IF @Choice = 8
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [CRM]
    		FROM Slu_AW_YesNo 
    
    	--> IsCreditController
    	ELSE 
    	IF @Choice = 9
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Controller]
    		FROM Slu_AW_YesNo 

        --> Delivery Methods
        ELSE
        IF @Choice = 10
          	SELECT Sys_AW_Delivery_Methods_ID as [ID],
                   ISNULL(Description, '') AS [Description]
            FROM Sys_AW_Delivery_Methods 

        --> IsAccountant
        ELSE
        IF @Choice = 11
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Accountant]
    		FROM Slu_AW_YesNo 

        --> IsDataExporter
        ELSE
        IF @Choice = 12
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [DataExport]
    		FROM Slu_AW_YesNo 

        --> IsProcurementSupervisor
        ELSE
        IF @Choice = 13
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [ProcureSuper]
    		FROM Slu_AW_YesNo
    		 
		--> IsLevyController
        ELSE
        IF @Choice = 14
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [LevyCont]
    		FROM Slu_AW_YesNo     		
		--> IsRecordManager
        ELSE
        IF @Choice = 15
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [RecordsManager]
    		FROM Slu_AW_YesNo     		

        ELSE
        IF @Choice = 16
    		SELECT Lup_AP_Product_Bins_ID AS [ID],
    			   ISNULL([Description], '') AS [ProductBins]
    		FROM Lup_AP_Product_Bins     		
        ELSE
        --> IsBinSuper
        IF @Choice = 17
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [BinSuper]
    		FROM Slu_AW_YesNo     		
        ELSE
        --> IsTillPayout
        IF @Choice = 18
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [TillPayout]
    		FROM Slu_AW_YesNo     		

    END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







--Description   : sp_AW_Select_User_Roles
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          : 2001/07/20
--Authors       : Charl
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE   PROCEDURE sp_AW_Select_User_Roles
(
	@User_Role_Key smallint,
	@Company_ID int
)

AS
    SET NOCOUNT ON
	SELECT AW_User_Roles_ID AS [ID],
		[Description] ,
		User_Role_Key,
		Notes,
		Slu_AW_Active_ID AS [Status]
	FROM AW_User_Roles		
	WHERE User_Role_Key = @User_Role_Key AND
		AW_User_Companies_ID = @Company_ID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Users
--Purpose       :Select Users and Company Users
--              :
--Tables        :AW_Users, AW_Company_Users, AW_User_Companies
--Parameters    :
--Date          :2002/02/21
--Authors       :TB
--MODS          :08/09/02 - Added 'Trading Name' for SMS and eMail CComms
--2004.4.8      :Added check validation on ACTIVE users only
--V6.4		RL	:2018-02-14 - Return User Email
-------------------------------------------------------------------------------


CREATE Procedure [dbo].[sp_AW_Select_Users]

AS

SET NOCOUNT ON

    SELECT
        U.AW_Users_ID AS [User ID],
        U.UserName AS [User Name],
        U.Password AS [Password],
        U.Surname AS Surname,
        U.FirstName AS [First Name], 
        U.Slu_AW_Active_ID AS [Active User],
        UC.AW_User_Companies_ID AS [Company ID], 
        UC.Company_Name AS [Company Name],
        U.Sys_AW_Applications_ID AS [Applications],
        UC.Company_Trading_Name AS [Trading Name],
        ISNULL(U.User_Email,'') AS [User Email]
    FROM AW_Users U
        INNER JOIN dbo.AW_Company_Users CU
        	ON U.AW_Users_ID = CU.AW_Users_ID 
        INNER JOIN dbo.AW_User_Companies UC 
        	ON CU.AW_User_Companies_ID = UC.AW_User_Companies_ID
--     WHERE CU.Slu_AW_Active_ID <> 0 AND
--           UC.Slu_AW_Active_ID <> 0
    WHERE U.Slu_AW_Active_ID = 1
    ORDER BY UC.Yes_No_Default_Company DESC, UC.Company_Name

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Roles
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/04/04
--Authors       :TB
--Version       :1.0.0
-------------------------------------------------------------------------------
CREATE        PROCEDURE sp_AW_Select_Users_Per_Role
    (
    	@User_Role_ID smallint,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

	SELECT DISTINCT UPR.AW_Users_ID,
        CASE WHEN U.FirstName IS NULL OR RTRIM(LTRIM(U.FirstName)) = ''
            THEN ISNULL(U.Surname, '')
            ELSE ISNULL(U.Surname, '') + ', ' + 
                 RTRIM(LTRIM(U.FirstName))
            END as [User]
	FROM AW_Users_Per_Role UPR
        LEFT JOIN AW_Users U
        	ON UPR.AW_Users_ID = U.AW_Users_ID
	WHERE UPR.AW_Roles_ID = @User_Role_ID AND
          UPR.AW_User_Companies_ID = @Company_ID AND
          U.AW_Users_ID > 0

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Users_W
--Purpose       :Select a User's Companies
--              :
--Tables        :AW_Users, AW_Company_Users, AW_User_Companies
--Parameters    :
--Date          :2003/09/01
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------


CREATE            Procedure sp_AW_Select_Users_W
    (
        @Username varchar(20),
        @Password varchar(20)
    )

AS

SET NOCOUNT ON

    SELECT
        u.AW_Users_ID AS [UserID],
        ISNULL(u.FirstName + ' ', '') + ISNULL(u.Surname, '') AS [Fullname],
        uc.AW_User_Companies_ID AS [CompanyID], 
        uc.Company_Name AS [CompanyName],
        u.Sys_AW_Applications_ID AS [Application],
        uc.Company_Trading_Name AS [TradingName]
    FROM AW_Users u
        INNER JOIN AW_Company_Users cu
        	ON U.AW_Users_ID = CU.AW_Users_ID 
        INNER JOIN dbo.AW_User_Companies uc 
        	ON cu.AW_User_Companies_ID = uc.AW_User_Companies_ID
    WHERE u.UserName = @Username AND
          u.Password = @Password AND
          cu.Slu_AW_Active_ID = 1 AND
          uc.Slu_AW_Active_ID = 1 
    ORDER BY uc.Company_Name

SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--------------------------------------------------------------------------
--Description   :sp_AW_Select_YearID_From_Year
--Purpose       :SELECT Slu_AW_Years_ID from YEAR(NOW)
--Functionality :
--Parameters    : 
--Date          :2002/10/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
--------------------------------------------------------------------------

CREATE         PROCEDURE sp_AW_Select_YearID_From_Year
	(
    	@Year int,
        @YearID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @YearID = 0

    SELECT @YearID = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = CONVERT(varchar(10), @Year)

SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_AW_Select_Year_End_Procedure_List
--Purpose       :Retrieves list of Year-End Period Procedures in DESCENDING
--              :date order for Period Procedure
--Date          :2004/03/14
--Authors       :TB
--MODS          :
--2004.4.8      :15/07/10 - Changed ORDER By to [Procedure Date] to display in
--              :           correct descending order if performed in quick succession
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Select_Year_End_Procedure_List
	(
        @CompanyID int
	)

AS

SET NOCOUNT ON

    SELECT pp.AW_Period_Procedures_ID AS [ID],
           ISNULL(pt.[Description], '') AS [Type], 
           ISNULL(pp.[Description], '') AS [Description],
           m.[Description] AS [Month],
           y.[Description] AS [Year],
           pp.Month_End_Date AS [Procedure Date],
           pp.Date_Captured AS [Captured],
           ISNULL(u.FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
    FROM AW_Period_Procedures pp
        LEFT JOIN Sys_AW_Period_Procedure_Types pt
            ON pp.Sys_AW_Period_Procedure_Types_ID = pt.Sys_AW_Period_Procedure_Types_ID
        LEFT JOIN AW_Users u
            ON pp.[User_ID] = u.AW_Users_ID 
        LEFT JOIN Slu_AW_Months m
            ON pp.[Month] = m.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years y
            ON pp.[Year] = y.Slu_AW_Years_ID
    WHERE pp.AW_User_Companies_ID = @CompanyID AND
          pp.Sys_AW_Period_Procedure_Types_ID = 5
    ORDER BY [Procedure Date] DESC

SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















--------------------------------------------------------------------------
--Description   :sp_AW_Select_Year_From_YearID
--Purpose       :SELECT Year from a YearID
--Date          :2007/03/09
--Authors       :TB
--MODS          :
--------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Select_Year_From_YearID
	(
        @YearID int,
    	@Year int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @Year = 1899

    SELECT @Year = [Description]
    FROM Slu_AW_Years
    WHERE Slu_AW_Years_ID = @YearID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















----------------------------------------------------------------------------
--Description   :sp_AW_Set_SP_Account_ID
--Date          :2009/03/31
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_AW_Set_SP_Account_ID
   (        
        @CompanyID int,
        @AccountID int
    )

AS


SET NOCOUNT OFF

    UPDATE AW_User_Companies
    SET Sp_Account_ID = @AccountID
    WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















----------------------------------------------------------------------------
--Description   :sp_AW_Set_SP_Web_Password
--Date          :2010/01/16
--Authors       :TB
--MODS          :
----------------------------------------------------------------------------

CREATE              PROCEDURE sp_AW_Set_SP_Web_Password
   (        
        @CompanyID int,
        @WebPW varchar(20)
    )

AS


SET NOCOUNT OFF

    UPDATE AW_User_Companies
    SET Sp_Web_Password = @WebPW
    WHERE AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE Procedure sp_AW_TableIsFullTextEnabled 
(
	@TableName varchar(100)
)
AS
	declare @IsFT tinyint
	SET @IsFT = OBJECTPROPERTY(OBJECT_ID(@TableName),'TableHasActiveFulltextIndex')
	IF @IsFT = 1
		Print 'Yip'
	else
		print 'Nope'







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AW_TableRowsCount_Cursor
--Purpose       :Counts the rows in each database table
--Parameters    :
--Date          :2003/04/21
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_TableRowsCount_Cursor

AS


    DECLARE TableRowsCount_Cursor CURSOR FOR
                                (
                                    SELECT TABLE_NAME 
                                    FROM INFORMATION_SCHEMA.TABLES
                                    WHERE TABLE_TYPE = 'BASE TABLE'
                                )

    OPEN TableRowsCount_Cursor
    
    DECLARE @tablename sysname
    --SET @tablename = 'AB_Transactions'
    
    FETCH NEXT FROM TableRowsCount_Cursor
    INTO @tablename
    
    WHILE (@@FETCH_STATUS <> -1)
        BEGIN
            IF (@@FETCH_STATUS <> -2)
                BEGIN   
                    SELECT @tablename = RTRIM(@tablename) 

                    EXEC ('SELECT ''' + @tablename + ''' = COUNT(*) FROM ' 
                           + @tablename )

                    PRINT ' '
                END

                FETCH NEXT FROM TableRowsCount_Cursor
                INTO @tablename
        END
    
    CLOSE TableRowsCount_Cursor
    
    DEALLOCATE TableRowsCount_Cursor







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_AW_Tills_Per_User_Select
--Purpose       :Select Tills per User
--              :
--Tables        :AW_Users, AW_Users_Per_Role, AW_Users_Tills
--Parameters    :
--Date          :2002/02/21
--Authors       :TB
--MODS:         :13/01/04 - Replaced join with AW_Users_Per_Role (Cashier role)
--              :           with using the IsCashier flag in AW_Users
--2004.5.8 RGL  :Changed Order of result set to user name
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Tills_Per_User_Select]
	(
		@Choice int,
		@CompanyID int
	)
AS

SET NOCOUNT ON

	IF @Choice = 1
		SELECT
            Lup_AS_Tills_ID AS [ID],
            [Description] AS [Till] 
		FROM Lup_AS_Tills
		WHERE AW_User_Companies_ID = @CompanyID

	ELSE
	IF @Choice = 2
		SELECT DISTINCT
            u.AW_Users_ID AS [ID],
            ISNULL(ISNULL(u.Surname,'') + ISNULL(', ' + u.Firstname,''),'') AS [User] 
		FROM AW_Users u
        WHERE u.AW_Users_ID > 0 AND
              u.IsCashier = 1
        ORDER BY [User]

	ELSE
	IF @Choice = 3
		SELECT
			t.AW_Users_Tills_ID AS [ID], 
			t.AW_Users_ID AS [User], 
			t.Lup_AS_Tills_ID AS [Till],
			t.AW_User_Companies_ID AS [CompanyID],
			t.[User_ID] AS [UserID],
			ISNULL(ISNULL(u.Surname,'') + ISNULL(', ' + u.Firstname,''),'') AS [User2] 
		FROM AW_Users_Tills t
		INNER JOIN AW_Users u
			ON t.AW_Users_ID = u.AW_Users_ID
		WHERE t.AW_User_Companies_ID = @CompanyID
		ORDER BY [User2]


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE  PROCEDURE sp_AW_Transaction_Detail_Described 
	(@TransactionID int)
AS
SELECT     
		td.AS_Transaction_Details_ID AS ID, 
		td.AS_Transactions_ID AS FKID, 
		p.Description AS [Product              ], 
		p.Product_Code AS [Code   ], 
		td.Quantity AS Qty, td.Unit_Cost AS Cost, 
		td.Unit_Price AS Price, 
		td.Original_Price AS [Original Price], 
		td.Discount_Amount AS Discount, 
		td.Tax_Amount AS Tax, 
		td.Extended_Amount AS Total, 
		td.Commission_Amount AS Commission
FROM         dbo.AS_Transaction_Details td LEFT JOIN
                      dbo.AP_Products p ON td.AP_Products_ID = p.AP_Products_ID
WHERE td.AS_Transactions_ID = @TransactionID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










CREATE     PROCEDURE sp_AW_Transaction_Header_Described 
	(@TransactionID int)
AS
	SELECT    
		t.AS_Transactions_ID AS ID, 
		c.Surname + ISNULL(', ' + c.Firstnames, '') AS [Customer        ], 
		t.Transaction_Number AS [Trans No], 
             t.Total_Cost AS [Cost   ], 
		t.Amount, 
		t.Total_Tax_Amount AS [Tax     ], 
		t.Total_Discount_Amount AS Discount, 
		t.Total_Amount AS [Total     ], 
		t.Payment_Amount AS Payment, 
		t.Transaction_Date AS [Date    ], 
		t.Customer_Reference AS [Customer Ref], t.Comment,
		a.Description AS Account
FROM         dbo.AS_Transactions t LEFT JOIN
                      dbo.AC_Customers c ON t.AC_Customers_ID = c.AC_Customers_ID LEFT JOIN
                      dbo.AB_Accounts a ON t.AB_Accounts_ID = a.AB_Accounts_ID
WHERE t.AS_Transactions_ID = @TransactionID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description   :sp_AW_Transaction_Numbers_Select
--Purpose       :Select GL Transaction Numbers
--Date          :2006/01/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_AW_Transaction_Numbers_Select
	(
		@CompanyID int
	)

AS

	SELECT
		Sys_AW_Transaction_Numbers_ID as ID,
		Sys_AW_Transaction_Types_ID as TransactionType,
		Last_Number as [Last Number],
		Number_Suffix as Suffix
	FROM Sys_AW_Transaction_Numbers
	WHERE AW_User_Companies_ID = @CompanyID









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







-------------------------------------------------------------------------------
--Description   :sp_AW_Transaction_Types_Select
--Purpose       :Select GL Transaction Types
--Date          :2006/01/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_AW_Transaction_Types_Select

AS

	SELECT 
		Sys_AW_Transaction_Types_ID as [ID],
		Description,
		Type_code as [Code]
	FROM Sys_AW_Transaction_Types






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE PROC sp_AW_User_Companies_Subset

(
        @CompanyID int = 1
)

AS

SELECT
	a.Company_Name AS [Company Name],
	a.AW_User_Companies_ID AS [Company Number],
	a.Company_Trading_Name AS [Trading Name],
	a.Company_Registration_Number AS [Registration Number],
	a.Company_Year_End_Month AS [Year-End Month],
             	a.Company_Month_End_Day AS [Month-End Day],
	b.Description AS [Year-End Month]

FROM AW_User_Companies a INNER JOIN Lup_AB_Year_End_Month b
        ON a.Company_Year_End_Month = b.Lup_AB_Year_End_Month_ID

WHERE a.AW_User_Companies_ID = @CompanyID

 






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






--Description   : Used in the Day End 
--Date          : 2001/09/18
--Authors       : GL
--Version       : 1
-------------------------------------------------------------------------------
CREATE  PROCEDURE  sp_Current_AS_Transaction_Details
	(
		@TransactionID int
	)
AS
SELECT     
	ISNULL(p.Description,'') AS Product, 
	ISNULL(p.Product_Code,'') AS Code, 
	ISNULL(td.Quantity,0) AS Qty, 
	ISNULL(td.Unit_Cost,0) AS Cost, 
	ISNULL(td.Unit_Price,0) AS Price, 
       ISNULL(td.Original_Price,0) AS [Original Price], 
	ISNULL(td.Original_Discount,0) AS [Original Discount], 
	ISNULL(td.Discount_Amount,0) AS Discount, 
	ISNULL(td.Tax_Amount,0) AS Tax, 
       ISNULL(td.Extended_Amount,0) AS Amount, 
	ISNULL(td.Commission_Amount,0) AS Commission, 
	td.AP_Products_ID AS ProductID, 
	td.AS_Transactions_ID AS TransactionID, 
       td.AS_Transaction_Details_ID AS ID
FROM  	AS_Transaction_Details td 
		LEFT OUTER JOIN AP_Products p ON td.AP_Products_ID = p.AP_Products_ID
WHERE td.AS_Transactions_ID = @TransactionID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















----------------------------------------------------------------------------
--Description	:sp_Current_AS_Transaction_Headers
--Purpose       :Day End Sales Shape - GetCompletedDE (Completed Day Ends)
--Date			:2002/02/04
--Authors		:TB
--MODS          :13/07/02 - Removed superfluous colums
--              :01/10/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :           and commented JOIN to Lup_AS_Cashiers
--2004.4.2      :24/10/08 - Removed superflous joins
--              :24/10/08 - Added ORDER BY [Type], [No]
--2004.5.3      :08/08/11 - Added @TranDate input parameter for DAY-End Cutoff processing
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_Current_AS_Transaction_Headers
	(
		@CompanyID int,
        @TranDate datetime
	)

AS

SET NOCOUNT ON

	SELECT     
		ISNULL(t.Transaction_Number,'') as [No], 
		ISNULL(t.Amount,0) as [Amount], 
		ISNULL(t.Total_Cost,0) as [Cost], 
        ISNULL(t.Total_Tax_Amount,0) as [Tax], 
		ISNULL(t.Total_Discount_Amount,0) as [Discount], 
		ISNULL(t.Total_Amount,0) as [Total], 
		ISNULL(t.Payment_Amount,0) as [Payment], 
		t.Transaction_Date as [Date],
		tt.[Description] AS [Type],
		ISNULL(c.Surname, '') + isnull(', ' + c.Firstnames, '') as [Customer],		
		t.Day_End as [DayEnd], 
        ISNULL(u.Surname, '') + ISNULL(', ' + u.FirstName, '') as [User],
		t.AW_User_Companies_ID as [CompanyID],
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
		c.AC_Customers_ID as [CustomerID],
		t.AS_Transactions_ID AS [ID],
        t.Date_Captured AS [Captured]
	FROM AS_Transactions t 
        LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID 
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
	WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.Day_End IS NULL
          AND t.Transaction_Date <= @TranDate
    ORDER BY [Type], [No]


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



----------------------------------------------------------------------------
--Description	:sp_Current_AS_Transaction_Headers_SUM
--Purpose       :Day End Sales Shape - GetCompletedDE (Completed Day Ends)
--Date			:2017/02/24
--Authors		:RL
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Current_AS_Transaction_Headers_SUM]
	(
		@CompanyID int,
        @TranDate datetime
	)

AS

SET NOCOUNT ON

	SELECT    
		tt.[Description] AS [Transaction Type],	
		SUM(ISNULL(t.Amount,0)) as [Amount], 	
		SUM(ISNULL(t.Total_Cost,0)) as [Cost], 	
        SUM(ISNULL(t.Total_Tax_Amount,0)) as [Tax], 
		SUM(ISNULL(t.Total_Discount_Amount,0)) as [Discount],         
		SUM(ISNULL(t.Total_Amount,0)) as [Total], 
		SUM(ISNULL(t.Payment_Amount,0)) as [Payment]
	FROM AS_Transactions t 
	    LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
	WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.Day_End IS NULL
          AND t.Transaction_Date <= @TranDate
    GROUP BY tt.[Description]      
    ORDER BY tt.[Description]

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_POS_Login
--Purpose       :Select POS Login User
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_POS_Login
    (
        @Username varchar(50) = '',
        @Password varchar(50) = '',
        @CompanyID int = 0,
        @TillID int =0
    )

AS

SET NOCOUNT ON

    SELECT DISTINCT 
        u.UserName, 
        u.[Password], 
        cu.AW_User_Companies_ID, 
        ut.Lup_AS_Tills_ID, 
        u.AW_Users_ID as [ID],
        u.Surname + ISNULL(', ' + Firstname, '') as [Fullname]
    FROM AW_Users u 
        INNER JOIN AW_Users_Tills ut
            ON u.AW_Users_ID = ut.AW_Users_ID 
        INNER JOIN AW_Company_Users cu
            ON u.AW_Users_ID = cu.AW_Users_ID 
    WHERE u.UserName = @UserName AND
          u.[Password] = @Password AND
          cu.AW_User_Companies_ID = @CompanyID AND
          ut.Lup_AS_Tills_ID = @TillID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE Procedure sp_POS_Select_Login_Tills
    @ParUserID int
AS
    SELECT 
        Lup_AS_Tills_ID as ID, 
        Description 
FROM Lup_AS_Tills 
WHERE Cashier_ID = @ParUserID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE Procedure sp_POS_Select_Login_Users
    @ParUserID int
AS
    SELECT 
        AW_Users_ID as ID, 
        UserName, 
        Password,
        isnull(Surname,'') + isnull(', ' + Firstname,'') as FullName
FROM AW_Users 
WHERE AW_Users_ID = @ParUserID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Annual_Budget
--Purpose       :Annual Budget Report
--Parameters    :
--Date          :2003/04/07
--Authors       :TB
--Version       :1.0.0
--MODS          :09/04/03 - Added ORDER BY AB_Accounts.Description to display
--              :           all report category accounts 
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AB_Annual_Budget
    (
        @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(7000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @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)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(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 [Budget1], '

    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 [Budget2], '

    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 [Budget3], '

    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 [Budget4], '

    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 [Budget5], '

    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 [Budget6], '

    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 [Budget7], '

    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 [Budget8], '

    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 [Budget9], '

    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 [Budget10], '

    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 [Budget11], '

    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 [Budget12], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '       AND b.Sys_AB_I4_ID = 10 '    --Only REVENUE accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS  [SalesTot] '


    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, '
--------------------------------------------------------------
--19/03/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------



EXEC (@sql)



SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Balance_Sheet
--Purpose       :GAAP Balance Sheet Report
--Parameters    :
--Date          :2002/12/01
--Authors       :TB
--Version       :1.0.0
--MODS:         :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :16/10/03 - Modified TOTAL INCOME AND EXPENSE account balance
--              :           (at the ending period) to TOTAL OF ALL TRANSACTIONS
--              :           from the system start (see note below)
--              :26/03/04 - Modified [Balance] field to fetch account totals up
--              :           to @EndPeriod for ALL accounts not only BS accounts
--2004.2.5      :21/11/05 - Added option @IgnoreZeroTrans and @IgnoreZeroBalance
--              :           to ignore accounts with no entries and/or zero balances
--2004.3.8      :10/04/08 - Increased @sql to 8000
--              :11/04/08 - Commented [TranCount] not used
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Balance_Sheet]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint        
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_B1_ID					int, '
	SET @sql = @sql + '		Sys_AB_B2_ID					int, '
	SET @sql = @sql + '		Sys_AB_B3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		Balance							decimal(18,3) '	
	SET @sql = @sql + ') '	


-- --NEW 06/03/03----------------------------------
--     EXEC sp_AB_Get_Fiscal_Span
--                         @CompanyID,
--                         @YearEndMonthID OUTPUT,
--                         @StartMonthID OUTPUT,
--                         @StartYearID OUTPUT,
--                         @CurrentMonthID OUTPUT,
--                         @CurrentYearID OUTPUT


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	--SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_B1_ID, '	
	SET @sql = @sql + '		Sys_AB_B2_ID, '	
	SET @sql = @sql + '		Sys_AB_B3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    --SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
	SET @sql = @sql + ' b.Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
	SET @sql = @sql + ' b.Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
	SET @sql = @sql + ' b.Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '

-- --NEW 21/11/05----------------------------------
--     SET @sql = @sql + ' ( '
--     SET @sql = @sql + '     SELECT COUNT(*) '
--     SET @sql = @sql + '     FROM AB_GL_Transactions t '
--     SET @sql = @sql + '     WHERE '
--     SET @sql = @sql + '         ( '
--     SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--     SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--     SET @sql = @sql + '         ) '
--     SET @sql = @sql + ' ) AS [TranCount], '
-- ------------------------------------------------


--NEW 26/03/04----------------------------------
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Balance] '
------------------------------------------------


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B1 c '
    SET @sql = @sql + '         ON b.Sys_AB_B1_ID = c.Sys_AB_B1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B2 d '
    SET @sql = @sql + '         ON b.Sys_AB_B2_ID = d.Sys_AB_B2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B3 e '
    SET @sql = @sql + '         ON b.Sys_AB_B3_ID = e.Sys_AB_B3_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)   --  + ' AND '


    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_B1_ID, '
    SET @sql = @sql + '          b.Sys_AB_B2_ID, '
    SET @sql = @sql + '          b.Sys_AB_B3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '    --Orders the P/L categories
    SET @sql = @sql + '          a.[Description] '


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		Balance AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
--		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_B1_ID, '		
		SET @sql = @sql + '          Sys_AB_B2_ID, '		
		SET @sql = @sql + '          Sys_AB_B3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

    EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Balance_Sheet
--Purpose       :GAAP Comparative Balance Sheet Report
--Parameters    :
--Date          :2008/04/11
--Authors       :TB
--MODS:         :2008/04/11 - Ignore Zero Trans and Balance accounts not allowed
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Balance_Sheet_Comparative]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint                
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6),
            @LastStartPeriod varchar(6),
            @LastEndPeriod varchar(6),
            @LastYearID int

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_B1_ID					int, '
	SET @sql = @sql + '		Sys_AB_B2_ID					int, '
	SET @sql = @sql + '		Sys_AB_B3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		Balance							decimal(18,3), '	
	SET @sql = @sql + '		PrevBalance						decimal(18,3) '		
	SET @sql = @sql + ') '	

-- --NEW 06/03/03----------------------------------
--     EXEC sp_AB_Get_Fiscal_Span
--                         @CompanyID,
--                         @YearEndMonthID OUTPUT,
--                         @StartMonthID OUTPUT,
--                         @StartYearID OUTPUT,
--                         @CurrentMonthID OUTPUT,
--                         @CurrentYearID OUTPUT


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal to the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)


    SET @LastYearID = @CurrentYearID - 1
    SET @LastStartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @LastEndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @LastYearID)


	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	--SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_B1_ID, '	
	SET @sql = @sql + '		Sys_AB_B2_ID, '	
	SET @sql = @sql + '		Sys_AB_B3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		PrevBalance '
	SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    --SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
	SET @sql = @sql + ' b.Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
	SET @sql = @sql + ' b.Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
	SET @sql = @sql + ' b.Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
-- ------------------------------------------------
--     SET @sql = @sql + ' ( '
--     SET @sql = @sql + '     SELECT COUNT(*) '
--     SET @sql = @sql + '     FROM AB_GL_Transactions t '
--     SET @sql = @sql + '     WHERE '
--     SET @sql = @sql + '         ( '
--     SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--     SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--     SET @sql = @sql + '         ) '
--     SET @sql = @sql + ' ) AS [TranCount], '
-- ------------------------------------------------


------------------------------------------------
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Balance], '
------------------------------------------------


------------------------------------------------
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @LastEndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [PrevBalance] '
------------------------------------------------


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B1 c '
    SET @sql = @sql + '         ON b.Sys_AB_B1_ID = c.Sys_AB_B1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B2 d '
    SET @sql = @sql + '         ON b.Sys_AB_B2_ID = d.Sys_AB_B2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B3 e '
    SET @sql = @sql + '         ON b.Sys_AB_B3_ID = e.Sys_AB_B3_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)   --  + ' AND '


--     IF @IgnoreZeroTrans = 1
--         BEGIN
--             SET @sql = @sql + ' AND ( '
--             SET @sql = @sql + '     SELECT COUNT(*) '
--             SET @sql = @sql + '     FROM AB_GL_Transactions t '
--             SET @sql = @sql + '     WHERE '
--             SET @sql = @sql + '         ( '
--             SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--             SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--             SET @sql = @sql + '         ) '
--             SET @sql = @sql + ' ) <> 0 '
--         END
-- 
-- 
--     IF @IgnoreZeroBalance = 1
--         BEGIN
--             SET @sql = @sql + ' AND ( '
--             SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
--             SET @sql = @sql + '     FROM AB_GL_Transactions t '
--             SET @sql = @sql + '     WHERE '
--             SET @sql = @sql + '         ( '
--             SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--             SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--             SET @sql = @sql + '         ) '
--             SET @sql = @sql + ' ) <> 0 '
-- 
--         END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_B1_ID, '
    SET @sql = @sql + '          b.Sys_AB_B2_ID, '
    SET @sql = @sql + '          b.Sys_AB_B3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '    --Orders the P/L categories
    SET @sql = @sql + '          a.[Description] '

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		PrevBalance AS [PrevBalance] '		
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance], '
		SET @sql = @sql + '		SUM(ISNULL(PrevBalance,0)) AS [PrevBalance] '		
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
--		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_B1_ID, '		
		SET @sql = @sql + '          Sys_AB_B2_ID, '		
		SET @sql = @sql + '          Sys_AB_B3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END


    EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Bank_Recon
--Purpose       :Returns Bank Reconciliation report for specific Company Bank
--              :Used by Library and Ad Hoc Bank Recon reports
--Functionality :
--Parameters    :
--Date          :2002/11/25
--Authors       :TB
--Version       :1.0.0
--MODS          :27/11/02 - Removed Recon-Chk field
--              :06/01/04 - Added Accounting Period filters
--2004.3.8      :20/04/08 - Modified ORDER BY clauses for SQL 2005 Upgrade Advisor
--2004.4.2      :10/12/08 - Added ISNULL validations
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AB_Bank_Recon
    (
        @CompanyBanksID int,
        @Option tinyint,
        @BankBalance money = 0,
        @MonthID tinyint,
        @YearID int
    )

AS

SET NOCOUNT ON

    DECLARE @EndPeriod varchar(6)

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

--> CompanyBank details
    IF @Option = 0
        SELECT cb.AW_Company_Banks_ID AS [ID], 
               ISNULL(b.[Description], '') + 
               ISNULL(' - ' + cb.Account_Number, '') + 
               ISNULL(' - ' + cb.Account_Name, '') AS [Bank],

--               gl.AB_Account_Balance AS [GLBalance],

              (SELECT SUM(ISNULL(t.AB_Transaction_Amount, 0))
               FROM AB_GL_Transactions t
               WHERE t.AB_Accounts_ID = gl.AB_Accounts_ID AND
                     dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod) AS [GLBalance],

               getdate() AS [ReportDate],
--               gl.[Description] AS [GLDescription]
               ISNULL(gl.Account_Number, '') + 
               ISNULL(' (' + CONVERT(varchar(20), gl.AB_Accounts_ID), '') + 
               ISNULL(') - ' + gl.[Description], '') AS [GLDescription]
        FROM AW_Company_Banks cb 
            LEFT JOIN Slu_AW_Banks b 
                ON cb.Slu_AW_Banks_ID = b.Slu_AW_Banks_ID
            LEFT JOIN AB_Accounts gl
                ON cb.AB_Accounts_ID = gl.AB_Accounts_ID
        WHERE cb.AW_Company_Banks_ID = @CompanyBanksID

-------------------------------------------------------------
    ELSE
--> Outstanding Cheques and Other Payments - TOTAL
    IF @Option = 1
        SELECT
            SUM(ISNULL(t.Amount, 0) - ISNULL(t.Recon_Amount, 0)) AS [Payments]
        FROM AB_Cash_Book_Transactions t
            LEFT JOIN AW_Company_Banks b
            	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
        WHERE t.AW_Company_Banks_ID = @CompanyBanksID AND 
              ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
              dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod AND
             (t.Sys_AB_Transaction_Types_ID = 9 OR     --Cash Book - Cheque
              t.Sys_AB_Transaction_Types_ID = 11 OR    --Cash Book - Interest Paid
              t.Sys_AB_Transaction_Types_ID = 12 OR    --Cash Book - Bank Charge
              t.Sys_AB_Transaction_Types_ID = 13 OR    --Credit Card - Charge
              t.Sys_AB_Transaction_Types_ID = 14 OR    --Credit Card - Payment
              t.Sys_AB_Transaction_Types_ID = 18 OR    --Cash Book - Debit Order
              t.Sys_AB_Transaction_Types_ID = 20 OR    --Cash Book - EFT Payment
              t.Sys_AB_Transaction_Types_ID = 21) 

-------------------------------------------------------------
    ELSE
--> Outstanding Cheques and Other Payments - DETAIL
    IF @Option = 2
        SELECT
            t.AB_Cash_Book_Transactions_ID AS [ID], 
            t.Amount AS [Amount], 
            t.Recon_Amount AS [Reconciled],
           (ISNULL(t.Amount, 0) - ISNULL(t.Recon_Amount, 0)) AS [Balance],
            tt.Transaction_Code AS [Type],
            t.Reference_No AS [Ref No], 
            t.Transaction_Date AS [Date], 
            m.[Description] AS [Month], 
            y.[Description] AS [Year],
            t.Transaction_Description AS [Description]
        FROM AB_Cash_Book_Transactions t
            LEFT JOIN Sys_AB_Transaction_Types tt
            	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
            LEFT JOIN AW_Company_Banks b
            	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
            LEFT JOIN Slu_AW_Months m
            	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
            LEFT JOIN Slu_AW_Years y
            	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        WHERE t.AW_Company_Banks_ID = @CompanyBanksID AND 
              ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
              dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod AND
             (t.Sys_AB_Transaction_Types_ID = 9 OR     --Cash Book - Cheque
              t.Sys_AB_Transaction_Types_ID = 11 OR    --Cash Book - Interest Paid
              t.Sys_AB_Transaction_Types_ID = 12 OR    --Cash Book - Bank Charge
              t.Sys_AB_Transaction_Types_ID = 13 OR    --Credit Card - Charge
              t.Sys_AB_Transaction_Types_ID = 14 OR    --Credit Card - Payment
              t.Sys_AB_Transaction_Types_ID = 18 OR    --Cash Book - Debit Order
              t.Sys_AB_Transaction_Types_ID = 20 OR    --Cash Book - EFT Payment
              t.Sys_AB_Transaction_Types_ID = 21)      --Cash Book - Buy Association
        ORDER BY [Date], [Type]

-------------------------------------------------------------
    ELSE
--> Outstanding Deposits and Other Receipts - TOTAL
    IF @Option = 3
        SELECT
            SUM(ISNULL(t.Amount, 0) - ISNULL(t.Recon_Amount, 0)) AS [Receipts]
        FROM AB_Cash_Book_Transactions t
            LEFT JOIN AW_Company_Banks b
            	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
        WHERE t.AW_Company_Banks_ID = @CompanyBanksID AND 
              ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
              dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod AND
             (t.Sys_AB_Transaction_Types_ID = 10 OR    --Cash Book - Deposit
              t.Sys_AB_Transaction_Types_ID = 17 OR    --Cash Book - Interest Received
              t.Sys_AB_Transaction_Types_ID = 19)      --Cash Book - EFT Deposit

-------------------------------------------------------------
    ELSE
--> Outstanding Deposits and Other Receipts - DETAIL
    IF @Option = 4
        SELECT
            t.AB_Cash_Book_Transactions_ID AS [ID], 
            t.Amount AS [Amount], 
            t.Recon_Amount AS [Reconciled],
           (ISNULL(t.Amount, 0) - ISNULL(t.Recon_Amount, 0)) AS [Balance],
            tt.Transaction_Code AS [Type],
            t.Reference_No AS [Ref No], 
            t.Transaction_Date AS [Date], 
            m.[Description] AS [Month], 
            y.[Description] AS [Year],
            t.Transaction_Description AS [Description]
        FROM AB_Cash_Book_Transactions t
            LEFT JOIN Sys_AB_Transaction_Types tt
            	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
            LEFT JOIN AW_Company_Banks b
            	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
            LEFT JOIN Slu_AW_Months m
            	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
            LEFT JOIN Slu_AW_Years y
            	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        WHERE t.AW_Company_Banks_ID = @CompanyBanksID AND 
              ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
              dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod AND
             (t.Sys_AB_Transaction_Types_ID = 10 OR    --Cash Book - Deposit
              t.Sys_AB_Transaction_Types_ID = 17 OR    --Cash Book - Interest Received
              t.Sys_AB_Transaction_Types_ID = 19)      --Cash Book - EFT Deposit
        ORDER BY [Date], [Type]


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Chart_Of_Accounts
--Purpose       :Returns the General Ledger Accounts List
--Functionality :
--Parameters    :
--Date          :2002/01/09
--Authors       :TB
--MODS          :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--2004.4.4      :08/05/09 - Added Division and Group fields
--              :08/05/09 - Added @SortOrder and changed to DYNAMIC SQL
--------------------------------------------------------------------------------

CREATE      PROCEDURE sp_RPT_AB_Chart_Of_Accounts
    (
        @CompanyID int,
        @SortOrder tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [ID], '
    SET @sql = @sql + ' a.Description AS [AccountName], '
    SET @sql = @sql + ' a.Account_Number AS [AccountNumber], '
    SET @sql = @sql + ' b.Description AS [AccountCategory], '
    SET @sql = @sql + ' c.Description AS [AccountDivision], '
    SET @sql = @sql + ' d.Description AS [AccountGroup] '

    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 Lup_AB_Account_Divisions c '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = c.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups d '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = d.Lup_AB_Account_Groups_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [AccountName] '
        END

    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [AccountNumber] '
        END

    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [AccountCategory] '
        END

    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [AccountDivision] '
        END

    ELSE
    IF @SortOrder = 4
        BEGIN
            SET @sql = @sql + ' ORDER BY [AccountGroup] '
        END

    ELSE
    IF @SortOrder = 5
        BEGIN
            SET @sql = @sql + ' ORDER BY [ID] '
        END


    EXEC (@sql)













SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Balance_Sheet
--Purpose       :Fetch Enterprise Income Statement
--Date          :2007/09/09
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Balance_Sheet]

AS

SET NOCOUNT ON


	DECLARE @sql varchar(4000)

	Alter Table AB_Enterprise_Balance_Sheet
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Balance_Sheet
	Drop Column Department

    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AB_Enterprise_Balance_Sheet '

    SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
    SET @sql = @sql + '          Sys_AB_B2_ID, '
    SET @sql = @sql + '          Sys_AB_B3_ID, '
    SET @sql = @sql + '          Account   '


    EXEC (@sql)

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Income_Statement
--Purpose       :Fetch Enterprise Income Statement
--Date          :2007/09/05
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Income_Statement]

AS

SET NOCOUNT ON


	DECLARE @sql varchar(4000)

	Alter Table AB_Enterprise_Income_Statement
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Income_Statement
	Drop Column Department


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AB_Enterprise_Income_Statement '

    SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
    SET @sql = @sql + '          Sys_AB_I2_ID, '
    SET @sql = @sql + '          Sys_AB_I3_ID, '
    SET @sql = @sql + '          Sys_AB_I4_ID, '
    SET @sql = @sql + '          Account   '


    EXEC (@sql)

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Management_Accounts
--Purpose       :Fetch Enterprise Management Accounts
--Date          :2007/09/22
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Management_Accounts]
(
	@CombineSalesCOS tinyint
)
AS

SET NOCOUNT ON


	DECLARE @sql varchar(4000)

	Alter Table AB_Enterprise_Management_Accounts
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Management_Accounts
	Drop Column Department

    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AB_Enterprise_Management_Accounts '

    --SET @sql = @sql + ' ORDER BY IS1ID, '
    --SET @sql = @sql + '          IS2ID, '
    --SET @sql = @sql + '          IS3ID, '
    --SET @sql = @sql + '          IS4ID, '
    --SET @sql = @sql + '          Account   '


    SET @sql = @sql + ' ORDER BY IS1ID, '
    SET @sql = @sql + '          IS2ID, '
    SET @sql = @sql + '          IS3ID, '
--    SET @sql = @sql + '          [Level4], '
 --   SET @sql = @sql + '          Account,   '


    --SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    --SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    --SET @sql = @sql + '          b.Sys_AB_I3_ID, '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + '          [Level4], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '          IS4ID, '
        END

    SET @sql = @sql + '          GLDivision, '
    SET @sql = @sql + '          GLGroup, '

    IF @CombineSalesCOS = 1
        BEGIN
            ------------------------------------------------------------
            --> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
            SET @sql = @sql + '          IS4ID, '
            ------------------------------------------------------------

            SET @sql = @sql + '          AccountNo, '
        END

    SET @sql = @sql + '          Account   '




    EXEC (@sql)



SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Trial_Balance
--Purpose       :Fetch Enterprise Trial Balance
--Date          :2007/08/28
--Authors       :TB
--MODS:         :
--2004.4.8      :05/11/09 - Added @GroupBy and @Grouping sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Trial_Balance]
    (
        @GroupBy tinyint,
        @Sort tinyint		
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(8000),
            @Grouping varchar(1000)

	Alter Table AB_Enterprise_Trial_Balance
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Trial_Balance
	Drop Column Department


    SET @Grouping = ''

    SET @sql = ' SELECT * '
	SET @sql = @sql + ' FROM AB_Enterprise_Trial_Balance '

    IF @GroupBy = 0
        BEGIN
            SET @Grouping = ' ORDER BY '
        END
    ELSE
    IF @GroupBy = 1
        BEGIN
            SET @Grouping = ' ORDER BY Divisions, '
        END
    ELSE
    IF @GroupBy = 2
        BEGIN
            SET @Grouping = ' ORDER BY Groups, '
        END

    IF @Sort = 0
        BEGIN
            SET @sql = @sql + @Grouping + ' Description '
        END
    ELSE
    IF @Sort = 1
        BEGIN
            SET @sql = @sql + @Grouping + ' Account_Number '
        END
    ELSE
    IF @Sort = 2
        BEGIN
            SET @sql = @sql + @Grouping + ' Category, [Description] '
        END


    EXEC (@sql)

SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_GL_Audit_Trail
--Purpose       :GL Account Transaction Audit Trail Report
--              :for all AB_GL_Transactions
--Date          :2003/10/15
--Authors       :TB
--Version       :1.0.0
--MODS:         :15/12/04 - Added additional fields, ORDER By, and renamed RefNo fields
--2004.3.8      :20/03/08 - Modfied ORDER BY to [GLTranID], [RefID], [Period], [DateCaptured]
--              :           to enable GROUPIND transaction components together otherwise
--              :           running GL balance randomly appears out-of-balance
-------------------------------------------------------------------------------
--EXEC sp_RPT_AB_GL_Audit_Trail 1, 1, 1, 0, 0, 3, 4, 0, '2003/10/01 12:00:01 AM', '2003/10/18 11:59:59 PM'
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_RPT_AB_GL_Audit_Trail
    (
            @CompanyID int,
            @ChkGLAccount int,
            @GLAccountID int,
            @ActiveOnly int,
            @ChkPeriods int,
            @mbytMonthsID int,
            @mintYearsID int,
            @ChkDates int,
            @mdteListingStart datetime,
            @mdteListingEnd datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


-- --NEW 06/03/03----------------------------------
--     EXEC sp_AB_Get_Fiscal_Span
--                         @CompanyID,
--                         @YearEndMonthID OUTPUT,
--                         @StartMonthID OUTPUT,
--                         @StartYearID OUTPUT,
--                         @mbytMonthsID OUTPUT,
--                         @mintYearsID OUTPUT
-- 


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)


    SET @sql = ' '
    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [GLID], '
    SET @sql = @sql + '     a.AB_GL_Transactions_ID AS [GLTranID], '
    SET @sql = @sql + '     a.Date_Captured AS [DateCaptured], '
    SET @sql = @sql + '     ISNULL(f.[Description], '''') AS [GLAccount], '
--     SET @sql = @sql + '     ISNULL(f.[Account_Number], '''') AS [GLNumber], '
--     SET @sql = @sql + '     ISNULL(g.[Description], '''') AS [Category], '
--     SET @sql = @sql + '     f.AB_Account_Balance AS [CurrentBalance], '
    SET @sql = @sql + '     LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + '     a.AB_Source_Ref AS [SourceRef], '
    SET @sql = @sql + '     a.AB_Transaction_Ref AS [RefID], '
    SET @sql = @sql + '     b.Transaction_Code AS [Type], '
    SET @sql = @sql + '     c.[Description] AS [MonID], '
    SET @sql = @sql + '     d.[Description] AS [YearID], '
    SET @sql = @sql + '     a.[Description] AS [Narration], '
    SET @sql = @sql + '     a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + '     e.UserName AS [User], '
    SET @sql = @sql + '     dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) AS [Period] '
    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Transaction_Types b '
    SET @sql = @sql + '         ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON a.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
--     SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
--     SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '


    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


--FIX 09 JUL 03 --------------------------------
    IF @ChkGLAccount = 0    --Single GL Account
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE                  --ALL transactions
                BEGIN
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
------------------------------------------------


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND (a.AB_Transaction_Date >= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingStart, 121), 19) + '''' + ' '
            SET @sql = @sql + '  AND  a.AB_Transaction_Date <= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingEnd, 121), 19) + '''' + ') '
        END


-- This DUPLICATES the Accounting Period statement in the WHERE clause
--     IF @ChkPeriods = 1    --Accounting Period'
--         BEGIN
--             SET @sql = @sql + '    AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''    -- + ' AND '
--         END



    IF @ChkGLAccount = 0    --Single GL Account
        BEGIN
            SET @sql = @sql + ' ORDER BY [Period], [GLTranID], [RefID], [DateCaptured] ASC '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [GLTranID], [RefID], [Period], [DateCaptured] ASC '
        END





    EXEC (@sql)


SET NOCOUNT OFF

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_GL_Listing
--Purpose       :GL Account Transaction Listing Report
--              :    for all ACTIVE CURRENT YEAR AB_GL_Transactions
--Date          :2002/11/29
--Authors       :TB
--Version       :1.0.0
--MODS:         :23/10/02 - New TB Version: Added Current & Prior 2 months
--              :           for all ACTIVE AB_GL_Transactions
--              :30/11/02 - Added Report Sort Order selecttion with @SortOrder
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :           For the 'This Financial  Year only' UI checkbox only
--              :09/07/03 - Fixed returning ALL accounts when the DEFAULT STARTUP
--              :           options (a SINGLE account, CURRENT YEAR only) is selected
--              :04/02/04 - Added new [SourceNo] column
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AB_GL_Listing
    (
            @CompanyID int,
            @ChkGLAccount int,
            @GLAccountID int,
            @ActiveOnly int,
            @ChkPeriods int,
            @mbytMonthsID int,
            @mintYearsID int,
            @ChkDates int,
            @mdteListingStart datetime,
            @mdteListingEnd datetime,
            @SortOrder tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @mbytMonthsID OUTPUT,
                        @mintYearsID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)


    SET @sql = ' '
    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [AccountID], '
    SET @sql = @sql + '     ISNULL(f.[Description], '''') + '' - '' + ISNULL(f.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), f.AB_Accounts_ID) + '')''  AS [GLAccount], '
    SET @sql = @sql + '     ISNULL(g.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + '     f.AB_Account_Balance AS [GLBalance], '
    SET @sql = @sql + '     CONVERT(varchar(20), d.[Description]) + '', ''' +
                      '     + CONVERT(varchar(20), c.[Long_Description]) AS [Period], '

    SET @sql = @sql + '     LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + '     a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + '     a.AB_Source_Ref AS [SourceNo], '
    SET @sql = @sql + '     a.Date_Captured AS [Captured], '
    SET @sql = @sql + '     b.Transaction_Code AS [Type], '

    SET @sql = @sql + '     a.Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + '     a.Slu_AW_Years_ID AS [YearID], '
    SET @sql = @sql + '     a.[Description] AS [Narration], '
    SET @sql = @sql + '     a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + '     e.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Transaction_Types b '
    SET @sql = @sql + '         ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON a.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '


    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


--FIX 09 JUL 03 --------------------------------
    IF @ChkGLAccount = 0    --ONE GL Account
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE                  --ALL transactions
                BEGIN
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
------------------------------------------------


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND (a.AB_Transaction_Date >= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingStart, 121), 19) + '''' + ' '
            SET @sql = @sql + '  AND  a.AB_Transaction_Date <= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingEnd, 121), 19) + '''' + ') '
        END
    
    IF @ChkPeriods = 1    --Accounting Period'
        BEGIN
            SET @sql = @sql + '    AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''    -- + ' AND '
--            SET @sql = @sql + '  AND (a.Slu_AW_Months_ID <= ' + CONVERT(varchar(10), @mbytMonthsID) + ' '
--            SET @sql = @sql + '  AND  a.Slu_AW_Years_ID <= ' + CONVERT(varchar(10), @mintYearsID) + ') '
        END

    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY ISNULL(f.[Description], ''''), '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END

    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY ISNULL(f.Account_Number, '''') + ISNULL(f.[Description], ''''), '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END

    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY a.AB_Accounts_ID, '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END


    EXEC (@sql)


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_GL_Listing_BFWD
--Purpose       :GL Account Transaction Listing Report
--              :with BFWD balance from YEAR-END preceding Ending Accounting Period
--Date          :2004/12/28
--Authors       :TB
--Version       :1.0.0
--MODS:         :21/04/05 - Changed functionality to fetch ONLY ONE MONTH at a time
--              :           instead of everything up to the selected ENDING PERIOD
--              :27/04/05 - Changed functionality to fetch FROM MONTH TO MONTH
--                          instead of ONLY ONE MONTH at a time
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_RPT_AB_GL_Listing_BFWD
    (
        @CompanyID int,
        @ChkGLAccount int,
        @GLAccountID int,
        @mbytMonthsID int,
        @mintYearsID int,
        @mbytToMonthsID int,
        @mintToYearsID int,
        @SortOrder tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartPeriod varchar(6),
            @EndPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytToMonthsID, @mintToYearsID)


    SET @sql = ' '
    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [AccountID], '

    SET @sql = @sql + '     ISNULL(f.[Description], '''') + '' ('' + ' +
                      '         CONVERT(varchar(20), f.AB_Accounts_ID) + '')''  AS [GLAccount], '
    SET @sql = @sql + '     ISNULL(f.Account_Number, '''')  AS [GLAccountNo], '
    SET @sql = @sql + '     ISNULL(g.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + '     ISNULL(h.[Description], '''') AS [GLType], '

    SET @sql = @sql + '     f.AB_Account_Balance AS [GLBalance], '
    SET @sql = @sql + '     CONVERT(varchar(20), d.[Description]) + '', ''' +
                      '     + CONVERT(varchar(20), c.[Long_Description]) AS [Period], '

    SET @sql = @sql + '     LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + '     a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + '     a.AB_Source_Ref AS [SourceNo], '
    SET @sql = @sql + '     a.Date_Captured AS [Captured], '
    SET @sql = @sql + '     b.Transaction_Code AS [Type], '

    SET @sql = @sql + '     a.Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + '     a.Slu_AW_Years_ID AS [YearID], '
    SET @sql = @sql + '     a.[Description] AS [Narration], '

    SET @sql = @sql + '     a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + '     e.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Transaction_Types b '
    SET @sql = @sql + '         ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON a.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Types h '
    SET @sql = @sql + '         ON h.Sys_AB_Account_Types_ID = g.Sys_AB_Account_Types_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

-- ONE MONTH at a time -------------------------
--     IF @ChkGLAccount = 0    --ONE GL Account
--         BEGIN
--             SET @sql = @sql + '  AND a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
--             SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) = ' + '''' + @EndPeriod + ''''
--         END
--     ELSE                    --ALL GL Accounts
--         BEGIN
--             SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) = ' + '''' + @EndPeriod + ''''
--         END

-- FROM MONTH TO MONTH -------------------------

    IF @ChkGLAccount = 0    --ONE GL Account
        BEGIN
            SET @sql = @sql + '  AND a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
            SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
        END
------------------------------------------------


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY ISNULL(f.[Description], ''''), '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END

    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY ISNULL(f.Account_Number, '''') + ISNULL(f.[Description], ''''), '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END

    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY ISNULL(g.[Description], '''') + ISNULL(f.[Description], ''''), '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END

    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY a.AB_Accounts_ID, '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          a.AB_Transaction_Date ASC '
        END


    EXEC (@sql)


SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_GL_TranType_Listing
--Purpose       :GL Account Listing Transaction Summary Report
--              :with BFWD balance from YEAR-END preceding Ending Accounting Period
--Date          :2005/11/22
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_RPT_AB_GL_TranType_Listing
    (
        @CompanyID int,
        @ChkGLAccount int,
        @GLAccountID int,
        @mbytMonthsID int,
        @mintYearsID int,
        @mbytToMonthsID int,
        @mintToYearsID int,
        @SortOrder tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartPeriod varchar(6),
            @EndPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytToMonthsID, @mintToYearsID)


    SET @sql = ' '

    SET @sql = @sql + ' SELECT DISTINCT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [AccountID], '
    SET @sql = @sql + '     a.Sys_AB_Transaction_Types_ID AS [TypeID],  '
    SET @sql = @sql + '     b.Transaction_Code AS [TypeCode], '
    SET @sql = @sql + '     b.[Description] AS [Type], '

    SET @sql = @sql + '     f.[Description] AS [Account], '
    SET @sql = @sql + '     ISNULL(f.[Description], '''') + '' ('' + ' +
                      '         CONVERT(varchar(20), f.AB_Accounts_ID) + '')''  AS [GLAccount], '
    SET @sql = @sql + '     f.Account_Number AS [GLAccountNo], '
    SET @sql = @sql + '     g.[Description] AS [GLCategory], '
    SET @sql = @sql + '     ISNULL(h.[Description], '''') AS [GLType], '

    SET @sql = @sql + '     f.AB_Account_Balance AS [GLBalance], '
    SET @sql = @sql + '     CONVERT(varchar(20), d.[Description]) + '', ''' +
                      '     + CONVERT(varchar(20), c.[Long_Description]) AS [Period], '

    SET @sql = @sql + '     a.Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + '     a.Slu_AW_Years_ID AS [YearID], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND t.Sys_AB_Transaction_Types_ID = a.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '          AND t.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '          AND t.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Amount] '

    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Transaction_Types b '
    SET @sql = @sql + '         ON a.Sys_AB_Transaction_Types_ID = b.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON a.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON a.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Types h '
    SET @sql = @sql + '         ON h.Sys_AB_Account_Types_ID = g.Sys_AB_Account_Types_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '



-- FROM MONTH TO MONTH -------------------------
    IF @ChkGLAccount = 0    --ONE GL Account
        BEGIN
            SET @sql = @sql + '  AND a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
            SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(a.Slu_AW_Months_ID, a.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
        END
------------------------------------------------


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY f.[Description], '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          b.[Description] ASC '


        END

    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY f.Account_Number, '
            SET @sql = @sql + '          f.[Description], '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          b.[Description] ASC '
        END

    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY g.[Description], '
            SET @sql = @sql + '          f.[Description], '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          b.[Description] ASC '
        END

    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY a.AB_Accounts_ID, '
            SET @sql = @sql + '          a.Slu_AW_Years_ID, '
            SET @sql = @sql + '          a.Slu_AW_Months_ID, '
            SET @sql = @sql + '          b.[Description] ASC '
        END


    EXEC (@sql)


SET NOCOUNT OFF

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_RPT_AB_GL_Transactions
--Purpose       :GL Account Tranasctions by Transaction Type
--Date          :2004/11/07
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AB_GL_Transactions
    (
        @chkAccount tinyint,
        @GLAccountID int,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ClosingPeriod varchar(6),
            @Month tinyint,
            @Year int


-----------------------------------------------------------------------------
-- SET BFWD @ClosingPeriod from PERIOD preceding @MonthID & @YearID
-----------------------------------------------------------------------------
    SET @Month = @MonthID - 1
    SET @Year = @YearID
    
    IF @Month < 1
        BEGIN
            SET @Month = 12
            SET @Year = @Year - 1
        END

    SET @ClosingPeriod = dbo.fn_AB_Get_Ending_GL_Period(@Month, @Year)
-----------------------------------------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gt.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     gt.AB_GL_Transactions_ID AS [GLTranID], '
    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gt.Sys_AB_Transaction_Types_ID AS [TypeID],  '
    SET @sql = @sql + '     tt.[Description] AS [Type],  '
    SET @sql = @sql + '     tt.Transaction_Code AS [TypeCode],  '
    SET @sql = @sql + '     gt.AB_Source_Ref AS [GLSourceRefID], '
    SET @sql = @sql + '     gt.Description AS [Description], '

    SET @sql = @sql + '     ISNULL(gl.[Description], '''') +
                             '' ('' + ISNULL(gl.Account_Number, '''') + '')'' +
                             '' ('' + CONVERT(VARCHAR(10), gl.AB_Accounts_ID) + '') ''
                              AS [GL Account], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), gt.AB_Transaction_Date, 121)) AS [Date],  '
    SET @sql = @sql + '     m.[Description] AS [Month], '
    SET @sql = @sql + '     y.[Description] AS [Year], '

    SET @sql = @sql + '     dbo.fn_AB_BFWD_GL_Account(gt.AB_Accounts_ID, ' +
                                 '''' + CONVERT(varchar(10), @ClosingPeriod) + '''' +
                                 ') AS [BFWD], '

    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount], '
    SET @sql = @sql + '     gt.Date_Captured AS [Captured] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AB_Transaction_Types tt '
    SET @sql = @sql + '         ON gt.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID '

    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '

    IF @chkAccount = 0    --ONE GL Accounts
        BEGIN
            SET @sql = @sql + '  AND gt.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '

            SET @sql = @sql + '     ORDER BY gt.Sys_AB_Transaction_Types_ID, gt.AB_Transaction_Date, gt.AB_Transaction_Ref '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '     ORDER BY gt.AB_Accounts_ID, gt.Sys_AB_Transaction_Types_ID, gt.AB_Transaction_Date, gt.AB_Transaction_Ref '
        END


    EXEC (@sql)


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_General_Journal_Listing
--Purpose       :General Journals Listing
--Date          :2004/07/23
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AB_General_Journal_Listing
    (
            @CompanyID int,
            @ChkGLAccount int,
            @GLAccountID int,
            @ChkPeriods int,
            @mbytMonthsID int,
            @mintYearsID int,
            @mbytMonths2ID int,
            @mintYears2ID int,
            @ChkDates int,
            @mdteListingStart datetime,
            @mdteListingEnd datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000),
            @StartPeriod varchar(6),
            @EndPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonths2ID, @mintYears2ID)


    SET @sql = ' '
    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     b.AB_Journals_ID AS [JournalID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [AccountID], '
    SET @sql = @sql + '     f.[Description] AS [GLAccount], '
    SET @sql = @sql + '     ISNULL(g.[Description], '''') AS [GLCategory], '

    SET @sql = @sql + '     CONVERT(varchar(20), c.[Description]) AS [PeriodMonth], '
    SET @sql = @sql + '     CONVERT(varchar(20), d.[Description]) AS [PeriodYear], '

    SET @sql = @sql + '     LEFT(CONVERT(CHAR(10), b.Journal_Date, 121), 10) AS [Date], '
    SET @sql = @sql + '     b.Date_Captured AS [Captured], '

    SET @sql = @sql + '     b.Journal_Reference AS [Ref No], '
    SET @sql = @sql + '     b.Journal_Narration AS [Narration], '
    SET @sql = @sql + '     b.Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + '     b.Slu_AW_Years_ID AS [YearID], '

    SET @sql = @sql + '     a.Notes AS [Notes], '
    SET @sql = @sql + '     a.Amount AS [Amount], '
    SET @sql = @sql + '     e.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AB_Journal_Details a '
    SET @sql = @sql + '     LEFT JOIN AB_Journals b '
    SET @sql = @sql + '         ON a.AB_Journals_ID = b.AB_Journals_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON b.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON b.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON b.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkGLAccount = 0    --ONE GL Account
        BEGIN
            SET @sql = @sql + ' AND '
            SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
            SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + ' '
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND (b.Journal_Date >= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingStart, 121), 19) + '''' + ' '
            SET @sql = @sql + '  AND  b.Journal_Date <= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingEnd, 121), 19) + '''' + ') '
        END
    
    IF @ChkPeriods = 1    --Accounting Period'
        BEGIN
            SET @sql = @sql + '    AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '    AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
        END


    SET @sql = @sql + ' ORDER BY b.AB_Journals_ID '


    EXEC (@sql)


SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_General_Journals
--Purpose       :General Journals report
--Date          :2004/03/28
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AB_General_Journals
    (
            @CompanyID int,
            @ChkGLAccount int,
            @GLAccountID int,
            @ActiveOnly int,
            @ChkPeriods int,
            @mbytMonthsID int,
            @mintYearsID int,
            @ChkDates int,
            @mdteListingStart datetime,
            @mdteListingEnd datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @mbytMonthsID OUTPUT,
                        @mintYearsID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)


    SET @sql = ' '
    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     b.AB_Journals_ID AS [JournalID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [AccountID], '
    SET @sql = @sql + '     f.[Description] AS [GLAccount], '

--     SET @sql = @sql + '     ISNULL(f.[Description], '''') + '' - '' + ISNULL(f.Account_Number, '''') + '' ('' + ' +
--                       '     CONVERT(varchar(20), f.AB_Accounts_ID) + '')''  AS [GLAccount], '

    SET @sql = @sql + '     ISNULL(g.[Description], '''') AS [GLCategory], '
--    SET @sql = @sql + '     f.AB_Account_Balance AS [GLBalance], '
    SET @sql = @sql + '     CONVERT(varchar(20), d.[Description]) + '', ''' +
                      '     + CONVERT(varchar(20), c.[Long_Description]) AS [Period], '

    SET @sql = @sql + '     LEFT(CONVERT(CHAR(10), b.Journal_Date, 121), 10) AS [Date], '
    SET @sql = @sql + '     b.Journal_Reference AS [Ref No], '
    SET @sql = @sql + '     b.Journal_Narration AS [Narration], '
    SET @sql = @sql + '     b.Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + '     b.Slu_AW_Years_ID AS [YearID], '

    SET @sql = @sql + '     a.Notes AS [Notes], '
    SET @sql = @sql + '     a.Amount AS [Amount], '
    SET @sql = @sql + '     e.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AB_Journal_Details a '
    SET @sql = @sql + '     LEFT JOIN AB_Journals b '
    SET @sql = @sql + '         ON a.AB_Journals_ID = b.AB_Journals_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON b.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON b.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON b.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


--FIX 09 JUL 03 --------------------------------
    IF @ChkGLAccount = 0    --ONE GL Account
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE                  --ALL transactions
                BEGIN
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
------------------------------------------------


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND (b.Journal_Date >= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingStart, 121), 19) + '''' + ' '
            SET @sql = @sql + '  AND  b.Journal_Date <= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingEnd, 121), 19) + '''' + ') '
        END
    
    IF @ChkPeriods = 1    --Accounting Period'
        BEGIN
            SET @sql = @sql + '    AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''    -- + ' AND '
        END


    SET @sql = @sql + ' ORDER BY b.AB_Journals_ID '


    EXEC (@sql)


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_General_Journal_Listing
--Purpose       :General Journals UI Report
--Functionality :Displays DEBITS and CREDITS
--Date          :2009/03/10
--Authors       :TB
--MODS:         :
--2004.4.3      :13/03/09 - Modified [User] field to include Surname and Firstname
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AB_General_Journals_Report
    (
        @CompanyID int,
        @JournalID int
    )
AS

SET NOCOUNT ON


    SELECT a.AW_User_Companies_ID AS [CompanyID],
            b.AB_Journals_ID AS [JournalID],
            LEFT(CONVERT(CHAR(10), b.Journal_Date, 121), 10) AS [Date],
            b.Journal_Reference AS [Ref No],
            f.[Description] AS [GLAccount],
            b.Journal_Narration AS [Narration],
            a.Notes AS [Notes],
            c.[Description] AS [Month],
            d.[Description] AS [Year],
            b.Date_Captured AS [Captured],

            CASE WHEN a.Amount >= 0
                 THEN a.Amount
            END AS [Debit],

            CASE WHEN a.Amount < 0
                 THEN a.Amount
            END AS [Credit],

            e.Surname + ISNULL(', ' + e.FirstName, '') AS [User]
    FROM AB_Journal_Details a
        LEFT JOIN AB_Journals b
            ON a.AB_Journals_ID = b.AB_Journals_ID
        LEFT JOIN Slu_AW_Months c
            ON b.Slu_AW_Months_ID = c.Slu_AW_Months_ID
        LEFT JOIN Slu_AW_Years d
            ON b.Slu_AW_Years_ID = d.Slu_AW_Years_ID
        LEFT JOIN AW_Users e
            ON b.[User_ID] = e.AW_Users_ID
        LEFT JOIN AB_Accounts f
            ON a.AB_Accounts_ID = f.AB_Accounts_ID
    
    WHERE a.AW_User_Companies_ID = @CompanyID AND
          b.AB_Journals_ID = @JournalID




SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Income_Statement
--Purpose       :GAAP Income Statement Report
--Parameters    :
--Date          :2002/12/01
--Authors       :TB
--Version       :1.0.0
--MODS:         :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :19/03/03 - Added ORDER BY AB_Accounts.Description to display
--              :           all report category accounts
--              :03/08/03 - Added Cost Center filtering
--              :14/04/05 - Added @IgnoreYEJnl input parameter that now displays
--              :           monthly account totals reflecting ACTUAL movement
--2004.2.7      :06/04/06 - Added @IgnoreZeroTrans and @IgnoreZeroBalance options
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.0	:2013-12-09 - Exclude year end GL's on balance and transaction checks
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Income_Statement]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)
            
	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		Level1							varchar(100), '
	SET @sql = @sql + '		Level2							varchar(100), '
	SET @sql = @sql + '		Level3							varchar(100), '
	SET @sql = @sql + '		Level4							varchar(100), '
	SET @sql = @sql + '		Account							varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		Prior2							decimal(18,3), '
	SET @sql = @sql + '		Prior1							decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int '		
	SET @sql = @sql + ') '	


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @CurrentMonthID OUTPUT,
                        @CurrentYearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Account, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		Prior2, '
	SET @sql = @sql + '		Prior1, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '
	SET @sql = @sql + '		Sys_AB_I2_ID, '
	SET @sql = @sql + '		Sys_AB_I3_ID, '
	SET @sql = @sql + '		Sys_AB_I4_ID '
	SET @sql = @sql + ' ) '
		
    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '    
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [Department], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth2ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear2ID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Prior2], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth1ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear1ID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Prior1], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @CurrentMonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @CurrentYearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance], '

	SET @sql = @sql + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID] '

    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '    --Only Income Statement accounts


    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END

    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            --SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            --Needs to be same period as the rest of the report RL	V6.2
		    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
			SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
		    	    
		    --> IGNORE the INCOME & EXPENSE CLOSING JNL - RL 2013-12-09
			IF @IgnoreYEJnl = 1
				BEGIN
					SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
				END
            
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            --SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            --Needs to be same period as the rest of the report RL	V6.2
		    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
			SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
		    
		    --> IGNORE the INCOME & EXPENSE CLOSING JNL - RL 2013-12-09
			IF @IgnoreYEJnl = 1
				BEGIN
					SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
				END
            
            SET @sql = @sql + ' ) <> 0 '

        END

    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
--------------------------------------------------------------
--19/03/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------
--Select @EndPeriod

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		Prior2 AS [Prior2], '
		SET @sql = @sql + '		Prior1 AS [Prior1], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		Department AS [Department] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, ' 
		SET @sql = @sql + '          Account   '   
	END
	ELSE
	BEGIN    
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
	        
		SET @sql = @sql + ' SELECT '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(Prior2) AS [Prior2], '
		SET @sql = @sql + '		SUM(Prior1) AS [Prior1], '
		SET @sql = @sql + '		SUM([Current]) AS [Current], '
		SET @sql = @sql + '		SUM(Balance) AS [Balance], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID] '
		SET @sql = @sql + ' FROM @Tbl '
		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Account, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '    
		SET @sql = @sql + '          Account '                
	    
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, ' 
		SET @sql = @sql + '          Account   '       
	END
	
EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Income_Statement_Comparative
--Purpose       :GAAP Comparative Income Statement Report
--Parameters    :
--Date          :2008/04/10
--Authors       :TB
--MODS:         :11/04/08 - Ignore Zero Trans and Balance accounts not allowed
--2004.4.3      :13/03/09 - Fixed method to set @LastStartPeriod and @LastEndPeriod
--              :13/03/09 - Added @PeriodOption for MOVING 12 MONTHS or FISCAL YEAR-TO-DATE
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Income_Statement_Comparative]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @PeriodOption tinyint,
        @GroupByDepartment tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartPeriod varchar(6),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @LastStartPeriod varchar(6),
            @LastEndPeriod varchar(6)

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		CurrentTot						decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		BudgetTot						decimal(18,3), '	
	SET @sql = @sql + '		Budget							decimal(18,3), '
	SET @sql = @sql + '		BalanceTot						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '	
	SET @sql = @sql + '		PrevTot							decimal(18,3), '	
	SET @sql = @sql + '		PrevBalance						decimal(18,3) '	
	SET @sql = @sql + ') '	

    IF @PeriodOption = 0
        BEGIN
            ----------------------------------------------------------------------------------------
            -- Get PERIODS for MOVING 12 MONTHS
            ----------------------------------------------------------------------------------------
            SET @StartMonthID = @MonthID + 1
            SET @StartYearID = @YearID - 1

            IF @StartMonthID = 13
                BEGIN
                    SET @StartMonthID = 1
                    SET @StartYearID = @StartYearID + 1
                END

            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

            SET @LastStartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, (@StartYearID - 1))
            SET @LastEndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID - 1)
            ----------------------------------------------------------------------------------------
        END
    ELSE
    IF @PeriodOption = 1
        BEGIN
            ----------------------------------------------------------------------------------------
            -- Get PERIODS for FISCAL YEAR-TO-DATE
            ----------------------------------------------------------------------------------------
            EXEC sp_AB_Get_Fiscal_Span
                            @CompanyID,
                            @YearEndMonthID OUTPUT,
                            @StartMonthID OUTPUT,
                            @StartYearID OUTPUT,
                            @MonthID OUTPUT,
                            @YearID OUTPUT

            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

            SET @LastStartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID - 1)
            SET @LastEndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID - 1)
            ----------------------------------------------------------------------------------------
        END

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		CurrentTot, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		BudgetTot, '
	SET @sql = @sql + '		Budget, '
	SET @sql = @sql + '		BalanceTot, '		
	SET @sql = @sql + '		Balance, '	
	SET @sql = @sql + '		PrevTot, '		
	SET @sql = @sql + '		PrevBalance '		
	SET @sql = @sql + ' ) '
	
    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '
    
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
	SET @sql = @sql + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '

    ------------------------------------------------------------------------------------------------------
    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [CurrentTot], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS  [BudgetTot], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @LastStartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @LastEndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [PrevTot], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @LastStartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @LastEndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [PrevBalance] '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '   

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '    --Only Income Statement accounts

    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
--------------------------------------------------------------
--09/04/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		CurrentTot AS [CurrentTot], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		BudgetTot AS [BudgetTot], '
		SET @sql = @sql + '		Budget AS [Budget], '								
		SET @sql = @sql + '		BalanceTot AS [BalanceTot], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		PrevTot AS [PrevTot], '
		SET @sql = @sql + '		PrevBalance AS [PrevBalance] '				
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
	
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(CurrentTot,0)) AS [CurrentTot], '
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL(BudgetTot,0)) AS [BudgetTot], '
		SET @sql = @sql + '		SUM(ISNULL(Budget,0)) AS [Budget], '								
		SET @sql = @sql + '		SUM(ISNULL(BalanceTot,0)) AS [BalanceTot], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance], '
		SET @sql = @sql + '		SUM(ISNULL(PrevTot,0)) AS [PrevTot], '
		SET @sql = @sql + '		SUM(ISNULL(PrevBalance,0)) AS [PrevBalance] '				
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Man_Acc
--Purpose       :GAAP Management Accounts Report
--Parameters    :
--Date          :2002/12/10
--Authors       :TB
--Version       :1.0.0
--MODS:         :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--                          FROM @StartMonthID and @StartYearID inclusive
--                          TO @CurrentYearID and @CurrentYearID inclusive
--              :09/04/03 - Added ORDER BY AB_Accounts.Description to display
--              :           all report category accounts
--              :03/08/03 - Added Cost Center filtering
--              :14/04/05 - Added @IgnoreYEJnl input parameter that now displays
--              :           monthly account totals reflecting ACTUAL movement
--2004.2.7      :06/04/06 - Added @IgnoreZeroTrans and @IgnoreZeroBalance options
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Man_Acc]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)
            
--Declare @GroupByDepartment tinyint
--Set @GroupByDepartment = 1

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		CurrentTot						decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		BudgetTot						decimal(18,3), '	
	SET @sql = @sql + '		Budget							decimal(18,3), '
	SET @sql = @sql + '		BalanceTot						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3) '	
	SET @sql = @sql + ') '	


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		CurrentTot, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		BudgetTot, '
	SET @sql = @sql + '		Budget, '
	SET @sql = @sql + '		BalanceTot, '		
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '



    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
	SET @sql = @sql + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [CurrentTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS  [BudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '    --Only Income Statement accounts

    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END


    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
--------------------------------------------------------------
--09/04/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		CurrentTot AS [CurrentTot], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		BudgetTot AS [BudgetTot], '
		SET @sql = @sql + '		Budget AS [Budget], '								
		SET @sql = @sql + '		BalanceTot AS [BalanceTot], '
		SET @sql = @sql + '		Balance AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(CurrentTot,0)) AS [CurrentTot], '
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL(BudgetTot,0)) AS [BudgetTot], '
		SET @sql = @sql + '		SUM(ISNULL(Budget,0)) AS [Budget], '								
		SET @sql = @sql + '		SUM(ISNULL(BalanceTot,0)) AS [BalanceTot], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Man_Acc_Control
--Purpose       :GAAP Controllable Management Accounts Report
--Parameters    :
--Date          :2005/05/02
--Authors       :TB
--MODS:         :
--2004.2.8      :10/04/08 - Increased @sql to 8000
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AB_Man_Acc_Control
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND '
    SET @sql = @sql + '           a.AW_YesNo_Controllable_ID = 1 '    -- Contollable Accounts ONLY

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [CurrentTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND '
    SET @sql = @sql + '           a.AW_YesNo_Controllable_ID = 1 '    -- Contollable Accounts ONLY
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND '
    SET @sql = @sql + '           a.AW_YesNo_Controllable_ID = 1 '    -- Contollable Accounts ONLY
    SET @sql = @sql + ' ) AS  [BudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND '
    SET @sql = @sql + '           a.AW_YesNo_Controllable_ID = 1 '    -- Contollable Accounts ONLY
    SET @sql = @sql + ' ) AS [Budget], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + '''' + ' AND '
    SET @sql = @sql + '           a.AW_YesNo_Controllable_ID = 1 '    -- Contollable Accounts ONLY
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + '''' + ' AND '
    SET @sql = @sql + '           a.AW_YesNo_Controllable_ID = 1 '    -- Contollable Accounts ONLY
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '    --Only Income Statement accounts

    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END

    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
--------------------------------------------------------------
--09/04/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------

EXEC (@sql)


SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Management_Account_Groups
--Purpose       :Management Accounts GROUP BY GL Account Group Report
--Parameters    :
--Date          :2007/09/23
--Authors       :TB
--MODS:         :
--2004.4.4      :08/05/09 - Added b.Sys_AB_I4_ID in Sort Order IF @CombineSalesCOS = 1
--              :           to DISPLAY SALES ACCOUNTS FIRST in Group lists
--              :08/05/09 - Reworked @IgnoreZeroTrans and @IgnoreZeroBalance sections to
--              :           prevent loss of accounts with ZERO Current but with a Balance
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Management_Account_Groups]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @CombineSalesCOS tinyint,
        @GroupByDepartment tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6),
            @RevenueCategory varchar(100)

--Declare @GroupByDepartment tinyint
--Set @GroupByDepartment = 0

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLID							int, '
	SET @sql = @sql + '		AccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		GLDivision						varchar(100), '	
	SET @sql = @sql + '		GLGroup							varchar(100), '			
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	SET @sql = @sql + '		DivisionID						int, '			
	SET @sql = @sql + '		GroupID							int, '					
	
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Budget							decimal(18,3), '
	SET @sql = @sql + '		YTDBudget						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3) '	
	SET @sql = @sql + ') '	

    --NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    ------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

    ------------------------------------------------
    -- Get the DESCRIPTION of the Revenue Category
    ------------------------------------------------
    SELECT @RevenueCategory = Description
    FROM Sys_AB_Account_Categories
    WHERE Sys_AB_Account_Categories_ID = 13
    ------------------------------------------------

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLID, '
	SET @sql = @sql + '		AccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		GLDivision, '
	SET @sql = @sql + '		GLGroup, '		

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	SET @sql = @sql + '		DivisionID, '
	SET @sql = @sql + '		GroupID, '		
	
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Budget, '	
	SET @sql = @sql + '		YTDBudget, '	
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '


    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [AccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    SET @sql = @sql + ' ISNULL(g.[Description], '''') AS [GLDivision], '
    SET @sql = @sql + ' ISNULL(h.[Description], '''') AS [GLGroup], '

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + ' CASE WHEN b.Sys_AB_Account_Categories_ID = 14 '
            SET @sql = @sql + '      THEN ''' + @RevenueCategory + ''' '
            SET @sql = @sql + '      ELSE ISNULL(b.[Description], '''') '
            SET @sql = @sql + ' END AS [Level4], ' 
        END
    ELSE
         BEGIN
            SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [Level4], '
         END
    
	SET @sql = @sql + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '


--    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Divisions_ID AS [DivisionID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Groups_ID AS [GroupID], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)

    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [YTDBudget], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Divisions g '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = g.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups h '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = h.Lup_AB_Account_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
   

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND b.Sys_AB_I4_ID <> 0 '                    --Only Income Statement accounts

    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END

    IF @IgnoreZeroTrans = 1
        BEGIN
--             SET @sql = @sql + ' AND ( '
--             SET @sql = @sql + '     SELECT COUNT(*) '
--             SET @sql = @sql + '     FROM AB_GL_Transactions t '
--             SET @sql = @sql + '     WHERE '
--             SET @sql = @sql + '         ( '
--             SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--             SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--             SET @sql = @sql + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END

    IF @IgnoreZeroBalance = 1
        BEGIN
--             SET @sql = @sql + ' AND ( '
--             SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
--             SET @sql = @sql + '     FROM AB_GL_Transactions t '
--             SET @sql = @sql + '     WHERE '
--             SET @sql = @sql + '         ( '
--             SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
--             SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--             SET @sql = @sql + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

            IF @IgnoreYEJnl = 1
                BEGIN
                    SET @sql = @sql + '          AND Sys_AB_Transaction_Types_ID <> 16'
                END
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + '          [Level4], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
        END

    SET @sql = @sql + '          g.[Description], '
    SET @sql = @sql + '          h.[Description], '

    IF @CombineSalesCOS = 1
        BEGIN
            --------------------------------------------------------------
            --> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            --------------------------------------------------------------

            SET @sql = @sql + '          a.Account_Number, '
        END

    SET @sql = @sql + '          a.Description   '


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '

		
		SET @sql = @sql + '		Sys_AB_I4_ID AS [IS4ID], '
		SET @sql = @sql + '		GLID AS [GLID], '
		SET @sql = @sql + '		DivisionID AS [DivisionID], '						
		SET @sql = @sql + '		GroupID AS [GroupID], '								
		
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		AccountNo AS [AccountNo], '
		SET @sql = @sql + '		GLDivision AS [GLDivision], '
		SET @sql = @sql + '		GLGroup AS [GLGroup], '		
		
		SET @sql = @sql + '		ISNULL([Current],0) AS [Current], '
		SET @sql = @sql + '		ISNULL([Budget],0) AS [Budget], '
		SET @sql = @sql + '		ISNULL([YTDBudget],0) AS [YTDBudget], '
		SET @sql = @sql + '		ISNULL([Balance],0) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '

	    IF @CombineSalesCOS = 1
		    BEGIN
			    SET @sql = @sql + '          [Level4], '
			END
		ELSE
			BEGIN
				SET @sql = @sql + '          Sys_AB_I4_ID, '
			END

		SET @sql = @sql + '          GLDivision, '
		SET @sql = @sql + '			 GLGroup, '

		IF @CombineSalesCOS = 1
			BEGIN
				--------------------------------------------------------------
				--> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
				SET @sql = @sql + '          Sys_AB_I4_ID, '
				--------------------------------------------------------------

				SET @sql = @sql + '          AccountNo, '
			END

	    SET @sql = @sql + '          Account   '

	END
	ELSE
	BEGIN
	
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLID = 1, '
		SET @sql = @sql + '		AccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		AccountNo AS [AccountNo], '
		SET @sql = @sql + '		GLDivision AS [GLDivision], '
		SET @sql = @sql + '		GLGroup AS [GLGroup], '		
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL([Budget],0)) AS [Budget], '
		SET @sql = @sql + '		SUM(ISNULL([YTDBudget],0)) AS [YTDBudget], '		
		SET @sql = @sql + '		SUM(ISNULL([Balance],0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account, '
		SET @sql = @sql + '          AccountNo, '		
		SET @sql = @sql + '          GLDivision, '
		SET @sql = @sql + '          GLGroup '				
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '

	    IF @CombineSalesCOS = 1
		    BEGIN
			    SET @sql = @sql + '          [Level4], '
			END
		ELSE
			BEGIN
				SET @sql = @sql + '          Sys_AB_I4_ID, '
			END

		SET @sql = @sql + '          GLDivision, '
		SET @sql = @sql + '			 GLGroup, '

		IF @CombineSalesCOS = 1
			BEGIN
				--------------------------------------------------------------
				--> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
				SET @sql = @sql + '          Sys_AB_I4_ID, '
				--------------------------------------------------------------

				SET @sql = @sql + '          AccountNo, '
			END

	    SET @sql = @sql + '          Account   '
	
	END

EXEC (@sql)
--Select @sql

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Management_Accounts
--Purpose       :Management Accounts Report
--Parameters    :
--Date          :2004/06/13
--Authors       :TB
--Version       :1.0.0
--MODS:         :14/04/05 - Added @IgnoreYEJnl input parameter that now displays
--              :           monthly account totals reflecting ACTUAL movement
--2004.2.7      :06/04/06 - Added @IgnoreZeroTrans and @IgnoreZeroBalance options
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Management_Accounts]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
	@GroupByDepartment tinyint        
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		CurrentTot						decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		BudgetTot						decimal(18,3), '
	SET @sql = @sql + '		Budget							decimal(18,3), '		
	SET @sql = @sql + '		YTDBudgetTot					decimal(18,3), '
	SET @sql = @sql + '		YTDBudget						decimal(18,3), '
	SET @sql = @sql + '		BalanceTot						decimal(18,3), '	
	SET @sql = @sql + '		Balance							decimal(18,3) '		
	SET @sql = @sql + ') '	


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------

    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		CurrentTot, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		BudgetTot, '
	SET @sql = @sql + '		Budget, '	
	SET @sql = @sql + '		YTDBudgetTot, '
	SET @sql = @sql + '		YTDBudget, '	
	SET @sql = @sql + '		BalanceTot, '		
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
	SET @sql = @sql + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '            --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [CurrentTot], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(bud.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets bud '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON bud.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '            --Only Income Statement accounts
    SET @sql = @sql + '           bud.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           bud.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS  [BudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(bud.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets bud '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON bud.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '                --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS  [YTDBudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [YTDBudget], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '                --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '                    --Only Income Statement accounts

    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END


    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
-------------------------------------------------------------------------------------------
--09/04/03 - Added ORDER BY AB_Accounts.Description to display all report category accounts 
    SET @sql = @sql + '          a.Description   '
-------------------------------------------------------------------------------------------

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '		
		SET @sql = @sql + '		CurrentTot AS [CurrentTot], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		BudgetTot AS [BudgetTot], '
		SET @sql = @sql + '		Budget AS [Budget], '
		SET @sql = @sql + '		YTDBudgetTot AS [YTDBudgetTot], '
		SET @sql = @sql + '		YTDBudget AS [YTDBudget], '		
		SET @sql = @sql + '		BalanceTot AS [BalanceTot], '
		SET @sql = @sql + '		Balance AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
	
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(CurrentTot,0)) AS [CurrentTot], '
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL(BudgetTot,0)) AS [BudgetTot], '
		SET @sql = @sql + '		SUM(ISNULL(Budget,0)) AS [Budget], '		
		SET @sql = @sql + '		SUM(ISNULL(YTDBudgetTot,0)) AS [YTDBudgetTot], '								
		SET @sql = @sql + '		SUM(ISNULL(YTDBudget,0)) AS [YTDBudget], '
		SET @sql = @sql + '		SUM(ISNULL(BalanceTot,0)) AS [BalanceTot], '		
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Recurring_Journals
--Purpose       :Recurring Journals report
--Date          :2004/03/28
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AB_Recurring_Journals
    (
            @CompanyID int,
            @ChkGLAccount int,
            @GLAccountID int,
            @ActiveOnly int,
            @ChkPeriods int,
            @mbytMonthsID int,
            @mintYearsID int,
            @ChkDates int,
            @mdteListingStart datetime,
            @mdteListingEnd datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @mbytMonthsID OUTPUT,
                        @mintYearsID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@mbytMonthsID, @mintYearsID)


    SET @sql = ' '
    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     b.AB_Recurring_ID AS [JournalID], '
    SET @sql = @sql + '     a.AB_Accounts_ID AS [AccountID], '
    SET @sql = @sql + '     f.[Description] AS [GLAccount], '

--     SET @sql = @sql + '     ISNULL(f.[Description], '''') + '' - '' + ISNULL(f.Account_Number, '''') + '' ('' + ' +
--                       '     CONVERT(varchar(20), f.AB_Accounts_ID) + '')''  AS [GLAccount], '

    SET @sql = @sql + '     ISNULL(g.[Description], '''') AS [GLCategory], '
--    SET @sql = @sql + '     f.AB_Account_Balance AS [GLBalance], '
    SET @sql = @sql + '     CONVERT(varchar(20), d.[Description]) + '', ''' +
                      '     + CONVERT(varchar(20), c.[Long_Description]) AS [Period], '

    SET @sql = @sql + '     LEFT(CONVERT(CHAR(10), b.Recurring_Date, 121), 10) AS [Date], '
    SET @sql = @sql + '     b.Recurring_Reference AS [Ref No], '
    SET @sql = @sql + '     b.Recurring_Narration AS [Narration], '
    SET @sql = @sql + '     b.Slu_AW_Months_ID AS [MonthID], '
    SET @sql = @sql + '     b.Slu_AW_Years_ID AS [YearID], '

    SET @sql = @sql + '     a.Notes AS [Notes], '
    SET @sql = @sql + '     a.Amount AS [Amount], '
    SET @sql = @sql + '     e.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AB_Recurring_Details a '
    SET @sql = @sql + '     LEFT JOIN AB_Recurring b '
    SET @sql = @sql + '         ON a.AB_Recurring_ID = b.AB_Recurring_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months c '
    SET @sql = @sql + '         ON b.Slu_AW_Months_ID = c.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years d '
    SET @sql = @sql + '         ON b.Slu_AW_Years_ID = d.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON b.[User_ID] = e.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts f '
    SET @sql = @sql + '         ON a.AB_Accounts_ID = f.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories g '
    SET @sql = @sql + '         ON f.Sys_AB_Account_Categories_ID = g.Sys_AB_Account_Categories_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


--FIX 09 JUL 03 --------------------------------
    IF @ChkGLAccount = 0    --ONE GL Account
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + '  a.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
    ELSE                    --ALL GL Accounts
        BEGIN
            IF @ActiveOnly = 1    --This Year transactions only
                BEGIN
                    SET @sql = @sql + ' AND '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID <> 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                    SET @sql = @sql + ' OR '
                    SET @sql = @sql + ' ( '
                    SET @sql = @sql + '  g.Sys_AB_I1_ID = 1 '
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' ) '
                END
            ELSE                  --ALL transactions
                BEGIN
                    SET @sql = @sql + '  AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
                    SET @sql = @sql + ' '
                END
        END
------------------------------------------------


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND (b.Recurring_Date >= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingStart, 121), 19) + '''' + ' '
            SET @sql = @sql + '  AND  b.Recurring_Date <= ' +
                                '''' + LEFT(CONVERT(CHAR(19), @mdteListingEnd, 121), 19) + '''' + ') '
        END
    
    IF @ChkPeriods = 1    --Accounting Period'
        BEGIN
            SET @sql = @sql + '    AND dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''    -- + ' AND '
        END


    SET @sql = @sql + ' ORDER BY b.AB_Recurring_ID '


    EXEC (@sql)


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Trial_Balance
--Purpose       :GL Trial Balance Report data
--Functionality :Shows PERIOD BALANCES for the PRIOR Periods
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS:         :23/10/02 - NEW version: Added Current & Prior 2 months
--              :           for all ACTIVE AB_GL_Transactions
--              :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :10/03/03 - Replaced 'Balance' query section with the Balance
--              :           Sheet retrieval method which distinquises between
--              :           Balance Sheet and Income/Expense accounts and uses
--              :           a seperate WHERE clause criteria for each
--              :16/10/03 - Modified TOTAL INCOME AND EXPENSE account balance
--              :           (at the ending period) to TOTAL OF ALL TRANSACTIONS
--              :           from the system start (see note below)
--              :26/03/04 - Modified [Balance] field to fetch account totals up
--              :           to @EndPeriod for ALL accounts not only BS accounts
--              :29/12/04 - Added @SortOrder parameter and [GLAccountNo] field
--2004.2.7      :07/02/06 - Added new [TranCount] field to count # of GL Transaction
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Trial_Balance]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @SortOrder tinyint,
		@GroupByDepartment tinyint
        
--         @IgnoreZeroTrans tinyint,
--         @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

--Declare @GroupByDepartment tinyint        
--SET @GroupByDepartment = 1

    DECLARE @sql varchar(8000),
            @StartPeriod varchar(6),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @Period1 varchar(6),
            @Period2 varchar(6),
            @Period3 varchar(6)

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccount						varchar(100), '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		Prior2							decimal(18,3), '
	SET @sql = @sql + '		Prior1							decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '
	SET @sql = @sql + '		TranCount						int '
	SET @sql = @sql + ') '	


-- --NEW 06/03/03----------------------------------
--     EXEC sp_AB_Get_Fiscal_Span
--                         @CompanyID,
--                         @YearEndMonthID OUTPUT,
--                         @StartMonthID OUTPUT,
--                         @StartYearID OUTPUT,
--                         @CurrentMonthID OUTPUT,
--                         @CurrentYearID OUTPUT


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth2ID, @PriorYear2ID)
    SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth1ID, @PriorYear1ID)
    SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccount, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		Prior2, '
	SET @sql = @sql + '		Prior1, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		TranCount '
	SET @sql = @sql + ' ) '


    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' r.Lup_AB_Account_Departments_ID AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [Department], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @Period1 + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Prior2], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @Period2 + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Prior1], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @Period3 + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Balance], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT COUNT(*) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [TranCount] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories c '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		Prior2 AS [Prior2], '
		SET @sql = @sql + '		Prior1 AS [Prior1], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		TranCount AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl   '

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY GLAccountID ASC '
			END
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccount = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		SUM(Prior2) AS [Prior2], '
		SET @sql = @sql + '		SUM(Prior1) AS [Prior1], '
		SET @sql = @sql + '		SUM([Current]) AS [Current], '
		SET @sql = @sql + '		SUM(Balance) AS [Balance], '
		SET @sql = @sql + '		SUM(TranCount) AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl '
		SET @sql = @sql + ' GROUP BY CompanyID, '
		SET @sql = @sql + '			 GLAccountID, '
		SET @sql = @sql + '			 GLAccount, '
		SET @sql = @sql + '			 GLAccountNo, '
		SET @sql = @sql + '			 GLCategory '		

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY CONVERT(VARCHAR(10),GLAccountID) + ISNULL([GLAccount], '''') ASC '
			END
	
	END
	
	--Select @sql
    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Trial_Balance
--Purpose       :GL Trial Balance Report data
--Functionality :Shows PERIOD MOVEMENT for the PRIOR Periods
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS:         :23/10/02 - NEW version: Added Current & Prior 2 months
--              :           for all ACTIVE AB_GL_Transactions
--              :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :10/03/03 - Replaced 'Balance' query section with the Balance
--              :           Sheet retrieval method which distinquises between
--              :           Balance Sheet and Income/Expense accounts and uses
--              :           a seperate WHERE clause criteria for each
--              :16/10/03 - Modified TOTAL INCOME AND EXPENSE account balance
--              :           (at the ending period) to TOTAL OF ALL TRANSACTIONS
--              :           from the system start (see note below)
--              :26/03/04 - Modified [Balance] field to fetch account totals up
--              :           to @EndPeriod for ALL accounts not only BS accounts
--              :29/12/04 - Added @SortOrder parameter and [GLAccountNo] field
--2004.2.7      :07/02/06 - Added new [TranCount] field to count # of GL Transaction
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Trial_Balance_Movement]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @SortOrder tinyint,
		@GroupByDepartment tinyint
--         @IgnoreZeroTrans tinyint,
--         @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON
--Declare @GroupByDepartment tinyint        
--SET @GroupByDepartment = 1

    DECLARE @sql varchar(8000),
            @StartPeriod varchar(6),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @Period1 varchar(6),
            @Period2 varchar(6),
            @Period3 varchar(6)

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccount						varchar(100), '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		Prior2							decimal(18,3), '
	SET @sql = @sql + '		Prior1							decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '
	SET @sql = @sql + '		TranCount						int '
	SET @sql = @sql + ') '	

-- --NEW 06/03/03----------------------------------
--     EXEC sp_AB_Get_Fiscal_Span
--                         @CompanyID,
--                         @YearEndMonthID OUTPUT,
--                         @StartMonthID OUTPUT,
--                         @StartYearID OUTPUT,
--                         @CurrentMonthID OUTPUT,
--                         @CurrentYearID OUTPUT


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth2ID, @PriorYear2ID)
    SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth1ID, @PriorYear1ID)
    SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccount, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		Prior2, '
	SET @sql = @sql + '		Prior1, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		TranCount '
	SET @sql = @sql + ' ) '


    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' r.Lup_AB_Account_Departments_ID AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [Department], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth2ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear2ID)
    SET @sql = @sql + ' ) AS [Prior2], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth1ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear1ID)
    SET @sql = @sql + ' ) AS [Prior1], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @CurrentMonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @CurrentYearID)
    SET @sql = @sql + ' ) AS  [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [Balance], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT COUNT(*) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE '
    SET @sql = @sql + '         ( '
    SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [TranCount] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories c '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		Prior2 AS [Prior2], '
		SET @sql = @sql + '		Prior1 AS [Prior1], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		TranCount AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl   '

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY GLAccountID ASC '
			END
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccount = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		SUM(Prior2) AS [Prior2], '
		SET @sql = @sql + '		SUM(Prior1) AS [Prior1], '
		SET @sql = @sql + '		SUM([Current]) AS [Current], '
		SET @sql = @sql + '		SUM(Balance) AS [Balance], '
		SET @sql = @sql + '		SUM(TranCount) AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl '
		SET @sql = @sql + ' GROUP BY CompanyID, '
		SET @sql = @sql + '			 GLAccountID, '
		SET @sql = @sql + '			 GLAccount, '
		SET @sql = @sql + '			 GLAccountNo, '
		SET @sql = @sql + '			 GLCategory '		

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY CONVERT(VARCHAR(10),GLAccountID) + ISNULL([GLAccount], '''') ASC '
			END
	
	END

    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AB_VAT_Report
--Purpose       :Monthly V.A.T. Report
--Date          :2004/11/07
--Authors       :TB
--Version       :1.0.0
--MODS          :
----2016.6.2 RL	2016-08-04	:Added option to exlude or exclude TAX payments or receipts
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_VAT_Report]
    (
        @Option					tinyint,
        @MonthID				tinyint,
    	@YearID					int,
        @ToMonthID				tinyint,
    	@ToYearID				int,
		@ChkShowExclusion		int,
        @ExclusionOption		int,
        @CompanyID				int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @GLControlAccount int,
            @StartPeriod varchar(6),
            @EndPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)


    SELECT @GLControlAccount = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 401    --VAT Control


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gt.AB_GL_Transactions_ID AS [GLTranID], '
    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gt.Sys_AB_Transaction_Types_ID AS [TypeID],  '
    SET @sql = @sql + '     tt.[Description] AS [Type],  '
    SET @sql = @sql + '     tt.Transaction_Code AS [TypeCode],  '
    SET @sql = @sql + '     gt.AB_Source_Ref AS [GLSourceRefID], '
    SET @sql = @sql + '     gt.Description AS [Description], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), gt.AB_Transaction_Date, 121)) AS [Date],  '
    SET @sql = @sql + '     m.[Description] AS [Month], '
    SET @sql = @sql + '     y.[Description] AS [Year], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount], '
    SET @sql = @sql + '     gt.Date_Captured AS [Captured] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AB_Transaction_Types tt '
    SET @sql = @sql + '         ON gt.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID '

--     SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--     SET @sql = @sql + '         gt.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLControlAccount) + ' AND '
--     SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
--     SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           gt.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLControlAccount) + ' AND '
    SET @sql = @sql + '           dbo.fn_AB_Get_Ending_GL_Period(gt.Slu_AW_Months_ID, gt.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''

	IF @ChkShowExclusion = 1
	BEGIN
		IF @ExclusionOption = 2 BEGIN
			SET @sql = @sql + '           AND gt.Sys_AB_Transaction_Types_ID IN (30, 31)'
		END
	END
	ELSE
	BEGIN
			SET @sql = @sql + '           AND gt.Sys_AB_Transaction_Types_ID NOT IN (30, 31)'
	END
	
	
    SET @sql = @sql + '     ORDER BY gt.Sys_AB_Transaction_Types_ID, gt.AB_Transaction_Date, gt.AB_Transaction_Ref '

    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Contract_Pricing
--Purpose       :
--Date          :2008/07/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Contract_Pricing]
    (
        @Filter tinyint,
        @CustomerID	int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int        
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' p.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' cp.[Description] AS [Product], '
    SET @sql = @sql + ' cp.Product_Code AS [Code], '
    SET @sql = @sql + ' CONVERT(CHAR(10), cp.Start_Date, 121) AS [Start Date], '
    SET @sql = @sql + ' CONVERT(CHAR(10), cp.End_Date, 121) AS [End Date], '
    SET @sql = @sql + ' cp.Unit_Price AS [Unit Price], '
    SET @sql = @sql + ' cp.Discount_Perc AS [Disc %], '
    SET @sql = @sql + ' cp.Discount_Amount AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate())) AS [Retail], '
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg. Cost], '
    SET @sql = @sql + ' p.On_Hand as [On Hand], '
	SET @sql = @sql + ' MinSaleQty As [MinQty] '
    SET @sql = @sql + ' FROM AC_Contract_Prices cp '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON p.AP_Products_ID = cp.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = cp.AC_Customers_ID '

	IF @CustomerID <> 0 
		BEGIN
			SET @sql = @sql + ' WHERE c.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
		END

    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND cp.Start_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND cp.End_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END

    IF @Filter = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Customer], [Product], [Start Date] '
        END
    ELSE
    IF @Filter = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product], [Customer], [Start Date] '
        END
    ELSE
    IF @Filter = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Code], [Customer], [Start Date] '
        END
    ELSE
    IF @Filter = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [Start Date], [Customer], [Product] '
        END
    ELSE
    IF @Filter = 4
        BEGIN
            SET @sql = @sql + ' ORDER BY [End Date], [Customer], [Product] '
        END
    


--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Age_Analysis
--Purpose       :Customer Age Analysis report
--Functionality :Combines INTERIM and PERIOD PROCEDURE options 
--Date          :2004/12/21
--Authors       :TB
--MODS          :
--2004.3.5      :14/05/07 - Added Customer Notes field
--2004.3.8      :09/04/08 - Added TRIM and ISNULL validation for Customer Notes
--2004.4.2      :27/11/08 - Added ISNULL validation on all ageing fields
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AC_Customer_Age_Analysis
    (
        @PeriodProceduresID int,
        @PrintZeroBalances tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' t.FullName AS [FullName], '
    SET @sql = @sql + ' t.Customer_Number AS [CustomerNo], '
    SET @sql = @sql + ' t.Post_Address AS [PostAddress], '
    SET @sql = @sql + ' t.Post_Office AS [PostOffice], '
    SET @sql = @sql + ' t.Post_Code AS [PostCode], '
    SET @sql = @sql + ' t.Work_Email AS [Email], '
    SET @sql = @sql + ' ISNULL(t.Account_Balance, 0) AS [AccountBalance], '
    SET @sql = @sql + ' ISNULL(t.[Current], 0) AS [Current], '
    SET @sql = @sql + ' ISNULL(t.[30Days], 0) AS [30Days], '
    SET @sql = @sql + ' ISNULL(t.[60Days], 0) AS [60Days], '
    SET @sql = @sql + ' ISNULL(t.[90Days], 0) AS [90Days], '
    SET @sql = @sql + ' (ISNULL(t.[120Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[150Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[180+Days], 0)) AS [120+Days], '
    SET @sql = @sql + ' c.Contact_Name AS [ContactName], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' c.Initials AS [Initials], '
    SET @sql = @sql + ' dbo.fn_AC_Get_Last_Payment_Date(t.AC_Customers_ID) AS [LastPayDate], '
    SET @sql = @sql + ' dbo.fn_AC_Get_Last_Payment_Amount(t.AC_Customers_ID) AS [LastPayAmount], '
    SET @sql = @sql + ' c.Credit_Limit AS [CreditLimit], '
    SET @sql = @sql + ' c.Credit_Insurers_Limit AS [InsurerLimit], '
    SET @sql = @sql + ' c.Fax_No AS [FaxNo], '
    SET @sql = @sql + ' c.Cell_No AS [CellNo], '

    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') AS [TradeStyle], '
    SET @sql = @sql + ' ISNULL(c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.City, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Street_Post_Code, '''') AS [StreetAddr], '

    SET @sql = @sql + ' tt.[Description] AS [Terms], '
    SET @sql = @sql + ' s.[Description] AS [Status], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Notes, ''''))) AS [Notes] '

    IF @PeriodProceduresID = 0
        BEGIN
            SET @sql = @sql +
               ' FROM AC_Statements_Temp t '
        END
    ELSE
        BEGIN
            SET @sql = @sql +
               ' FROM AC_Statements t '
        END


    SET @sql = @sql +
        ' INNER JOIN AC_Customers c ' +
        '     ON t.AC_Customers_ID = c.AC_Customers_ID ' +
        ' LEFT JOIN Sys_AC_Account_Status s ' +
        '     ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID ' +
        ' LEFT JOIN Slu_AW_Credit_Terms tt ' +
        '     ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID ' +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
        '       AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '


    IF @PrintZeroBalances = 0
        BEGIN
            SET @sql = @sql + '       AND ISNULL(t.Account_Balance, 0) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY t.FullName '



    EXEC (@sql)




SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Age_Analysis_Filter
--Purpose       :Customer Age Analysis report by Filter
--Functionality :Combines INTERIM and PERIOD PROCEDURE options 
--Date          :2006/07/20
--Authors       :TB
--MODS          :
--2004.4.2      :27/11/08 - Added ISNULL validation on all ageing fields
--2004.5.0      :16/12/10 - Added Filters 5 to 8
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AC_Customer_Age_Analysis_Filter
    (
        @Filter tinyint,
        @PeriodProceduresID int,
        @PrintZeroBalances tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    IF @Filter = 1
        SET @sql = @sql +
            ' o.Lup_AC_Customer_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 2
        SET @sql = @sql +
            ' o.Lup_AC_Customer_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 3
        SET @sql = @sql +
            ' o.Sys_AC_Account_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 4
        SET @sql = @sql +
            ' o.Sys_AC_Account_Status_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 5
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 6
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 7
        SET @sql = @sql +
            ' o.Slu_AW_Credit_Terms_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 8
        SET @sql = @sql +
            ' o.Sys_AC_Credit_Term_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' c.Lup_AS_Reps_ID AS [RepID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' t.FullName AS [FullName], '
    SET @sql = @sql + ' t.Customer_Number AS [CustomerNo], '
    SET @sql = @sql + ' t.Post_Address AS [PostAddress], '
    SET @sql = @sql + ' t.Post_Office AS [PostOffice], '
    SET @sql = @sql + ' t.Post_Code AS [PostCode], '
    SET @sql = @sql + ' t.Work_Email AS [Email], '
    SET @sql = @sql + ' ISNULL(t.Account_Balance, 0) AS [AccountBalance], '
    SET @sql = @sql + ' ISNULL(t.[Current], 0) AS [Current], '
    SET @sql = @sql + ' ISNULL(t.[30Days], 0) AS [30Days], '
    SET @sql = @sql + ' ISNULL(t.[60Days], 0) AS [60Days], '
    SET @sql = @sql + ' ISNULL(t.[90Days], 0) AS [90Days], '
    SET @sql = @sql + ' (ISNULL(t.[120Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[150Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[180+Days], 0)) AS [120+Days], '
    SET @sql = @sql + ' c.Contact_Name AS [ContactName], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' c.Initials AS [Initials], '
    SET @sql = @sql + ' dbo.fn_AC_Get_Last_Payment_Date(t.AC_Customers_ID) AS [LastPayDate], '
    SET @sql = @sql + ' dbo.fn_AC_Get_Last_Payment_Amount(t.AC_Customers_ID) AS [LastPayAmount], '
    SET @sql = @sql + ' c.Credit_Limit AS [CreditLimit], '
    SET @sql = @sql + ' c.Credit_Insurers_Limit AS [InsurerLimit], '
    SET @sql = @sql + ' c.Fax_No AS [FaxNo], '
    SET @sql = @sql + ' c.Cell_No AS [CellNo], '

    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') AS [TradeStyle], '
    SET @sql = @sql + ' ISNULL(c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.City, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Street_Post_Code, '''') AS [StreetAddr], '

    SET @sql = @sql + ' r.Description AS [RepName], '
    SET @sql = @sql + ' s.[Description] AS [Status], '
    SET @sql = @sql + ' tt.[Description] AS [Terms] '


    IF @PeriodProceduresID = 0
        BEGIN
            SET @sql = @sql +
               ' FROM AC_Statements_Temp t '
        END
    ELSE
        BEGIN
            SET @sql = @sql +
               ' FROM AC_Statements t '
        END


    SET @sql = @sql + ' INNER JOIN AC_Customers c '
    SET @sql = @sql + '     ON t.AC_Customers_ID = c.AC_Customers_ID '


    SET @sql = @sql + ' LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '     ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '     ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + ' LEFT JOIN Slu_AW_Credit_Terms tt '
    SET @sql = @sql + '     ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID '


    IF @Filter = 1
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Customer_Types o ' +
            '     ON c.Lup_AC_Customer_Types_ID = o.Lup_AC_Customer_Types_ID '
    ELSE
    IF @Filter = 2
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Customer_Groups o ' +
            '     ON c.Lup_AC_Customer_Groups_ID = o.Lup_AC_Customer_Groups_ID '
    ELSE
    IF @Filter = 3
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Account_Types o ' +
            '     ON c.Sys_AC_Account_Types_ID = o.Sys_AC_Account_Types_ID '
    ELSE
    IF @Filter = 4
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Account_Status o ' +
            '     ON c.Sys_AC_Account_Status_ID = o.Sys_AC_Account_Status_ID '
    ELSE
    IF @Filter = 5
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '
    ELSE
    IF @Filter = 6
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 7
        SET @sql = @sql +
            ' LEFT JOIN Slu_AW_Credit_Terms o ' +
            '     ON c.Slu_AW_Credit_Terms_ID = o.Slu_AW_Credit_Terms_ID '
    ELSE
    IF @Filter = 8
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Credit_Term_Types o ' +
            '     ON c.Sys_AC_Credit_Term_Types_ID = o.Sys_AC_Credit_Term_Types_ID '


    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '


    IF @PrintZeroBalances = 0
        BEGIN
            SET @sql = @sql + '   AND ISNULL(t.Account_Balance, 0) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY [Filter], [HeaderID], [FullName] '



    EXEC (@sql)




SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Age_Analysis_Rep
--Purpose       :Customer Age Analysis report by Salesperson
--Functionality :Combines INTERIM and PERIOD PROCEDURE options 
--Date          :2005/11/30
--Authors       :TB
--MODS          :
--2004.4.2      :27/11/08 - Added ISNULL validation on all ageing fields
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AC_Customer_Age_Analysis_Rep
    (
        @PeriodProceduresID int,
        @PrintZeroBalances tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' r.Description AS [RepName], '
    SET @sql = @sql + ' c.Lup_AS_Reps_ID AS [RepID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' t.FullName AS [FullName], '
    SET @sql = @sql + ' t.Customer_Number AS [CustomerNo], '
    SET @sql = @sql + ' t.Post_Address AS [PostAddress], '
    SET @sql = @sql + ' t.Post_Office AS [PostOffice], '
    SET @sql = @sql + ' t.Post_Code AS [PostCode], '
    SET @sql = @sql + ' t.Work_Email AS [Email], '
    SET @sql = @sql + ' ISNULL(t.Account_Balance, 0) AS [AccountBalance], '
    SET @sql = @sql + ' ISNULL(t.[Current], 0) AS [Current], '
    SET @sql = @sql + ' ISNULL(t.[30Days], 0) AS [30Days], '
    SET @sql = @sql + ' ISNULL(t.[60Days], 0) AS [60Days], '
    SET @sql = @sql + ' ISNULL(t.[90Days], 0) AS [90Days], '
    SET @sql = @sql + ' (ISNULL(t.[120Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[150Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[180+Days], 0)) AS [120+Days], '
    SET @sql = @sql + ' c.Contact_Name AS [ContactName], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' c.Initials AS [Initials], '
    SET @sql = @sql + ' dbo.fn_AC_Get_Last_Payment_Date(t.AC_Customers_ID) AS [LastPayDate], '
    SET @sql = @sql + ' dbo.fn_AC_Get_Last_Payment_Amount(t.AC_Customers_ID) AS [LastPayAmount], '
    SET @sql = @sql + ' c.Credit_Limit AS [CreditLimit], '
    SET @sql = @sql + ' c.Credit_Insurers_Limit AS [InsurerLimit], '
    SET @sql = @sql + ' c.Fax_No AS [FaxNo], '
    SET @sql = @sql + ' c.Cell_No AS [CellNo], '

    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') AS [TradeStyle], '
    SET @sql = @sql + ' ISNULL(c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.City, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Street_Post_Code, '''') AS [StreetAddr], '


    SET @sql = @sql + ' tt.[Description] AS [Terms], '
    SET @sql = @sql + ' s.[Description] AS [Status] '

    IF @PeriodProceduresID = 0
        BEGIN
            SET @sql = @sql +
               ' FROM AC_Statements_Temp t '
        END
    ELSE
        BEGIN
            SET @sql = @sql +
               ' FROM AC_Statements t '
        END


    SET @sql = @sql +
        ' INNER JOIN AC_Customers c ' +
        '     ON t.AC_Customers_ID = c.AC_Customers_ID ' +
        ' LEFT JOIN Lup_AS_Reps r ' +
        '     ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID ' +
        ' LEFT JOIN Sys_AC_Account_Status s ' +
        '     ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID ' +
        ' LEFT JOIN Slu_AW_Credit_Terms tt ' +
        '     ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID ' +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
        '       AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '


    IF @PrintZeroBalances = 0
        BEGIN
            SET @sql = @sql + '       AND ISNULL(t.Account_Balance, 0) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY r.Description, c.Lup_AS_Reps_ID, t.FullName '



    EXEC (@sql)




SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Ageing
--Purpose       :Retrieves Customer Statement data
--Tables        :AC_Statements, AC_Statement_Details
--Parameters    :
--Date          :2002/03/05
--Authors       :TB
--Version       :1.0.0
--MODS          :16/08/02 - Added @PrintZeroBalances parameter
--              :29/01/03 - Fetch Credit Terms and not Credit Term Types
--              :15/09/03 - Added @CompanyID and validate in WHERE clause
--2004.4.2      :27/11/08 - Added ISNULL validation on all ageing fields
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AC_Customer_Ageing
    (
        @PeriodProceduresID int,
        @PrintZeroBalances tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE
        @sql varchar(8000)

    SET @sql = ' SELECT ' +
        ' t.AC_Customers_ID AS [CustomerID], ' +
        ' t.FullName AS [FullName], ' +
        ' t.Customer_Number AS [CustomerNo], ' +
        ' t.Post_Address AS [PostAddress], ' +
        ' t.Post_Office AS [PostOffice], ' +
        ' t.Post_Code AS [PostCode], ' +
        ' t.Work_Email AS [Email], ' +
        ' ISNULL(t.Account_Balance, 0) AS [AccountBalance], ' +
        ' ISNULL(t.[Current], 0) AS [Current], ' +
        ' ISNULL(t.[30Days], 0) AS [30Days], ' +
        ' ISNULL(t.[60Days], 0) AS [60Days], ' +
        ' ISNULL(t.[90Days], 0) AS [90Days], ' +
        ' (ISNULL(t.[120Days], 0) + ' +
        '  ISNULL(t.[150Days], 0) + ' +
        '  ISNULL(t.[180+Days], 0)) AS [120+Days], ' +
        ' c.Contact_Name AS [ContactName], ' +
        ' c.Work_Tel_No AS [WorkTelNo], ' +
        ' c.Initials AS [Initials], ' +
        ' c.Credit_Limit AS [CreditLimit], ' +
        ' c.Fax_No AS [FaxNo], ' +
        ' c.Cell_No AS [CellNo], ' +
        ' tt.[Description] AS [Terms], ' +
        ' s.[Description] AS [Status] ' +
   ' FROM AC_Statements t ' +
        ' INNER JOIN AC_Customers c ' +
        '     ON t.AC_Customers_ID = c.AC_Customers_ID ' +
        ' LEFT JOIN Sys_AC_Account_Status s ' +
        '     ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID ' +
        ' LEFT JOIN Slu_AW_Credit_Terms tt ' +
        '     ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID ' +
    ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


--WHERE
    IF @PrintZeroBalances = 1
        BEGIN
            SET @sql = @sql +
                ' AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '
        END
    ELSE
        BEGIN
            SET @sql = @sql +
                ' AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' AND ' +
                '       ISNULL(t.Account_Balance, 0) <> 0 '
        END

    SET @sql = @sql +
       ' ORDER BY t.FullName '

--> RUN the script
--  --------------
    EXEC (@sql)


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Ageing_Temp
--Purpose       :Retrieves Ad-Hoc Customer Ageing data
--Tables        :AC_Statements_Temp, AC_Statement_Details_Temp
--Parameters    :
--Date          :2002/06/21
--Authors       :TB
--Version       :1.0.0
--MODS          :16/08/02 - Added @PrintZeroBalances parameter
--              :29/01/03 - Fetch Credit Terms and not Credit Term Types
--2004.4.2      :27/11/08 - Added ISNULL validation on all ageing fields
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AC_Customer_Ageing_Temp
    (
        @PeriodProceduresID int,
        @PrintZeroBalances tinyint
    )

AS

SET NOCOUNT ON

    DECLARE
        @sql varchar(2000)

    SET @sql = ' SELECT ' +
        ' t.AC_Customers_ID AS [CustomerID], ' +
        ' t.FullName AS [FullName], ' +
        ' t.Customer_Number AS [CustomerNo], ' +
        ' t.Post_Address AS [PostAddress], ' +
        ' t.Post_Office AS [PostOffice], ' +
        ' t.Post_Code AS [PostCode], ' +
        ' t.Work_Email AS [Email], ' +
        ' ISNULL(t.Account_Balance, 0) AS [AccountBalance], ' +
        ' ISNULL(t.[Current], 0) AS [Current], ' +
        ' ISNULL(t.[30Days], 0) AS [30Days], ' +
        ' ISNULL(t.[60Days], 0) AS [60Days], ' +
        ' ISNULL(t.[90Days], 0) AS [90Days], ' +
        ' (ISNULL(t.[120Days], 0) + ' +
        '  ISNULL(t.[150Days], 0) + ' +
        '  ISNULL(t.[180+Days], 0)) AS [120+Days], ' +
        ' c.Contact_Name AS [ContactName], ' +
        ' c.Work_Tel_No AS [WorkTelNo], ' +
        ' c.Initials AS [Initials], ' +
        ' c.Credit_Limit AS [CreditLimit], ' +
        ' c.Fax_No AS [FaxNo], ' +
        ' c.Cell_No AS [CellNo], ' +
        ' tt.[Description] AS [Terms], ' +
        ' s.[Description] AS [Status] ' +
   ' FROM AC_Statements_Temp t ' +
        ' INNER JOIN AC_Customers c ' +
        '     ON t.AC_Customers_ID = c.AC_Customers_ID ' +
        ' LEFT JOIN Sys_AC_Account_Status s ' +
        '     ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID ' +
        ' LEFT JOIN Slu_AW_Credit_Terms tt ' +
        '     ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID '

--WHERE
    IF @PrintZeroBalances = 1
        BEGIN
            SET @sql = @sql +
                ' WHERE t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '
        END
    ELSE
        BEGIN
            SET @sql = @sql +
                ' WHERE t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' AND ' +
                '       ISNULL(t.Account_Balance, 0) <> 0 '
        END

    SET @sql = @sql +
       ' ORDER BY t.FullName '

--> RUN the script
--  --------------
    EXEC (@sql)


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Audit_Trail
--Purpose       :Customer Transactions Audit Trail Report
--Date          :2003/10/15
--Authors       :TB
--Version       :1.0.0
--MODS:         :28/06/04 - Added formatting of the [TranDate] field
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AC_Customer_Audit_Trail
    (
            @CompanyID int,
            @ChkAllCustomers int,
            @CustomerID int,
            @TranTypes tinyint,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 1627
-- SET @TranTypes = 0
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '

    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '

--    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' CONVERT(CHAR(10), h.Transaction_Date, 121) AS [TranDate], '

    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '

    SET @sql = @sql + ' h.Total_Cost AS [Cost], '
    SET @sql = @sql + ' h.Amount AS [Amount], '
    SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' h.Total_Discount_Amount AS [Discount], '
    SET @sql = @sql + ' h.Total_Amount AS [Total], '
    SET @sql = @sql + ' h.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) AS [Balance], '

    SET @sql = @sql + ' til.[Description] AS [Till], '
    SET @sql = @sql + ' ISNULL(cas.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(cas.Surname, '''') AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '

    SET @sql = @sql + ' h.Cashed_Up AS [Cashed Up], '
    SET @sql = @sql + ' h.Day_End AS [Day End], '
    SET @sql = @sql + ' LEFT(ISNULL(g.Description, ''''), 20) AS [GL Account], '
    SET @sql = @sql + ' h.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User], '
    SET @sql = @sql + ' act.[Description] AS [Active] '
    
    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users cas '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = cas.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN AB_Accounts g '
    SET @sql = @sql + '          ON h.AB_Accounts_ID = g.AB_Accounts_ID '

    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Active act '
    SET @sql = @sql + '          ON h.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    SET @sql = @sql +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 4 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 5 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 7 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 15 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 18 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 21 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 22 '

    IF @TranTypes = 1          --ALL Transaction Types
        BEGIN
            SET @sql = @sql + 
                '    OR h.Sys_AW_Transaction_Types_ID = 1 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 2 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 13 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 16 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 17) '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ') '
        END


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY h.Transaction_Date ASC '


    EXEC (@sql)


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Bin_Exceptions
--Purpose       :List products sold to customers with incorrect bin selection
--Functionality :Tyre Corporation. Customer should only be able to buy out of bins linked to them
--Date          :2016-07-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Bin_Exceptions]
    (
		@ChkAllCustomers	int,
		@CustomerID			int,
		@ChkDates			int,
		@StartDate			datetime,
		@EndDate			datetime,
		@ChkBin				int,
        @Bin_ID				int,
		@ShowException		tinyint,
        @Sort				tinyint,
        @CompanyID			int
    )
AS

-- EXEC sp_RPT_AC_Customer_Bin_Exceptions 0, '2013-01-01', '2016-06-01', 'Customer', 1

SET NOCOUNT ON

	DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '
    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '    
    SET @sql = @sql + ' p.Product_Code AS [Code], '        
    SET @sql = @sql + ' p.[Description] As [Product], '            
    SET @sql = @sql + ' d.Quantity As [Quantity], '                
    SET @sql = @sql + ' y.[Description] As [TranType], '   
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '                     
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
	SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + u.UserName, ''''))) AS [User], '
	SET @sql = @sql + ' b.[Description] As [Bin] '	
	SET @sql = @sql + ' FROM AS_Transactions t '
	SET @sql = @sql + ' 	Inner Join AS_Transaction_Details d '
	SET @sql = @sql + ' 		On t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + ' 	Inner Join AC_Customers c '
	SET @sql = @sql + ' 		On t.AC_Customers_ID = c.AC_Customers_ID '
	SET @sql = @sql + ' 	Inner Join AW_Users u '
	SET @sql = @sql + ' 		On t.[User_ID] = u.AW_Users_ID '
	SET @sql = @sql + ' 	Inner Join AP_Products p '
	SET @sql = @sql + ' 		On d.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + ' 	Inner Join Sys_AW_Transaction_Types y '
	SET @sql = @sql + ' 		On t.Sys_AW_Transaction_Types_ID = y.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' 	Inner Join Lup_AP_Product_Bins b '
	SET @sql = @sql + ' 		On d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID '

	SET @sql = @sql +
		' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
		
    IF @ChkDates = 1    --From/To Dates
	BEGIN
		SET @sql = @sql + '  AND t.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
		SET @sql = @sql + '  AND t.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
	END

	IF @ShowException = 1
	BEGIN
		SET @sql = @sql + ' AND d.Lup_AP_Product_Bins_ID NOT IN (SELECT Lup_AP_Product_Bins_ID FROM AC_Product_Bins Where AC_Customers_ID = t.AC_Customers_ID AND SLU_AW_Active_ID = 1) '
	END
	
    IF @ChkAllCustomers = 0    --Single Customer Account
    BEGIN
        SET @sql = @sql + ' AND t.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    END

	IF @ChkBin = 0
	BEGIN
		SET @sql = @sql + ' AND d.Lup_AP_Product_Bins_ID = ' + CONVERT(varchar(10), @Bin_ID) + ' '
	END

    IF @Sort = 0        --Transaction Date
    BEGIN
        SET @sql = @sql + ' ORDER BY [TranDate] ASC '
    END

    IF @Sort = 1        --Transaction Number
    BEGIN
        SET @sql = @sql + ' ORDER BY [TranNo] ASC '
    END

    IF @Sort = 2        --Customer
    BEGIN
        SET @sql = @sql + ' ORDER BY [Customer] ASC '
    END

    IF @Sort = 3        --Product Code
    BEGIN
        SET @sql = @sql + ' ORDER BY [Code] ASC '
    END

    IF @Sort = 4        --Product Description
    BEGIN
        SET @sql = @sql + ' ORDER BY [Product] ASC '
    END

    IF @Sort = 5        --Product Bin
    BEGIN
        SET @sql = @sql + ' ORDER BY [Bin] ASC '
    END

	EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













----------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Cash_Terms_Exceeded
--Purpose       :Retrieves ALL Customers with CASH Terms Exceeded
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AC_Customer_Cash_Terms_Exceeded
    (
        @CompanyID int 
    )

AS

SET NOCOUNT ON


	SELECT
        a.AW_User_Companies_ID AS [CompanyID],
        a.AC_Customers_ID AS [CustomerID],
        ISNULL(a.Surname, '') + ISNULL(', ' + a.FirstNames, '') AS [Customer],
        ISNULL(a.Customer_Number, '') AS [CustomerNo], 
        ISNULL(a.Contact_Name, '') AS [ContactName], 
        ISNULL(a.Home_Email, '') AS [ContactEmail],
        ISNULL(a.Work_Tel_No, '') AS [WorkTel],
        ISNULL(a.Cell_No, '') AS [ContactCell],
        ISNULL(b.[Description], '') AS [CreditTerms],
        ISNULL(c.[Description], '') AS [TermsOfSale],
        ISNULL(a.Credit_Limit, 0) AS [CreditLimit], 
        ISNULL(dbo.fn_AC_Customer_Balance( a.AC_Customers_ID ), 0) AS [Balance]

	FROM AC_Customers a
        LEFT JOIN Slu_AW_Credit_Terms b
            ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Credit_Term_Types c
            ON c.Sys_AC_Credit_Term_Types_ID = a.Sys_AC_Credit_Term_Types_ID
	WHERE AW_User_Companies_ID = @CompanyID AND
          b.Terms_Value = 0 AND
          dbo.fn_AC_Customer_Balance( a.AC_Customers_ID ) <> 0


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Consignment_Listing
--Purpose       :Customer Consignment Stock Listing
--Date          :2015/05/21
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Consignment_Listing]
(
        @CompanyID int,
        @CustomerID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime
)        
AS


IF @ChkDates = 1
BEGIN
	IF @CustomerID = 0
		SELECT c.AC_Customers_ID, 
				ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
				t.Transaction_Date, 
				t.Transaction_Number, 
				p.Product_Code, 
				p.Description, 
 				d.Quantity   
					- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Qty],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * dbo.fn_AP_Get_Product_Cost(d.AP_Products_ID) As [Unit_Cost],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * Unit_Price As [Unit_Price]				
								
		FROM AS_Transactions t
			INNER JOIN AS_Transaction_Details d
				ON t.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			INNER JOIN AP_Products p
				ON d.AP_Products_ID = p.AP_Products_ID	
		WHERE t.Sys_AW_Transaction_Types_ID = 33  --Consignment Stock Note
		AND d.Quantity   
				- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
				- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
		AND t.Transaction_Date BETWEEN @StartDate AND @EndDate
		ORDER BY t.Transaction_Date, p.Product_Code 				 
	ELSE
		SELECT c.AC_Customers_ID, 
				ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
				t.Transaction_Date, 
				t.Transaction_Number, 
				p.Product_Code, 
				p.Description, 
 			--	d.Quantity   
				--	- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
				--	- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Qty],
				--Unit_Cost,
				--Unit_Price
 				d.Quantity   
					- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Qty],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * dbo.fn_AP_Get_Product_Cost(d.AP_Products_ID) As [Unit_Cost],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * Unit_Price As [Unit_Price]				
								
		FROM AS_Transactions t
			INNER JOIN AS_Transaction_Details d
				ON t.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			INNER JOIN AP_Products p
				ON d.AP_Products_ID = p.AP_Products_ID	
		WHERE t.Sys_AW_Transaction_Types_ID = 33  --Consignment Stock Note
		AND d.Quantity   
				- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
				- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
		AND c.AC_Customers_ID = @CustomerID
		AND t.Transaction_Date BETWEEN @StartDate AND @EndDate		
		ORDER BY t.Transaction_Date, p.Product_Code 				 
END		
ELSE
BEGIN
	IF @CustomerID = 0
		SELECT c.AC_Customers_ID, 
				ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
				t.Transaction_Date, 
				t.Transaction_Number, 
				p.Product_Code, 
				p.Description, 
 				d.Quantity   
					- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Qty],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * dbo.fn_AP_Get_Product_Cost(d.AP_Products_ID) As [Unit_Cost],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * Unit_Price As [Unit_Price]				
								
		FROM AS_Transactions t
			INNER JOIN AS_Transaction_Details d
				ON t.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			INNER JOIN AP_Products p
				ON d.AP_Products_ID = p.AP_Products_ID	
		WHERE t.Sys_AW_Transaction_Types_ID = 33  --Consignment Stock Note
		AND d.Quantity   
				- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
				- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
		ORDER BY t.Transaction_Date, p.Product_Code 				 
	ELSE
		SELECT c.AC_Customers_ID, 
				ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
				t.Transaction_Date, 
				t.Transaction_Number, 
				p.Product_Code, 
				p.Description, 
 				d.Quantity   
					- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Qty],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * dbo.fn_AP_Get_Product_Cost(d.AP_Products_ID) As [Unit_Cost],
				(
					d.Quantity   
						- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
						- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)
				) * Unit_Price As [Unit_Price]				
		FROM AS_Transactions t
			INNER JOIN AS_Transaction_Details d
				ON t.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			INNER JOIN AP_Products p
				ON d.AP_Products_ID = p.AP_Products_ID	
		WHERE t.Sys_AW_Transaction_Types_ID = 33  --Consignment Stock Note
		AND d.Quantity   
				- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
				- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
		AND c.AC_Customers_ID = @CustomerID
		ORDER BY t.Transaction_Date, p.Product_Code 				 
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















----------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Credit_Limit_Exceeded
--Purpose       :Retrieves ALL Customers with CREDIT LIMIT Exceeded
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AC_Customer_Credit_Limit_Exceeded
    (
        @CompanyID int 
    )

AS

SET NOCOUNT ON


	SELECT
        a.AW_User_Companies_ID AS [CompanyID],
        a.AC_Customers_ID AS [CustomerID],
        ISNULL(a.Surname, '') + ISNULL(', ' + a.FirstNames, '') AS [Customer],
        ISNULL(a.Customer_Number, '') AS [CustomerNo], 
        ISNULL(a.Contact_Name, '') AS [ContactName], 
        ISNULL(a.Home_Email, '') AS [ContactEmail],
        ISNULL(a.Work_Tel_No, '') AS [WorkTel],
        ISNULL(a.Cell_No, '') AS [ContactCell],
        ISNULL(b.[Description], '') AS [CreditTerms],
        ISNULL(c.[Description], '') AS [TermsOfSale],
        ISNULL(d.[Description], '') AS [AccountType],
--        ISNULL(dbo.fn_AC_Get_Customer_Status( a.AC_Customers_ID ), '') AS [AccountStatus],
        ISNULL(e.[Description], '') AS [AccountStatus],
        ISNULL(a.Credit_Limit, 0) AS [CreditLimit], 
        ISNULL(dbo.fn_AC_Customer_Balance( a.AC_Customers_ID ), 0) AS [Balance],
        ISNULL(dbo.fn_AC_Customer_Balance( a.AC_Customers_ID ), 0) - ISNULL(a.Credit_Limit, 0) AS [OverLimit]
	FROM AC_Customers a
        LEFT JOIN Slu_AW_Credit_Terms b
            ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Credit_Term_Types c
            ON c.Sys_AC_Credit_Term_Types_ID = a.Sys_AC_Credit_Term_Types_ID
        LEFT JOIN Lup_AC_Customer_Types d
            ON d.Lup_AC_Customer_Types_ID = a.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AC_Account_Status e
            ON e.Sys_AC_Account_Status_ID = a.Sys_AC_Account_Status_ID

	WHERE a.AW_User_Companies_ID = @CompanyID AND
          b.Terms_Value > 0 AND
          dbo.fn_AC_Customer_Balance( a.AC_Customers_ID ) > ISNULL(a.Credit_Limit, 0)
    ORDER BY [Customer]


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Credit_Terms_Exceeded
--Purpose       :Retrieves ALL Customers with Credit Terms Exceeded
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
----------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AC_Customer_Credit_Terms_Exceeded
    (
        @Date datetime,
        @CompanyID int,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

AS

SET NOCOUNT ON

    DECLARE @Midnight datetime

    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @Date), 0, 1)))

  	SELECT
        a.AW_User_Companies_ID AS [CompanyID],
        a.AC_Customers_ID AS [CustomerID],
        ISNULL(a.Surname, '') + ISNULL(', ' + a.FirstNames, '') AS [Customer],
        ISNULL(a.Customer_Number, '') AS [CustomerNo], 
        ISNULL(a.Contact_Name, '') AS [ContactName], 
        ISNULL(a.Home_Email, '') AS [ContactEmail],
        ISNULL(a.Work_Tel_No, '') AS [WorkTel],
        ISNULL(a.Cell_No, '') AS [ContactCell],
        ISNULL(b.[Description], '') AS [CreditTerms],
        ISNULL(c.[Description], '') AS [TermsOfSale],
        ISNULL(a.Credit_Limit, 0) AS [CreditLimit],
        ISNULL(dbo.fn_AC_Customer_Balance( a.AC_Customers_ID ), 0) AS [Balance],
        ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                    (a.Sys_AC_Credit_Term_Types_ID,
                     b.Terms_Value,
                     a.AC_Customers_ID,
                     @Midnight,
                     @D1,
                     @D2,
                     @D3,
                     @D4,
                     @D5,
                     @D6,
                     @D7), 0) AS [Overdue]

	FROM AC_Customers a
        LEFT JOIN Slu_AW_Credit_Terms b
            ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Credit_Term_Types c
            ON c.Sys_AC_Credit_Term_Types_ID = a.Sys_AC_Credit_Term_Types_ID
	WHERE AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AC_Customer_Overdue_Amount
                    (a.Sys_AC_Credit_Term_Types_ID,
                     b.Terms_Value,
                     a.AC_Customers_ID,
                     @Midnight,
                     @D1,
                     @D2,
                     @D3,
                     @D4,
                     @D5,
                     @D6,
                     @D7) > 0
    ORDER BY [Customer]


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_History
--Purpose       :
--Functionality :
--Date          :2003/05/01
--Authors       :TB
--Version       :1.0.0
--MODS          :27/10/03 - Added 4 new Bank Code columns to AC_History_Bankers
-------------------------------------------------------------------------------
CREATE                     PROCEDURE    sp_RPT_AC_Customer_History
    (
        @Option tinyint,
    	@Company_ID int,
    	@Customer_ID int
    )

AS

SET NOCOUNT ON

    IF @Option = 0
        SELECT
            a.AC_History_Status_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.Description AS [Status], 
            a.Status_Reason AS [Reason], 
            a.Date_Changed AS [Date Changed], 
            a.Date_Captured AS [Date Captured], 
            b.UserName AS [User]
        FROM AC_History_Status a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Sys_AC_Account_Status c
                ON a.Sys_AC_Account_Status_ID = c.Sys_AC_Account_Status_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Changed DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 1
        SELECT
            a.AC_History_Credit_Limits_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            c.Description AS [Credit Terms], 
            d.Description AS [Credit Term Type], 
            a.New_Limit AS [New Limit], 
            a.Limit_Reason AS [Reason], 
            a.Date_Changed AS [Date Changed], 
            a.Date_Captured AS [Date Captured], 
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Credit_Limits a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AW_Credit_Terms c
                ON a.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
            INNER JOIN Sys_AC_Credit_Term_Types d
                ON a.Sys_AC_Credit_Term_Types_ID = d.Sys_AC_Credit_Term_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Changed DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 2
        SELECT
            a.AC_History_Info_Reports_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            c.Description AS [Report Type], 
            a.Report_Date AS [Report Date], 
            a.Date_Captured AS [Date Captured], 
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Info_Reports a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AW_Info_Report_Types c
                ON a.Slu_AW_Info_Report_Types_ID = c.Slu_AW_Info_Report_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Report_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 3
        SELECT
            a.AC_History_Notarial_Bonds_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            c.Description AS [Bond Type],
            a.Bond_Holder AS [BondHolder],
            a.Bond_Amount AS [BondAmount],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
            a.Date_Registered AS [Date Registered],
            a.Collateral_Provider AS [Collateral],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Notarial_Bonds a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Bond_Types c
                ON a.Slu_AC_Bond_Types_ID = c.Slu_AC_Bond_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 4
        SELECT
            a.AC_History_Ratings_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            c.Description AS [Rating],
            a.Rating_Notes AS [Notes],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Ratings a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Ratings c
                ON a.Slu_AC_Ratings_ID = c.Slu_AC_Ratings_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 5
        SELECT
            a.AC_History_KIScores_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            c.Description AS [KI Score],
            a.Notes AS [Notes],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_KIScores a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_KI_Scores c
                ON a.Slu_AC_KI_Scores_ID = c.Slu_AC_KI_Scores_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 6
        SELECT
            a.AC_History_ITCScores_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID], 
            c.Description AS [ITC Score],
            a.Notes AS [Notes],
            a.Effective_Date AS [Effective Date],
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_ITCScores a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_ITC_Scores c
                ON a.Slu_AC_ITC_Scores_ID = c.Slu_AC_ITC_Scores_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 7
        SELECT
            a.AC_History_Trade_References_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.Description AS [Security Type], 
            a.Date_of_Reference AS [Date of Reference], 
            a.Supplier_Name AS [Supplier Name], 
            a.Contact_Name AS [Contact Name], 
            a.Contact_Position AS [Contact Position], 
            a.Telephone_Number AS [Tel No], 
            a.Fax_Number AS [Fax No], 
            a.Period_Known AS [Period Known], 
            a.Average_per_Month AS [Ave per Month], 
            a.Reference_Comments AS [Comments], 
            a.Highest_Amount AS [Highest Amount], 
            a.Account_Limit AS [Account Limit], 
            a.Terms_Given AS [Terms Given], 
            a.Terms_Taken AS [Terms Taken], 
            (ISNULL(a.Current_Balance, 0) +
             ISNULL(a.Days_30, 0) +
             ISNULL(a.Days_60, 0) +
             ISNULL(a.Days_90, 0) +
             ISNULL(a.Days_120, 0) +
             ISNULL(a.Days_150, 0) +
             ISNULL(a.Days_180, 0)) AS [Account Balance], 
            a.Current_Balance AS [Current Balance], 
            a.Days_30 AS [30 Days], 
            a.Days_60 AS [60 Days], 
            a.Days_90 AS [90 Days], 
            a.Days_120 AS [120 Days], 
            a.Days_150 AS [150 Days], 
            a.Days_180 AS [180 Days], 
            a.Past_Due_Amount AS [Past Due Amount], 
            a.Limit_Of_Guarantee AS [Limit of Guarantee], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Trade_References a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Security_Types c
                ON a.Slu_AC_Security_Types_ID = c.Slu_AC_Security_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_of_Reference DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 8
        SELECT
            a.AC_History_Default_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.Description AS [Adverse Reason], 
            a.Adverse_Source AS [Adverse Source], 
            a.Date_Reported AS [Date Reported], 
            a.Dispute_Amount AS [Dispute Amount], 
            a.Days_Overdue AS [Days Overdue], 
            a.Adverse_Comments AS [Comments], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Default a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Adverse_Reasons c
                ON a.Slu_AC_Adverse_Reasons_ID = c.Slu_AC_Adverse_Reasons_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Reported DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 9
        SELECT
            a.AC_History_Motion_Roll_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.[Description] AS [Nature Of Action], 
            d.[Description] AS [Lawsuit Type], 
            e.[Description] AS [Court], 
            a.Respondent_Name AS [Respondent], 
            a.Applicant AS [Applicant], 
            a.Application_Amount AS [Application Amount], 
            a.Case_Number AS [Case Number], 
            a.Item_Number AS [Item Number], 
            a.Hearing_Date AS [Hearing Date], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Motion_Roll a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AW_Nature_Of_Action c
                ON a.Slu_AW_Nature_Of_Action_ID = c.Slu_AW_Nature_Of_Action_ID
            INNER JOIN Slu_AW_Lawsuit_Types d
                ON a.Slu_AW_Lawsuit_Types_ID = d.Slu_AW_Lawsuit_Types_ID
            INNER JOIN Slu_AW_Courts e
                ON a.Slu_AW_Courts_ID = e.Slu_AW_Courts_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Hearing_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 10
        SELECT
            a.AC_History_Judgements_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.[Description] AS [Nature Of Action], 
            d.[Description] AS [Court], 
            a.Defendant_Name AS [Defendant], 
            a.Plaintiff_Name AS [Plaintiff], 
            a.Judgement_Amount AS [Judgement Amount], 
            a.Case_Number AS [Case Number], 
            a.Date_Of_Judgement AS [Judgement Date], 
            a.Default_Judgement AS [Default Judgement], 
            a.Date_Rescinded AS [Date Rescinded], 
            a.Rescindment_Reason AS [Rescindment Reason], 
            a.Date_Abandoned AS [Date Abandoned], 
            a.Abandonment_Reason AS [Abandonment Reason], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Judgements a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AW_Nature_Of_Action c
                ON a.Slu_AW_Nature_Of_Action_ID = c.Slu_AW_Nature_Of_Action_ID
            INNER JOIN Slu_AW_Courts d
                ON a.Slu_AW_Courts_ID = d.Slu_AW_Courts_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Of_Judgement DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 11
        SELECT
            a.AC_History_RD_Cheques_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Date_Reported AS [Date_Reported], 
            a.Cheque_Amount AS [Cheque Amount], 
            a.Comments AS [Comments], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_RD_Cheques a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Reported DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 12
        SELECT
            a.AC_History_Principals_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Name, 
            a.ID_Number AS [ID Number], 
            c.[Description] AS [Principal Type], 
            a.Home_Tel_No AS [Home Tel], 
            a.Cell_No AS [Cell No], 
            a.E_Mail AS [E-mail Address], 
            a.Home_Address AS [Home Address], 
            a.Date_Appointed AS [Date Appointed], 
            a.Date_Terminated AS [Date Terminated], 
            a.Primary_Function AS [Primary Function], 
            a.Principal_Comments AS [Comments], 
            a.Status_Ind AS [Status Ind], 
            a.Status_Date AS [Status Date], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Principals a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Principal_Types c
                ON a.Slu_AC_Principal_Types_ID = c.Slu_AC_Principal_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Name DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 13
        SELECT
            a.AC_History_Principal_Properties_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.AC_History_Principals_ID AS [PrincipalID], 
            c.Name, 
            a.Description, 
            a.Registered_Owner AS [Registered Owner], 
            a.Title_Deed_Number AS [Title Deed No], 
            a.Property_Size AS [Size], 
            a.Date_Purchased AS [Date Purchased], 
            a.Purchase_Price AS [Purchase Price], 
            a.Address1 AS [Address1], 
            a.Address2 AS [Address2], 
            a.Suburb AS [Suburb], 
            a.City AS [City], 
            a.Post_Code AS [Post Code], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Principal_Properties a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN AC_History_Principals c
                ON a.AC_History_Principals_ID = c.AC_History_Principals_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY c.Name, a.Date_Purchased DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 14
        SELECT
            a.AC_History_Shareholders_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Shareholder_Name AS [Name], 
            a.Interest_Percent AS [Interest %], 
            a.Number_Of_Shares AS [No Of Shares], 
            c.[Description] AS [Shareholding Type], 
            a.Members_Contribution AS [Members Contrib], 
            a.Par_Value_Of_Holding AS [Par Value], 
            a.Estimated_Valuation AS [Valuation], 
            a.Controlling_Shareholder AS [Controlling Shareholder], 
            a.Parent_Company AS [Parent Company], 
            a.Holding_Company AS [Holding Company], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Shareholders a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Shareholding_Types c
                ON a.Slu_AC_Shareholding_Types_ID = c.Slu_AC_Shareholding_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 15
        SELECT
            a.AC_History_Auditors_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Firm_Name AS [Firm Name], 
            a.Audit_Manager AS [Audit Manager], 
            a.Registration_Date AS [Reg Date], 
            c.[Description] AS [Profession Type], 
            d.[Description] AS [Auditor Ranking], 
            a.Profession_Number AS [Profession No], 
            a.Profession_Date_Changed AS [Date Changed], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Auditors a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Profession_Types c
                ON a.Slu_AC_Profession_Types_ID = c.Slu_AC_Profession_Types_ID
            INNER JOIN Slu_AC_Auditor_Rankings d
                ON a.Slu_AC_Auditor_Rankings_ID = d.Slu_AC_Auditor_Rankings_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 16
        SELECT
            a.AC_History_Associates_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Associate_Name AS [Associate Name], 
            c.[Description] AS [Association Type], 
            a.Shareholding_Percentage AS [Shareholding %], 
            d.[Description] AS [Shareholding Type], 
            a.Date_Acquired AS [Date Acquired], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Associates a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Association_Types c
                ON a.Slu_AC_Association_Types_ID = c.Slu_AC_Association_Types_ID
            INNER JOIN Slu_AC_Shareholding_Types d
                ON a.Slu_AC_Shareholding_Types_ID = d.Slu_AC_Shareholding_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Acquired DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 17
        SELECT
            a.AC_History_Bankers_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.[Description] AS [Bank], 
            a.Bank_Branch AS [Branch], 
            a.Bank_Branch_Code AS [Branch Code], 
            a.Account_Name AS [Account Name], 
            a.Account_Number AS [Account Number], 
            a.Slu_AC_Bank_Codes_ID AS [Bank Code], 
            a.Bank_Code_Amount AS [Code Amount], 
            a.Slu_AW_Credit_Terms_ID AS [Code Terms], 
            a.Banker_Comments AS [Code Comments], 
            a.Date_Opened AS [Date Opened], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Bankers a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AW_Banks c
                ON a.Slu_AW_Banks_ID = c.Slu_AW_Banks_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Opened DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 18
        SELECT
            a.AC_History_Balance_Sheets_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Statement_Date AS [Statement Date], 
            a.Property_Plant_and_Equipment AS [Prop Plant Equip], 
            a.Investment_Property AS [Invest Prop], 
            a.Investments_and_Loans AS [Invest &_Loans], 
            a.Investments_and_Finance_Leases AS [Invest & Fin Leases], 
            a.Forward_Exchange_Contract_Asset AS [Fwd Exch Contract Asset], 
            a.Inventories AS [Inventories], 
            a.Trade_and_Other_Receivables AS [Trade & Other Receivables], 
            a.Prepayments AS [Prepayments], 
            a.Cash_and_Cash_Equivalents AS [Cash], 
            a.Issued_Capital AS [Issued Capital], 
            a.Reserves AS [Reserves], 
            a.Accumulated_Profit_Loss AS [Accum Profit/Loss], 
            a.Interest_Bearing_Borrowings AS [Int Bearing Borrowings], 
            a.Deferred_Taxation AS [Deferred Taxation], 
            a.Retirement_Benefit_Obligations AS [Retire Benefit Obligs], 
            a.Trade_and_Other_Payables AS [Trade & Other Payables], 
            a.Taxation AS [Taxation], 
            a.Dividend_Declared AS [Dividend Declared], 
            a.Bank_Overdraft AS [Bank Overdraft], 
            a.Overdraft_Facility AS [Overdraft Facility], 
            a.Current_portion_of_Interest_Bearing_Borrowings AS [Curr port of Int Bear Borrow], 
            a.Warranty_Provision AS [Warranty Provision], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Balance_Sheets a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Statement_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 19
        SELECT
            a.AC_History_Income_Statements_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Statement_Date AS [Statement Date], 
            a.Revenue, 
            a.Cost_of_Sales AS [Cost of Sales], 
            a.Other_Income AS [Other Income], 
            a.Fleet_Rental AS [Fleet Rental], 
            a.Distribution_Expenses AS [Distrib Exp], 
            a.Auditors_Remuneration AS [Auditors Remun], 
            a.Depreciation AS [Depreciation], 
            a.Prepayments AS [Prepayments], 
            a.Profit_Loss_on_disposal_of_Assets AS [P/L on disposal of Assets], 
            a.Permanent_decline_in_value_of_Investment_Property AS [Permanent decline in value of Invest Prop], 
            a.Fees_for_Services AS [Fees for Services], 
            a.Rental_on_Operating_Leases AS [Rent on Operating Leases], 
            a.Forex_Gains_Losses AS [Forex Gains Losses], 
            a.Staff_Costs AS [Staff Costs], 
            a.Other_Long_Term_Employee_Benefits AS [Other Long Term Employee Benefits], 
            a.Directors_Emoluments AS [Directors Emoluments], 
            a.Other_Expenses AS [Other Expenses], 
            a.Financing_Costs AS [Financing Costs], 
            a.Financing_Costs_Capitalized AS [Fin Costs Capitalized], 
            a.Taxation AS [Taxation], 
            a.Extraordinary_Items AS [Extraordinary Items], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Income_Statements a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Statement_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 20
        SELECT
            a.AC_History_Bonds_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            a.Bond_Account_Number AS [Bond Acct No], 
            a.Bond_Holder AS [Bond Holder], 
            a.Bond_Amount AS [Bond Amount], 
            c.[Description] AS [Bond Type], 
            a.Repayment_Period AS [Repay Period], 
            a.Repayment_Amount AS [Repay Amount], 
            a.Effective_date AS [Effective Date], 
            a.Date_Registered AS [Date Registered], 
            a.Collateral_Provider AS [Collateral Provider], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Bonds a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Bond_Types c
                ON a.Slu_AC_Bond_Types_ID = c.Slu_AC_Bond_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Effective_Date DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 21
        SELECT
            a.AC_History_Properties_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],
            c.[Description] AS [Bond Type], 
            a.Description, 
            a.Registered_Owner AS [Registered Owner], 
            a.Title_Deed_Number AS [Title Deed No], 
            a.Property_Size AS [Size], 
            a.Date_Purchased AS [Date Purchased], 
            a.Purchase_Price AS [Price], 
            a.Address1 AS [Address1], 
            a.Address2 AS [Address2], 
            a.Suburb AS [Suburb], 
            a.City AS [City], 
            a.Post_Code AS [Post Code], 
            a.Date_Captured AS [Date Captured],
            b.UserName AS [User],
            a.[User_ID] AS [UserID],
            a.AW_User_Companies_ID AS [CompanyID], 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_History_Properties a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Slu_AC_Bond_Types c
                ON a.Slu_AC_Bond_Types_ID = c.Slu_AC_Bond_Types_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Purchased DESC
----------------------------------------------------------------------
    ELSE
    IF @Option = 22
        SELECT  a.Log_AC_Master_Controller_ID AS [ID],
                a.Actor_ID AS [CustomerID],
                f.Description AS [Source],
                a.Message AS [Message],
                c.Description AS [Severity],
                d.Description AS [Type],
                e.Description AS [Method],
                a.Date_Captured AS [Date Captured],
                b.UserName AS [User],
                a.[User_ID] AS [UserID],
                a.AW_User_Companies_ID AS [CompanyID]
        FROM Log_AC_Master_Controller a
            INNER JOIN AW_Users b
                ON a.[User_ID] = b.AW_Users_ID
            INNER JOIN Sys_AC_Severity_Levels c
                ON a.Sys_AC_Severity_Levels_ID = c.Sys_AC_Severity_Levels_ID
            INNER JOIN Sys_AC_Message_Types d
                ON a.Sys_AC_Message_Types_ID = d.Sys_AC_Message_Types_ID
            INNER JOIN Sys_AW_Delivery_Methods e
                ON a.Sys_AW_Delivery_Methods_ID = e.Sys_AW_Delivery_Methods_ID
            INNER JOIN Sys_AT_Actor_Types f
                ON a.Sys_AT_Actor_Types_ID = f.Sys_AT_Actor_Types_ID
        WHERE a.Actor_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC
----------------------------------------------------------------------











SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_History_Details
--Purpose       :
--Date          :2004/07/13
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------
CREATE            PROCEDURE sp_RPT_AC_Customer_History_Details
    (
        @CompanyID int,
        @ChkAllCustomers int,
        @CustomerID int
    )

AS

SET NOCOUNT ON

-- SET @CompanyID = 1
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 1

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '    c.AC_Customers_ID AS [ID], ' 
    SET @sql = @sql + '    c.Surname AS [Reg Name], ' 
    SET @sql = @sql + '    c.Firstnames AS [Trade Style], ' 
    SET @sql = @sql + '    c.Initials AS [Initials], ' 
    SET @sql = @sql + '    CASE WHEN t.[Description] = ''<None>'' OR t.[Description] IS NULL '
    SET @sql = @sql + '        THEN ''''' 
    SET @sql = @sql + '        ELSE t.[Description] ' 
    SET @sql = @sql + '        END AS [Title], ' 
    SET @sql = @sql + '    l.[Description] AS [Language], ' 
    SET @sql = @sql + '    c.IDReg_Number AS [ID/Reg No], ' 
    SET @sql = @sql + '    LEFT(CONVERT(CHAR(10), c.Start_Date, 111), 10) AS [Start Date], '

    SET @sql = @sql + '    c.Customer_Number AS [Customer No], ' 
    SET @sql = @sql + '    c.Old_Customer_Number AS [Old No], ' 
    SET @sql = @sql + '    c.Head_Office AS [Parent Company], ' 
    SET @sql = @sql + '    bt.[Description] AS [Cust Type], '
    SET @sql = @sql + '    cg.[Description] AS [Cust Group], '
    SET @sql = @sql + '    tc.[Description] AS [Tax Code], '
    SET @sql = @sql + '    c.Tax_Number AS [Tax Number], '

    SET @sql = @sql + '    prn.[Description] AS [PreNotify], ' 
    SET @sql = @sql + '    pon.[Description] AS [PostNotify], ' 
    SET @sql = @sql + '    c.Credit_Limit AS [Credit Limit], ' 
    SET @sql = @sql + '    ct.[Description] AS [Credit Terms], '
    SET @sql = @sql + '    ctt.[Description] AS [TermsOfSale], '
    SET @sql = @sql + '    c.Credit_Insurers_Reference AS [CreditInsRef], ' 
    SET @sql = @sql + '    c.Credit_Insurers_Limit AS [CreditInsLimit], '
    SET @sql = @sql + '    chint.[Description] AS [ChargeInt], '
    SET @sql = @sql + '    con.UserName AS [Controller], ' 
    SET @sql = @sql + '    c.Contact_Name AS [Contact Name], ' 
    SET @sql = @sql + '    act.[Description] AS [Account Type], '
    SET @sql = @sql + '    mdm.[Description] AS [Method], '
    SET @sql = @sql + '    a.[Description] AS [Active], ' 

    SET @sql = @sql + '    c.Post_Box AS [Post Box], ' 
    SET @sql = @sql + '    c.Post_Office AS [Post Office], ' 
    SET @sql = @sql + '    c.Post_Code AS [Post Code], ' 

    SET @sql = @sql + '    c.Street_Address AS [Street Address], ' 
    SET @sql = @sql + '    c.Suburb AS [Suburb], ' 
    SET @sql = @sql + '    c.City AS [City], ' 
    SET @sql = @sql + '    c.Street_Post_Code AS [Street Code], ' 

    SET @sql = @sql + '    c.Delivery_Address AS [Registered Address], ' 
    SET @sql = @sql + '    c.Delivery_Suburb AS [Registered Suburb], ' 
    SET @sql = @sql + '    c.Delivery_City AS [Registered City], ' 
    SET @sql = @sql + '    c.Delivery_Post_Code AS [Registered Post Code], ' 

    SET @sql = @sql + '    cn.[Description] AS [Country], ' 
    SET @sql = @sql + '    c.Home_Tel_No AS [Home Tel No], ' 
    SET @sql = @sql + '    c.Work_Tel_No AS [Work Tel No], ' 
    SET @sql = @sql + '    c.Cell_No AS [Cell No], ' 
    SET @sql = @sql + '    c.Fax_No AS [Fax No], ' 
    SET @sql = @sql + '    c.Work_Email AS [Principal E-mail], '

    SET @sql = @sql + '    ISNULL(c.Principal_Firstname, '''') + '' '' + '
    SET @sql = @sql + '    ISNULL(c.Principal_Name, '''') AS [Principal], '

    SET @sql = @sql + '    c.Web_Site_URL AS [Web Site URL], ' 
    SET @sql = @sql + '    c.Orders_URL AS [Accounts E-mail], ' 
    SET @sql = @sql + '    c.Home_Email AS [Contact E-mail], '     SET @sql = @sql + '    c.Work_Email AS [Principal E-mail], '
    SET @sql = @sql + '    c.Notes '

    SET @sql = @sql + 'FROM AC_Customers c '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_Titles t '
    SET @sql = @sql + '        ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_Languages l '
    SET @sql = @sql + '        ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_Active a '
    SET @sql = @sql + '        ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + '    LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '        ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_Countries cn '
    SET @sql = @sql + '        ON c.Slu_AW_Countries_ID = cn.Slu_AW_Countries_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '        ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '    LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '        ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '
    SET @sql = @sql + '    LEFT JOIN Sys_AC_Account_Types act '
    SET @sql = @sql + '        ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '    LEFT JOIN Sys_AC_Credit_Term_Types ctt '
    SET @sql = @sql + '        ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID '
    SET @sql = @sql + '    LEFT JOIN Lup_AC_Customer_Types bt '
    SET @sql = @sql + '        ON c.Lup_AC_Customer_Types_ID = bt.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '    LEFT JOIN Lup_AC_Customer_Groups cg '
    SET @sql = @sql + '        ON c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_YesNo prn '
    SET @sql = @sql + '        ON c.AW_YesNo_Pre_Notify_ID = prn.Slu_AW_YesNo_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_YesNo pon '
    SET @sql = @sql + '        ON c.AW_YesNo_Post_Notify_ID = pon.Slu_AW_YesNo_ID '
    SET @sql = @sql + '    LEFT JOIN Slu_AW_YesNo chint '
    SET @sql = @sql + '        ON c.AW_YesNo_Charge_Interest_ID = chint.Slu_AW_YesNo_ID '
    SET @sql = @sql + '    LEFT JOIN AW_Users con '
    SET @sql = @sql + '        ON c.Slu_AW_Controllers_ID = con.AW_Users_ID '
    SET @sql = @sql + '    LEFT JOIN Sys_AW_Delivery_Methods mdm '
    SET @sql = @sql + '        ON c.Sys_AW_Delivery_Methods_ID = mdm.Sys_AW_Delivery_Methods_ID '

    SET @sql = @sql + ' WHERE c.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

    IF @ChkAllCustomers = 0    --A single Customer Account
        BEGIN
            IF @CustomerID <> 0
                BEGIN
                    SET @sql = @sql + '  AND c.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
                END
        END


--PRINT @sql

EXEC (@sql)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Journals_GL
--Purpose       :Customer Journal Transactions by GL Allocations
--Date          :2004/12/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AC_Customer_Journals_GL
    (
--         @TranTypeID tinyint,
--         @ChkGLAccounts int,
--         @GLAccountID int,
--         @ChkAllCustomers int,
--         @CustomerID int,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount], '
    SET @sql = @sql + '     t.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + '     t.AC_Customers_ID AS [CustomerID],  '
    SET @sql = @sql + '     c.Surname AS [CustomerName], '
    SET @sql = @sql + '     c.Customer_Number AS [CustomerNo], '

    SET @sql = @sql + '     ISNULL(c.Surname, '''') +
--                             '' ('' + ISNULL(c.Customer_Number, '''') + '')'' +
                             '' ('' + CONVERT(VARCHAR(10), c.AC_Customers_ID) + '') '' +
                             ISNULL(c.Post_Box, '''') + '', '' +
                             + ISNULL(c.Post_Office, '''') + '', '' +
                             + ISNULL(c.Post_Code, '''')
                              AS [CustomerFull], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [Date],  '
    SET @sql = @sql + '     tt.Type_Code AS [Type],  '
    SET @sql = @sql + '     t.Customer_Reference AS [Ref No],  '
    SET @sql = @sql + '     t.Transaction_Number AS [Doc No],  '

--     SET @sql = @sql + '     CASE WHEN t.AO_GRV_ID > 0 '
--     SET @sql = @sql + '          THEN t.AO_GRV_ID '
--     SET @sql = @sql + '          ELSE NULL '
--     SET @sql = @sql + '          END AS [GRV],  '

    SET @sql = @sql + '     t.Comment AS [Notes],  '
    SET @sql = @sql + '     t.Amount AS [Net], '
    SET @sql = @sql + '     t.Total_Tax_Amount AS [VAT], '
    SET @sql = @sql + '     t.Total_Amount AS [Total], '
    SET @sql = @sql + '     t.Payment_Amount AS [Payment],  '
    SET @sql = @sql + '     gl.[Description] AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     INNER JOIN AS_Transactions t '
    SET @sql = @sql + '         ON gt.AB_Transaction_Ref = t.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '         ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--    SET @sql = @sql + '         t.AS_Transactions_ID = gt.AB_Transaction_Ref AND '
    SET @sql = @sql + '         t.Transaction_Number = gt.AB_Source_Ref AND '
--    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' AND '
    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 22 AND '
    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


--     IF @ChkGLAccounts = 0      --Single GL Account
--         BEGIN
--             SET @sql = @sql + ' AND gl.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
--         END
-- 
-- 
--     IF @ChkAllCustomers = 0    --Single Customer Account
--         BEGIN
--             SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
--         END


    SET @sql = @sql + '     ORDER BY [CustomerFull], gt.AB_Transaction_Ref '


    EXEC (@sql)


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Journals_GL_Summary
--Purpose       :Customer Journal Transactions by GL Allocations Summary
--Date          :2004/12/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AC_Customer_Journals_GL_Summary
    (
--         @TranTypeID tinyint,
--         @ChkGLAccounts int,
--         @GLAccountID int,
--         @ChkAllCustomers int,
--         @CustomerID int,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gl.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     SUM(gt.AB_Transaction_Amount) AS [GLTranAmount], '
    SET @sql = @sql + '     MAX(gl.[Description]) AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     INNER JOIN AS_Transactions t '
    SET @sql = @sql + '         ON gt.AB_Transaction_Ref = t.AS_Transactions_ID '
--     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 AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--    SET @sql = @sql + '         t.AS_Transactions_ID = gt.AB_Transaction_Ref AND '
    SET @sql = @sql + '         t.Transaction_Number = gt.AB_Source_Ref AND '
--    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' AND '
    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 22 AND '
    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '

--     IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
--         BEGIN
--             SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
--         END
--     ELSE
--     IF @Option = 2    --GRV transaction only
--         BEGIN
--             SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
--         END


--     IF @ChkGLAccounts = 0      --Single GL Account
--         BEGIN
--             SET @sql = @sql + ' AND gl.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLAccountID) + ' '
--         END
-- 
-- 
--     IF @ChkAllCustomers = 0    --Single Customer Account
--         BEGIN
--             SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
--         END


    SET @sql = @sql + '     GROUP BY gt.AW_User_Companies_ID, gl.AB_Accounts_ID '
    SET @sql = @sql + '     ORDER BY MAX(gl.[Description]) '


    EXEC (@sql)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















--sp_RPT_AC_Customer_Labels 1, -1, -1, -1, -1, -1, -1, -1, -1, 0
-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Labels
--Purpose       :Customer Labels
--Date          :2005/10/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AC_Customer_Labels
	(
    	@CompanyID int,
    	@ActiveID int = -1,
    	@AccounTypeID int = -1,
    	@AccounStatusID int = -1,
    	@CustomerTypeID int = -1,
    	@CustomerGroupID int = -1,
      	@SalesAreaID int = -1,
    	@SalesPersonID int = -1,
      	@PeriodProceduresID int = -1,
--        @Overdue int,
        @Sort int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(8000),
            @SQL varchar(8000),
            @PrintZeroBalances tinyint


	SET @Filter = ''
    SET @SQL = ''
    SET @PrintZeroBalances = 1


    --> Filter Labels
    	IF @PeriodProceduresID = -1 
    		BEGIN

            --> Active
            	IF @ActiveID > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Slu_AW_Active_ID = ' +
                                            convert(varchar(20), @ActiveID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Slu_AW_Active_ID = ' +
                                            convert(varchar(20), @ActiveID)
            		END
            --> Account Type
            	IF @AccounTypeID > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Sys_AC_Account_Types_ID = ' +
                                            convert(varchar(20), @AccounTypeID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Sys_AC_Account_Types_ID = ' +
                                            convert(varchar(20), @AccounTypeID)
            		END
            --> Account Status
            	IF @AccounStatusID > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Sys_AC_Account_Status_ID = ' +
                                            convert(varchar(20), @AccounStatusID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Sys_AC_Account_Status_ID = ' +
                                            convert(varchar(20), @AccounStatusID)
            		END
            --> Customer Type
            	IF @CustomerTypeID > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Lup_AC_Customer_Types_ID = ' +
                                            convert(varchar(20), @CustomerTypeID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Lup_AC_Customer_Types_ID = ' +
                                            convert(varchar(20), @CustomerTypeID)
            		END
            --> Customer Group
            	IF @CustomerGroupID > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Lup_AC_Customer_Groups_ID = ' +
                                            convert(varchar(20), @CustomerGroupID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Lup_AC_Customer_Groups_ID = ' +
                                            convert(varchar(20), @CustomerGroupID)
            		END
            --> Sales Area
            	IF @SalesAreaID  > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Lup_AC_Sales_Areas_ID = ' +
                                            convert(varchar(20), @SalesAreaID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Lup_AC_Sales_Areas_ID = ' +
                                            convert(varchar(20), @SalesAreaID)
                	END
            --> Sales Person
            	IF @SalesPersonID > 0 
            		BEGIN
        
            			IF @Filter = ''
            				SET @Filter = ' WHERE ' + ' c.Lup_AS_Reps_ID = ' +
                                            convert(varchar(20), @SalesPersonID)
            			ELSE
            				SET @Filter = @Filter + ' AND ' + ' c.Lup_AS_Reps_ID = ' +
                                            convert(varchar(20), @SalesPersonID)
            		END
        
        
        		IF @Filter = ''
                    BEGIN
        				SET @Filter = ' WHERE ' + ' c.AW_User_Companies_ID = ' +
                                        convert(varchar(20), @CompanyID)
                    END
        		ELSE
                    BEGIN
        				SET @Filter = @Filter + ' AND ' + ' c.AW_User_Companies_ID = ' +
                                        convert(varchar(20), @CompanyID)
                    END
        
--                 IF @Overdue = 1
--                     BEGIN
--             			IF @Filter = ''
--             				SET @Filter = ' WHERE ' + ' c.AW_User_Companies_ID = ' +
--                                             convert(varchar(20), @CompanyID) +
--                                           ' AND ' + ' c.On_Hand <> 0 '
--             			ELSE
--             				SET @Filter = @Filter + ' AND ' + ' c.On_Hand <> 0 '
--                     END
        
        
        
            	SET @SQL = 'SELECT '
                SET @SQL = @SQL + ' c.AW_User_Companies_ID AS [CompanyID], '
                SET @SQL = @SQL + ' c.AC_Customers_ID AS [CustomerID], '
                SET @SQL = @SQL + ' ISNULL(c.[Surname], '''') AS [Name], '
                SET @SQL = @SQL + ' c.[Post_Box] AS [PostAddress], '
                SET @SQL = @SQL + ' c.[Post_Office] AS [PostOffice], '
                SET @SQL = @SQL + ' c.[Post_Code] AS [PostCode], '
                SET @SQL = @SQL + ' c.[Street_Address] AS [StreetAddress], '
                SET @SQL = @SQL + ' c.[Suburb] AS [Suburb], '
                SET @SQL = @SQL + ' c.[City] AS [City], '
                SET @SQL = @SQL + ' c.[Street_Post_Code] AS [StreetCode], '
                SET @SQL = @SQL + ' c.[Delivery_Address] AS [DelAddress], '
                SET @SQL = @SQL + ' c.[Delivery_Suburb] AS [DelSuburb], '
                SET @SQL = @SQL + ' c.[Delivery_City] AS [DelCity], '
                SET @SQL = @SQL + ' c.[Delivery_Post_Code] AS [DelCode], '
                SET @SQL = @SQL + ' ISNULL(c.Customer_Number, '''') AS [CustomerNo] '
                SET @SQL = @SQL + ' FROM AC_Customers c '
                SET @SQL = @SQL + @Filter
        
        
                IF @Sort = 1
                    BEGIN
                        SET @SQL = @SQL + ' ORDER BY c.Surname '
                    END
                ELSE
                IF @Sort = 2
                    BEGIN
        
                        SET @SQL = @SQL + ' ORDER BY c.Customer_Number '
                    END
                ELSE
                IF @Sort = 3
                    BEGIN
        
                        SET @SQL = @SQL + ' ORDER BY c.AC_Customers_ID '
                    END
    		END


    --> Period Procedure Labels
        ELSE
    		BEGIN
            	SET @SQL = 'SELECT '
                SET @SQL = @SQL + ' t.AW_User_Companies_ID AS [CompanyID], '
                SET @SQL = @SQL + ' t.AC_Customers_ID AS [CustomerID], '
                SET @SQL = @SQL + ' ISNULL(t.FullName, '''') AS [Name], '
                SET @SQL = @SQL + ' t.Post_Address AS [PostAddress], '
                SET @SQL = @SQL + ' t.Post_Office AS [PostOffice], '
                SET @SQL = @SQL + ' t.Post_Code AS [PostCode], '
                SET @SQL = @SQL + ' c.[Street_Address] AS [StreetAddress], '
                SET @SQL = @SQL + ' c.[Suburb] AS [Suburb], '
                SET @SQL = @SQL + ' c.[City] AS [City], '
                SET @SQL = @SQL + ' c.[Street_Post_Code] AS [StreetCode], '
                SET @SQL = @SQL + ' c.[Delivery_Address] AS [DelAddress], '
                SET @SQL = @SQL + ' c.[Delivery_Suburb] AS [DelSuburb], '
                SET @SQL = @SQL + ' c.[Delivery_City] AS [DelCity], '
                SET @SQL = @SQL + ' c.[Delivery_Post_Code] AS [DelCode], '
                SET @SQL = @SQL + ' ISNULL(t.Customer_Number, '''') AS [CustomerNo] '
                SET @SQL = @SQL + ' FROM AC_Statements t '
                SET @SQL = @SQL + ' INNER JOIN AC_Customers c '
                SET @SQL = @SQL + '     ON t.AC_Customers_ID = c.AC_Customers_ID '
                SET @SQL = @SQL + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
                SET @SQL = @SQL + '   AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' AND '
                SET @SQL = @SQL + '       t.Account_Balance <> 0 '

                IF @PrintZeroBalances = 1
                    BEGIN
                        SET @SQL = @SQL +
                            ' AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '
                    END
                ELSE
                    BEGIN
                        SET @SQL = @SQL +
                            ' AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) +
                            ' AND t.Account_Balance <> 0 '
                    END

            
                IF @Sort = 1
                    BEGIN
                        SET @SQL = @SQL + ' ORDER BY t.FullName '
                    END
                ELSE
                IF @Sort = 2
                    BEGIN
        
                        SET @SQL = @SQL + ' ORDER BY t.Customer_Number '
                    END
                ELSE
                IF @Sort = 3
                    BEGIN
        
                        SET @SQL = @SQL + ' ORDER BY t.AC_Customers_ID '
                    END
            END


    EXEC (@SQL)



SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Ledger
--Purpose       :Debtors/Customer Ledger (Transactions Audit Trail)
--Date          :2004/01/29
--Authors       :TB
--Version       :1.0.0
--MODS:         :31/03/04 - Added @ChkTerms input parameter to filter
--              :           Only Customers with Credit Terms
-------------------------------------------------------------------------------
--EXEC sp_RPT_AC_Customer_Ledger 1, 1, 388, 0, 0, '2003/11/01 12:00:01 AM', '2003/11/22 11:59:59 PM', 0
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AC_Customer_Ledger
    (
            @CompanyID int,
            @ChkAllCustomers int,
            @CustomerID int,
            @ChkTerms int,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime

    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 1627
-- SET @ChkTerms = 0
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '

--    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' c.Customer_Number AS [CustNo], '
    SET @sql = @sql + ' ct.[Description] AS [CreditTerms], '
    SET @sql = @sql + ' ctt.[Description] AS [TermsType], '
    SET @sql = @sql + ' ISNULL(c.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' cut.[Description] AS [CustomerType], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '

    SET @sql = @sql + ' h.Total_Cost AS [Cost], '
    SET @sql = @sql + ' h.Total_Discount_Amount AS [Discount], '
    SET @sql = @sql + ' h.Amount AS [Amount], '
    SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' h.Total_Amount AS [Total], '
    SET @sql = @sql + ' h.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) AS [Balance], '

    SET @sql = @sql + ' til.[Description] AS [Till], '
    SET @sql = @sql + ' ISNULL(cas.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(cas.Surname, '''') AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '

    SET @sql = @sql + ' h.Cashed_Up AS [Cashed Up], '
    SET @sql = @sql + ' h.Day_End AS [Day End], '
--    SET @sql = @sql + ' LEFT(ISNULL(g.Description, ''''), 20) AS [GL Account], '
    SET @sql = @sql + ' h.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User], '
    SET @sql = @sql + ' act.[Description] AS [Active] '
    
    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users cas '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = cas.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '          ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Credit_Term_Types ctt '
    SET @sql = @sql + '          ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Types cut '
    SET @sql = @sql + '          ON c.Lup_AC_Customer_Types_ID = cut.Lup_AC_Customer_Types_ID '

--     SET @sql = @sql + '      LEFT JOIN AB_Accounts g '
--     SET @sql = @sql + '          ON h.AB_Accounts_ID = g.AB_Accounts_ID '

    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Active act '
    SET @sql = @sql + '          ON h.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    SET @sql = @sql +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 4 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 5 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 7 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 15 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 18 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 21 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 22) '


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END


    IF @ChkTerms = 1    --Only Customers with Credit Terms
        BEGIN
            SET @sql = @sql + '  AND ISNULL(ct.Terms_Value, 0) > 0 '
        END


    SET @sql = @sql + ' ORDER BY [Customer], [Day End], [TranDate] ASC '


    EXEC (@sql)


SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Listing2
--Purpose       :ustomer Listing - Condensed
--Date          :2007/01/17
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AC_Customer_Listing2
    (
            @CompanyID int
    )
AS


SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Customers_ID AS [CustID], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') AS [Surname], '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') AS [Tradename], '
    SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [CustNo], '

    SET @sql = @sql + ' c.Contact_Name AS [Contact], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTel], '
    SET @sql = @sql + ' c.Fax_No AS [FaxTel], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '

    SET @sql = @sql + ' ctype.[Description] AS [CustomerType], '
    SET @sql = @sql + ' cgrp.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' atype.[Description] AS [AccountType], '
    SET @sql = @sql + ' astatus.[Description] AS [AccountStatus], '
    SET @sql = @sql + ' ISNULL(c.Credit_Limit, 0) AS [CreditLimit], '
    SET @sql = @sql + ' ct.[Description] AS [CreditTerms], '
    SET @sql = @sql + ' act.[Description] AS [Active] '
    
    SET @sql = @sql + ' FROM AC_Customers c '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '          ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Credit_Term_Types ctt '
    SET @sql = @sql + '          ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Groups cgrp '
    SET @sql = @sql + '          ON c.Lup_AC_Customer_Groups_ID = cgrp.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Types ctype '
    SET @sql = @sql + '          ON c.Lup_AC_Customer_Types_ID = ctype.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Account_Types atype '
    SET @sql = @sql + '          ON c.Sys_AC_Account_Types_ID = atype.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Account_Status astatus '
    SET @sql = @sql + '          ON c.Sys_AC_Account_Status_ID = astatus.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Active act '
    SET @sql = @sql + '          ON c.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    SET @sql = @sql + ' ORDER BY [Surname] ASC '


    EXEC (@sql)


SET NOCOUNT OFF























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Lists
--Purpose       :Retrieves Customer Catalog and Ageing data
--Tables        :AC_Customer, dbo.fn_AC_Customer_Ageing_Values
--              :JOINS all Customer Lups
--Parameters    :
--Date          :2002/03/06
--Authors       :TB
--Version       :1.0.0
------------------------------------------------------------------------------

CREATE   PROCEDURE sp_RPT_AC_Customer_Lists
    (
        @CustomerID int,
        @D0 datetime = NULL,
        @D1 datetime = NULL,
        @D2 datetime = NULL,
        @D3 datetime = NULL,
        @D4 datetime = NULL,
        @D5 datetime = NULL,
        @D6 datetime = NULL,
        @D7 datetime = NULL,
        @Filter varchar(1000)
    )

AS

SELECT
    c.AC_Customers_ID AS [ID], 
	c.Customer_Number AS [Customer No], 
	c.Surname AS [Name], 
	c.Firstnames AS [First Names], 
	CASE WHEN t.[Description] = '<None>' OR t.[Description] IS NULL
         THEN ''
         ELSE t.[Description]
         END AS [Title], 
	c.Initials AS [Initials], 
	l.[Description] AS [Language], 
	c.IDReg_Number AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	a.[Description] AS [Active], 
	s.[Description] AS [Account Status],
	c.Contact_Name AS [Contact Name], 
	r.[Description] AS [Salesperson],
	c.Post_Box AS [Post Box], 
	c.Post_Office AS [Post Office], 
	c.Post_Code AS [Post Code], 
	c.Street_Address AS [Street Address], 
	c.Suburb AS [Suburb], 
	c.City AS [City], 
	c.Street_Post_Code AS [Street Code], 
	cu.[Description] + ' (' + cu.Country_Code3 + ')' AS [Country], 
	c.Delivery_Address AS [Delivery Address], 
	c.Delivery_Suburb AS [Delivery Suburb], 
	c.Delivery_City AS [Delivery City], 
	c.Delivery_Post_Code AS [Delivery Post Code], 
	c.Web_Site_URL AS [Web Site URL], 
	c.Orders_URL AS [Order URL], 
	c.Home_Email AS [E-mail Home], 
	c.Work_Email AS [E-mail Work],
	c.Home_Tel_No AS [Home Tel No], 
	c.Work_Tel_No AS [Work Tel No], 
	c.Cell_No AS [Cell No], 
	c.Fax_No AS [Fax No], 
	dc.[Description] AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ct.[Description] AS [Credit Terms],
	c.Credit_Insurers_Reference AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ci.[Description] AS [Charge Interest],
	sa.[Description] AS [Sales Area], 
	c.Head_Office AS [Head Office], 
	ct.[Description] AS [Customer Type], 
	tc.[Description] AS [Tax Code], 
	c.Tax_Number AS [Tax Number],
	act.[Description] AS [Account Types],
	ctt.[Description] AS [Credit Term Types],
	ISNULL(c.Account_Balance,0) AS [Account Balance],
	ISNULL(ag.[Current],0) AS [Current],
	ISNULL(ag.[30 Days],0) AS [30 Days],
	ISNULL(ag.[60 Days],0) AS [60 Days],
	ISNULL(ag.[90 Days],0) AS [90 Days],
	ISNULL(ag.[120 Days],0) AS [120 Days], 
	ISNULL(ag.[150 Days],0) AS [150 Days],
	ISNULL(ag.[180+ Days],0) AS [180+ Days],
	c.Notes,
    ag.CURRENTDATE,
    ag.DAYS30DATE,
    ag.DAYS60DATE,
    ag.DAYS90DATE,
    ag.DAYS120DATE,
    ag.DAYS150DATE,
    ag.DAYS180DATE

FROM AC_Customers c
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
        LEFT JOIN dbo.fn_AC_Customer_Ageing_Values
            ( @CustomerID, @D0, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) ag
            ON c.AC_Customers_ID = ag.CustomerID


-- vw_RPT_AC_Customers
----------------------
-- SELECT   
--       c.AC_Customers_ID AS ID, 
--       c.Surname, 
--       c.Firstnames, 
--       c.Initials, 
--       dbo.Lup_AW_Titles.Description AS Title, 
--       c.Contact_Name AS Contact, 
--       dbo.Lup_AW_Languages.Description AS [Language], 
--       c.IDReg_Number AS [ID/Reg No], 
--       c.Customer_Number AS [Customer No], 
--       c.Old_Customer_Number AS [Old Customer No], 
--       c.Post_Box AS [Post Box], 
--       c.Post_Office AS [Post Office], 
--       c.Post_Code AS [Post Code], 
--       c.Street_Address AS [Street Address], 
--       c.Suburb, 
--       c.City, 
--       c.Street_Post_Code AS [Street Post Code], 
--       c.Delivery_Address AS [Delivery Address], 
--       c.Delivery_Suburb AS [Delivery Suburb], 
--       c.Delivery_City AS [Delivery City], 
--       c.Delivery_Post_Code AS [Delivery Post Code], 
--       c.Head_Office AS [Head Office], 
--       Lup_AW_YesNo_1.Description AS [Inter Company], 
--       dbo.Lup_AC_Account_Status.Description AS [Account Status], 
--       dbo.Lup_AC_Discount_Categories.Description AS [Discount Category], 
--       c.Credit_Limit AS [Credit Limit], 
--       dbo.Lup_AW_Credit_Terms.Description AS [Credit Terms], 
--       dbo.Sys_Credit_Term_Types.Description AS [Term Type], 
--       Lup_AW_YesNo_1.Description AS [Charge Interest], 
--       dbo.Lup_AS_Reps.Description AS Rep, 
--       dbo.Lup_AW_Countries.Description AS Country, 
--       c.Cell_No AS [Cell No], 
--       c.Home_Tel_No AS [Home Tel], 
--       c.Work_Tel_No AS [Work Tel], 
--       c.Fax_No AS Fax, 
--       ISNULL(c.Web_Site_URL, '') AS URL, 
--       ISNULL(c.Orders_URL, '') AS [Orders URL], 
--       ISNULL(c.Home_Email, '') AS [Home email], 
--       ISNULL(c.Work_Email, '') AS [Work email], 
--       c.Start_Date AS [Activation Date], 
--       ISNULL(dbo.Lup_AW_Tax_Codes.Description, '') AS [Tax Code], 
--       ISNULL(c.Tax_Number, '') AS [Tax Number], 
--       ISNULL(c.Notes, '') AS Notes, 
--       ISNULL(c.Account_Balance, 0) AS [Account Balance], 
--       ISNULL(c.Current_Balance, 0) AS [Current Balance], 
--       ISNULL(c.Days_30, 0) AS [30 Days], 
--       ISNULL(c.Days_60, 0) AS [60 Days], 
--       ISNULL(c.Days_90, 0) AS [90 Days], 
--       ISNULL(c.Days_120, 0) AS [120 Days], 
--       ISNULL(c.Days_150, 0) AS [150 Days], 
--       ISNULL(c.Days_180, 0) AS [180 Days], 
--       c.Date_Captured AS [Date Captured], 
--       ISNULL(c.Days_30, 0) + ISNULL(c.Days_60, 0) + ISNULL(c.Days_90, 0) + ISNULL(c.Days_120, 0) + ISNULL(c.Days_150, 0) + ISNULL(c.Days_180, 0) AS [30+ Days],
--       ISNULL(c.Days_60, 0) + ISNULL(c.Days_90, 0) + ISNULL(c.Days_120, 0) + ISNULL(c.Days_150, 0) + ISNULL(c.Days_180, 0) AS [60+ Days],
--       ISNULL(c.Days_90, 0) + ISNULL(c.Days_120, 0) + ISNULL(c.Days_150, 0) + ISNULL(c.Days_180, 0) AS [90+ Days],
--       ISNULL(c.Days_120, 0) + ISNULL(c.Days_150, 0) + ISNULL(c.Days_180, 0) AS [120+ Days]
-- FROM         dbo.Lup_AW_Tax_Codes RIGHT OUTER JOIN
--                       dbo.Lup_AW_YesNo Lup_AW_YesNo_2 RIGHT OUTER JOIN
--                       dbo.AC_Customers c LEFT OUTER JOIN
--                       dbo.Lup_AW_Titles ON c.Lup_AW_Titles_ID = dbo.Lup_AW_Titles.Lup_AW_Titles_ID LEFT OUTER JOIN
--                       dbo.Lup_AW_YesNo Lup_AW_YesNo_1 ON c.AW_YesNo_Charge_Interest_ID = Lup_AW_YesNo_1.Lup_AW_YesNo_ID LEFT OUTER JOIN
--                       dbo.Lup_AW_Languages ON c.Lup_AW_Languages_ID = dbo.Lup_AW_Languages.Lup_AW_Languages_ID LEFT OUTER JOIN
--                       dbo.Lup_AS_Reps ON c.Lup_AS_Reps_ID = dbo.Lup_AS_Reps.Lup_AS_Reps_ID LEFT OUTER JOIN
--                       dbo.Lup_AW_Credit_Terms ON c.Lup_AW_Credit_Terms_ID = dbo.Lup_AW_Credit_Terms.Lup_AW_Credit_Terms_ID LEFT OUTER JOIN
--                       dbo.Lup_AC_Account_Status ON c.Lup_AC_Account_Status_ID = dbo.Lup_AC_Account_Status.Lup_AC_Account_Status_ID ON 
--                       Lup_AW_YesNo_2.Lup_AW_YesNo_ID = c.AW_YesNo_Inter_Company_ID LEFT OUTER JOIN
--                       dbo.Lup_AC_Discount_Categories ON 
--                       c.Lup_AC_Discount_Categories_ID = dbo.Lup_AC_Discount_Categories.Lup_AC_Discount_Categories_ID LEFT OUTER JOIN
--                       dbo.Sys_Credit_Term_Types ON c.Sys_Credit_Term_Types_ID = dbo.Sys_Credit_Term_Types.Sys_Credit_Term_Types_ID LEFT OUTER JOIN
--                       dbo.Lup_AW_Countries ON c.Lup_AW_Countries_ID = dbo.Lup_AW_Countries.Lup_AW_Countries_ID ON 
--                       dbo.Lup_AW_Tax_Codes.Lup_AW_Tax_Codes_ID = c.Lup_AW_Tax_Codes_ID
-- 






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Partly_Allocated_Payments
--Purpose       :Select Partly Allocated Payments Received for Customer Reports
--Source        :
--Date          :2004/07/15
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AC_Customer_Partly_Allocated_Payments
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

	SELECT
        t.AW_User_Companies_ID AS [CompanyID],
		c.AC_Customers_ID AS [CustomerID], 
		ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, '') AS [Name],
		ISNULL(c.Customer_Number, '') AS [CustNo],
		t.AS_Transactions_ID AS [TranID], 
		ISNULL(t.Transaction_Number, '') AS [No], 
        CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [Date], 
		ISNULL(t.Total_Amount, 0) AS [Total], 
		ISNULL(t.Payment_Amount, 0) AS [Allocated], 
		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
		ISNULL(t.Comment, '') AS [Comment]
    FROM AC_Customers c
        INNER JOIN AS_Transactions t
            ON c.AC_Customers_ID = t.AC_Customers_ID
	WHERE  dbo.fn_AC_Customer_Has_Unallocated_Payments( c.AC_Customers_ID ) = 1 AND
          t.AW_User_Companies_ID = @CompanyID AND
          t.Transaction_Date >= @StartDate AND
          t.Transaction_Date <= @EndDate AND
         (t.Sys_AW_Transaction_Types_ID = 7 OR
          t.Sys_AW_Transaction_Types_ID = 21 OR
          t.Sys_AW_Transaction_Types_ID = 22)
    ORDER BY [Name]




SET NOCOUNT OFF    














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Payment_Allocations
--Purpose       :Customer Payment Transaction Allocations
--Date          :2004/05/04
--Authors       :TB
--MODS:         :
--2004.2.9      :31/05/06 - Removed filter to exclude type = 7 POS Payments
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AC_Customer_Payment_Allocations
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


    SET @sql = ' SELECT '
   
    SET @sql = @sql + ' tp.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' talloc.Transaction_Date AS [Date], '
    SET @sql = @sql + ' th.Day_End AS [DayEnd], '
    SET @sql = @sql + ' tp.AS_Transaction_Payments_ID AS [TranPayID], '
    SET @sql = @sql + ' tr.AS_Transactions_Transactions_ID AS [TranTranID], '
    SET @sql = @sql + ' tr.Destination_AS_Transactions_ID AS [PaymentID], '
    SET @sql = @sql + ' tr.Source_AS_Transactions_ID AS [AllocationID], '

    SET @sql = @sql + ' th.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' th.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' th.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + csh.FirstName, '''') + ISNULL(csh.Surname, ''''))) AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' ISNULL(tp.Payor_Name, '''') AS [Payor],  '

    SET @sql = @sql + ' CASE WHEN talloc.Sys_AW_Transaction_Types_ID = 7 '
    SET @sql = @sql + '      THEN ''POS'' '
    SET @sql = @sql + '      WHEN talloc.Sys_AW_Transaction_Types_ID = 22 '
    SET @sql = @sql + '      THEN ''EFT'' '
    SET @sql = @sql + '      ELSE ''BOF'' '
    SET @sql = @sql + ' END AS [Location], '

    SET @sql = @sql + ' ci.[Description] AS [Institution], ' 
    SET @sql = @sql + ' tp.Sys_AW_Payment_Methods_ID as [MethodID], '
    SET @sql = @sql + ' pm.[Description] AS [Method], '
    SET @sql = @sql + ' ISNULL(tp.Card_Expiry_Date, '''') AS [Expiry], ' 
    SET @sql = @sql + ' ISNULL(tp.Card_Number, '''') AS [Card No], '
    SET @sql = @sql + ' ISNULL(tp.Authorisation_Number, '''') AS [Auth], ' 

    SET @sql = @sql + ' tp.Amount AS [Paid], '
    SET @sql = @sql + ' tr.Amount AS [Allocated], '
    SET @sql = @sql + ' talloc.Transaction_Number AS [ReceiptNo], '
    SET @sql = @sql + ' th.Total_Amount AS [TranTotal], '
    SET @sql = @sql + ' ISNULL(th.Total_Amount, 0) + ISNULL(tr.Amount, 0) AS [Difference], '
    SET @sql = @sql + ' th.Payment_Amount AS [TranPayment], '
    SET @sql = @sql + ' ISNULL(th.Total_Amount, 0) + ISNULL(th.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + u.FirstName, '''') + ISNULL(u.Surname, ''''))) AS [User], '
    SET @sql = @sql + ' th.Cashed_Up '
    
    SET @sql = @sql + ' FROM AS_Transaction_Payments tp '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions_Transactions tr '
    SET @sql = @sql + '         ON tr.Destination_AS_Transactions_ID = tp.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions th '
    SET @sql = @sql + '         ON tr.Source_AS_Transactions_ID = th.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions talloc '
    SET @sql = @sql + '         ON tr.Destination_AS_Transactions_ID = talloc.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = th.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users csh '
    SET @sql = @sql + '          ON th.Lup_AS_Cashiers_ID = csh.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON th.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Payment_Methods pm '
    SET @sql = @sql + '         ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID ' 
    SET @sql = @sql + '     LEFT JOIN Slu_AS_Card_Institutions ci '
    SET @sql = @sql + '         ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON tp.User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE tp.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
--    SET @sql = @sql + '   AND talloc.Sys_AW_Transaction_Types_ID <> 7 '

    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND tp.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND tp.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END

    SET @sql = @sql + ' ORDER BY [Customer], [PaymentID], [AllocationID] ASC '

    EXEC (@sql)




SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Payments_Received
--Purpose       :Select Payments Recieved for Customer Reports
--Source        :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AC_Customer_Payments_Received
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

	SELECT
        t.AW_User_Companies_ID AS [CompanyID],
		c.AC_Customers_ID AS [CustomerID], 
		ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, '') AS [Name],
		ISNULL(c.Customer_Number, '') AS [CustNo],
		t.AS_Transactions_ID AS [TranID], 
		ISNULL(t.Transaction_Number, '') AS [No], 
--        CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [Date], 
        t.Transaction_Date AS [Date], 
		ISNULL(t.Total_Amount, 0) AS [Total], 
		ISNULL(t.Payment_Amount, 0) AS [Allocated], 
		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
		ISNULL(t.Comment, '') AS [Comment]
    FROM AC_Customers c
         INNER JOIN AS_Transactions t
            ON c.AC_Customers_ID = t.AC_Customers_ID
	WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.Transaction_Date >= @StartDate AND
          t.Transaction_Date <= @EndDate AND
         (t.Sys_AW_Transaction_Types_ID = 7 OR
          t.Sys_AW_Transaction_Types_ID = 21 OR
          t.Sys_AW_Transaction_Types_ID = 22)
    ORDER BY [Name], t.Transaction_Date




SET NOCOUNT OFF    















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Performance_Statistics
--Purpose       :Retrieves Customers Performance Statistics
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :14/07/04 - Modified Options 4 & 6
--              :09/08/04 - Added Options 10 to 14
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Performance_Stats]
    (
        @Option tinyint,
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

AS

SET NOCOUNT ON

    DECLARE @Midnight		datetime,
			@OverdueCount	int

    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @ReportDate), 0, 1)))


    IF @Option = 1    --Customer Debtors Total, Overdue, Overdue %
        BEGIN
        
			SET @OverdueCount = 0
    		SELECT @OverdueCount = COUNT(Distinct a.AC_Customers_ID)
        	FROM AC_Customers a
        	INNER JOIN AS_Transactions t
        			ON a.AC_Customers_ID = t.AC_Customers_ID
        	LEFT JOIN Slu_AW_Credit_Terms b
                    ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
--        	WHERE AC_Customers_ID = @CustomerID AND
            WHERE (Sys_AW_Transaction_Types_ID = 3 OR       --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                  Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18) AND     --EFT Payment
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                --> If Transaction OLDER THAN @DaysTerms
                  DATEDIFF(d, @Midnight, Transaction_Date + b.Terms_Value) < 0
              
          	SELECT
--                COUNT(*) AS [OverdueCount],
				@OverdueCount AS [OverdueCount],
                SUM(ISNULL(dbo.fn_AC_Customer_Balance_As_At_Date
                            ( a.AC_Customers_ID,
                              @ReportDate), 0)) AS [Balance],
                SUM(ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                            (a.Sys_AC_Credit_Term_Types_ID,
                             b.Terms_Value,
                             a.AC_Customers_ID,
                             @Midnight,
                             @D1,
                             @D2,
                             @D3,
                             @D4,
                             @D5,
                             @D6,
                             @D7), 0)) AS [Overdue]

        	FROM AC_Customers a
                LEFT JOIN Slu_AW_Credit_Terms b
                    ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
        	WHERE a.AW_User_Companies_ID = @CompanyID
        END

    ELSE
    IF @Option = 2    --Total Value of SALES
        BEGIN

            --RL 2014-09-02 SELECT ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [Sales]
            SELECT ISNULL(SUM(Total_Amount), 0) AS [Sales]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 -- ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund

        END

    ELSE
    IF @Option = 3    --Total Value of REFUNDS (Credit Notes)
        BEGIN

            SELECT COUNT(*) AS [Count],
                   --RL 2014-09-02 ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [Refunds]
                   ISNULL(SUM(Total_Amount), 0) AS [Refunds]                   
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 --RL 2014-09-02 ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                  Sys_AW_Transaction_Types_ID = 4      --Refund

        END

    ELSE
    IF @Option = 4    --Total Value of PAYMENTS RECEIVED
        BEGIN

            SELECT ISNULL(SUM(Total_Amount), 0) AS [Payments]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

        END

    ELSE
    IF @Option = 5    --Number of NEW ACCOUNTS OPENED
        BEGIN

			--Start_Date must be captured on Customer Catalog
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Start_Date >= @StartDate AND
                  Start_Date <= @EndDate

        END

    ELSE
    IF @Option = 6    --Total Debtors MOVEMENT for the period
        BEGIN

            SELECT ISNULL(SUM(Total_Amount), 0) AS [Total]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

        END

    ELSE
    IF @Option = 7    --TOTAL SALES for last 3 months
        BEGIN

            --RL 2014-09-02 SELECT ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [SalesQtr]
            SELECT ISNULL(SUM(Total_Amount), 0) AS [SalesQtr]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  --ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= DATEADD(m, -3, @ReportDate) AND
                  Transaction_Date <= @ReportDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund

        END


    ELSE
    IF @Option = 8    --Customer Applications DECLINED this month
        BEGIN

            SELECT COUNT(*) AS [DeclinedCount]
            FROM AC_History_Status
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AC_Account_Status_ID = 5 AND        --5 = Declined
                  Date_Changed >= @StartDate AND
                  Date_Changed <= @EndDate

        END


    ELSE
    IF @Option = 9    --Total Value of SALES grouped by Terms Of Sale
        BEGIN
            SELECT MAX(a.AW_User_Companies_ID) AS [CompanyID],
                   MAX(c.Description) AS [TermsOfSale],
                   --RL 2014-09-02 ISNULL(SUM(a.Total_Amount), 0) + ISNULL(SUM(a.Payment_Amount), 0) AS [Sales]
                   ISNULL(SUM(a.Total_Amount), 0) AS [Sales]
            FROM AS_Transactions a
                LEFT JOIN AC_Customers b
                    ON b.AC_Customers_ID = a.AC_Customers_ID
                LEFT JOIN Sys_AC_Credit_Term_Types c
                    ON c.Sys_AC_Credit_Term_Types_ID = b.Sys_AC_Credit_Term_Types_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
             --     ISNULL(a.Total_Amount, 0) + ISNULL(a.Payment_Amount, 0) <> 0 AND
                  a.Transaction_Date >= @StartDate AND
                  a.Transaction_Date <= @EndDate AND
                 (a.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  a.Sys_AW_Transaction_Types_ID = 4)     --Refund
            GROUP BY b.Sys_AC_Credit_Term_Types_ID
            ORDER BY [TermsOfSale]

        END

--------------------------------------------------------

    ELSE
    IF @Option = 10    --Total Customers
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers

        END


    ELSE
    IF @Option = 11    --Total Active Customers
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers
            WHERE Slu_AW_Active_ID = 1

        END


    ELSE
    IF @Option = 12    --Customers with a Credit Limit
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers
            WHERE Credit_Limit > 0

        END


    ELSE
    IF @Option = 13    --Max Credit exposure
        BEGIN
            
            SELECT SUM(Credit_Limit) AS [Credit]
            FROM AC_Customers
            WHERE Credit_Limit > 0

        END


    ELSE
    IF @Option = 14    --Customers with a Credit Terms
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers a
                INNER JOIN Slu_AW_Credit_Terms b
                    ON a.Slu_AW_Credit_Terms_ID = b.Slu_AW_Credit_Terms_ID
            WHERE b.Terms_Value > 0

        END
    Else    
    IF @Option = 15    --Total Value of VAT on SALES
        BEGIN

            --RL 2014-09-02 SELECT ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [Sales]
            SELECT ISNULL(SUM(Total_Tax_Amount), 0) AS [VAT]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 -- ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund

        END




SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statement_Allocations
--Purpose       :Customer Statement Payments Transaction Allocations
--Date          :2004/05/30
--Authors       :TB
--Version       :1.0.0
--MODS:         :
--V6.3	RL	2017/09/18 - The report should displays when the allocation was done, and not the transaction date
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Statement_Allocations]
    (
        @Company_ID int,
        @CustomerID int,
        @PeriodProceduresID int
    )
AS

SET NOCOUNT ON

    DECLARE @ThisPeriodProceduresDate datetime,
            @PrevPeriodProceduresDate datetime

    IF @PeriodProceduresID <> 0
        BEGIN
            SELECT @ThisPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE AW_Period_Procedures_ID = @PeriodProceduresID

        	IF @ThisPeriodProceduresDate IS NULL
                BEGIN
            		SET @ThisPeriodProceduresDate =  getdate()
                    RETURN
                END

            SELECT Top 1 @PrevPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  Month_End_Date < @ThisPeriodProceduresDate AND
                  AW_User_Companies_ID = @Company_ID
            ORDER BY Month_End_Date DESC

        	IF @PrevPeriodProceduresDate IS NULL
                BEGIN
            		SET @PrevPeriodProceduresDate =  '1900/01/01 00:00:01'
                    RETURN
                END
        END

    ELSE
        BEGIN
            SELECT Top 1 @PrevPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  AW_User_Companies_ID = @Company_ID
            ORDER BY Month_End_Date DESC


        	IF @PrevPeriodProceduresDate IS NULL
                BEGIN
            		SET @PrevPeriodProceduresDate =  '1900/01/01 00:00:01'
                    RETURN
                END

            SET @ThisPeriodProceduresDate = getdate()

        END


    SELECT
        t.AS_Transactions_ID AS [ReceiptID],
        CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [ReceiptDate], 
        t.Transaction_Number AS [ReceiptNo],
        ISNULL(tt.[Description], '') AS [TranType],
        CONVERT(datetime, CONVERT(CHAR(10), dt.Transaction_Date, 121)) AS [TranDate], 
        dt.Transaction_Number AS [TranNo],
        dt.Total_Amount AS [TranTotal],
        st.Amount AS [Allocated],
        ISNULL(dt.Total_Amount, 0) + ISNULL(dt.Payment_Amount, 0) AS [Balance]

    FROM AS_Transactions t
        INNER JOIN AS_Transactions_Transactions st
            ON st.Destination_AS_Transactions_ID = t.AS_Transactions_ID
        INNER JOIN AS_Transactions dt
            ON dt.AS_Transactions_ID = st.Source_AS_Transactions_ID
        LEFT JOIN Sys_AW_Transaction_Types tt
             ON dt.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID

    WHERE t.AC_Customers_ID = @CustomerID AND
		(
			--t.Transaction_Date Between @PrevPeriodProceduresDate AND @ThisPeriodProceduresDate 
			-- The report should displays when the allocation was done, and not the transaction date
			--st.Date_Captured Between @PrevPeriodProceduresDate AND @ThisPeriodProceduresDate 
			st.Date_Captured > @PrevPeriodProceduresDate
		) AND

         (t.Sys_AW_Transaction_Types_ID = 7 OR
          t.Sys_AW_Transaction_Types_ID = 21 OR
          t.Sys_AW_Transaction_Types_ID = 22) 

    ORDER BY t.Date_Captured

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statement_Payments
--Purpose       :Retrieves current month PAYMENTS RECEIVED for Customer Statements
--Functionality :
--Date          :2003/11/18
--Authors       :TB
--Version       :1.0.0
--MODS          :29/05/04 - Added filtering Payments from AS_Transactions for
--              :           both Period Procedure and Interim options
--              :31/05/04 - Added TranType = 18 (Settlement Discount)
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AC_Customer_Statement_Payments
    (
    	@Company_ID int,
    	@Customer_ID int,
        @PeriodProceduresID int
    )

AS

SET NOCOUNT ON

    DECLARE @ThisPeriodProceduresDate datetime,
            @PrevPeriodProceduresDate datetime


    IF @PeriodProceduresID <> 0
        BEGIN
            SELECT @ThisPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE AW_Period_Procedures_ID = @PeriodProceduresID

        	IF @ThisPeriodProceduresDate IS NULL
                BEGIN
            		SET @ThisPeriodProceduresDate =  getdate()
                    RETURN
                END

            SELECT Top 1 @PrevPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  Month_End_Date < @ThisPeriodProceduresDate AND
                  AW_User_Companies_ID = @Company_ID
            ORDER BY Month_End_Date DESC

        	IF @PrevPeriodProceduresDate IS NULL
                BEGIN
            		SET @PrevPeriodProceduresDate =  '1900/01/01 00:00:01'
                    RETURN
                END


            SELECT 
                z.AS_Transactions_ID AS [TranID], 

                t.AC_Statements_Temp_ID AS [ID], 
                t.AC_Customers_ID AS [CustomerID], 
                CONVERT(datetime, CONVERT(CHAR(10), z.Transaction_Date, 121)) AS [TransactionDate], 
                tt.[Description] AS Type, 
                z.Transaction_Number AS [TransactionNo], 
                ISNULL(z.Total_Amount, 0) AS [Amount], 
                ISNULL(z.Payment_Amount, 0) AS [Payment], 
                ISNULL(z.Total_Amount, 0) + ISNULL(z.Payment_Amount, 0) AS [Balance], 
                z.Comment AS [Notes]
            FROM AC_Statements_Temp t 
                LEFT JOIN AS_Transactions z
                    ON z.AC_Customers_ID = t.AC_Customers_ID
                LEFT JOIN Sys_AW_Transaction_Types tt
                    ON z.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
            WHERE t.AW_User_Companies_ID = @Company_ID AND
                  t.AC_Customers_ID = @Customer_ID AND
                  z.Transaction_Date >= @PrevPeriodProceduresDate AND
                  z.Transaction_Date <= @ThisPeriodProceduresDate AND
                 (z.Sys_AW_Transaction_Types_ID = 7 OR
                  z.Sys_AW_Transaction_Types_ID = 18 OR
                  z.Sys_AW_Transaction_Types_ID = 21 OR
                  z.Sys_AW_Transaction_Types_ID = 22)
            ORDER BY [CustomerID], [TransactionDate]


        END

    ELSE
        BEGIN


            SELECT Top 1 @PrevPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  AW_User_Companies_ID = @Company_ID
            ORDER BY Month_End_Date DESC


        	IF @PrevPeriodProceduresDate IS NULL
                BEGIN
            		SET @PrevPeriodProceduresDate =  '1900/01/01 00:00:01'
                    RETURN
                END


            SELECT 
                t.AC_Statements_Temp_ID AS [ID], 
                t.AC_Customers_ID AS [CustomerID], 
                CONVERT(datetime, CONVERT(CHAR(10), z.Transaction_Date, 121)) AS [TransactionDate], 
                tt.[Description] AS Type, 
                z.Transaction_Number AS [TransactionNo], 
                ISNULL(z.Total_Amount, 0) AS [Amount], 
                ISNULL(z.Payment_Amount, 0) AS [Payment], 
                ISNULL(z.Total_Amount, 0) + ISNULL(z.Payment_Amount, 0) AS [Balance], 
                z.Comment AS [Notes]
            FROM AC_Statements_Temp t 
                LEFT JOIN AS_Transactions z
                    ON z.AC_Customers_ID = t.AC_Customers_ID
                LEFT JOIN Sys_AW_Transaction_Types tt
                    ON z.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
            WHERE t.AW_User_Companies_ID = @Company_ID AND
                  t.AC_Customers_ID = @Customer_ID AND
                  z.Transaction_Date > @PrevPeriodProceduresDate AND
                  t.AW_Period_Procedures_ID = @PeriodProceduresID AND
                 (z.Sys_AW_Transaction_Types_ID = 7 OR
                  z.Sys_AW_Transaction_Types_ID = 18 OR
                  z.Sys_AW_Transaction_Types_ID = 21 OR
                  z.Sys_AW_Transaction_Types_ID = 22)
            ORDER BY [CustomerID], [TransactionDate]

        END


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statements
--Purpose       :Retrieves Customer Statement data in Statements Report
--Tables        :AC_Statements, AC_Statement_Details
--Functionality :Prints only Customers with transactions owing
--Date          :2002/06/14
--Authors       :TB
--Version       :1.0.0
--MODS          :24/06/02 - Changed ORDER BY from CustomerID to t.FullName
--              :09/08/02 - Modified ORDER BY to include TransactionDate
--              :19/05/03 - Modified formatting CONVERT(int, d.Transaction_Date)
--              :           that ROUNDS THE DATE UP after 12:00 midday !!!!!!!,
--              :           to CONVERT(CHAR(10), d.Transaction_Date, 121)) that truncates
--              :02/11/04 - Trimmed Transaction_Number and Comment fields
--              :17/05/05 - Reworked ORDER BY to force grouping one customer's
--              :           transactions together when DUPLICATE CUSTOMER NAMES exist
--2004.3.5      :22/05/07 - Added [TransactionNo] in the SORT ORDER
--              :22/05/07 - Added [CreditTerms] field
--              :22/05/07 - Added [TermsType] field
--              :15/06/07 - Added OrderNo and OrderNotes fields
--2004.4.2      :01/11/08 - Commented in WHERE clause to include transactions
--              :           that have ZERO owing amounts
--V6.3	RL	2017-09-18 - Added option to pull report for specific customer
--V6.3	RL	2017-09-18 - Added option to ignore zero balance statements. 
--						 Month end are now pulled for all customers with transactions for a specific month
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Statements]
    (
        @PeriodProceduresID	int,
		@CustomerID			int,
		@ShowZeroBalance	int
    )

AS

SET NOCOUNT ON

IF @CustomerID = 0
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END
ELSE
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statements_Email
--Purpose       :Retrieves Customer Statement data to E-Mail
--Tables        :
--Date          :2004/06/21
--Authors       :TB
--Version       :1.0.0
--MODS          :11/03/06 - Added RTRIM(LTRIM to [TransactionNo] and [Notes]
--              :           for consistency with similar procedures
--2004.3.5      :22/05/07 - Added [TransactionNo] in the SORT ORDER
--              :22/05/07 - Added [CreditTerms] field
--              :22/05/07 - Added [TermsType] field
--              :15/06/07 - Added OrderNo and OrderNotes fields
--2004.4.2      :01/11/08 - Commented in WHERE clause to include transactions
--              :           that have ZERO owing amounts
--------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_RPT_AC_Customer_Statements_Email
    (
        @StatementID int
    )

AS

SET NOCOUNT ON

    SELECT 
        CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
        tt.[Description] AS [Type], 
        RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
        ISNULL(d.Amount, 0) AS [Amount], 
        ISNULL(d.Payment, 0) AS [Payment], 
        ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
        t.AC_Customers_ID AS [CustomerID], 
        t.FullName AS [Customer],
		ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
        t.Post_Address AS [CustomerPostAddress],
        t.Post_Office AS [CustomerPostOffice],
        t.Post_Code AS [CustomerPostCode],
        ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
        t.Work_Email AS [CustomerEmail],
        t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
        t.[Current],
        t.[30Days],
        t.[60Days],
        t.[90Days],
        (ISNULL(t.[120Days], 0) +
         ISNULL(t.[150Days], 0) +
         ISNULL(t.[180+Days], 0)) AS [120+Days],
        RTRIM(LTRIM(z.Comment)) AS [Notes],
        RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
        RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
    FROM AC_Statements t 
        JOIN AC_Statement_Details d
            ON t.AC_Statements_ID = d.AC_Statements_ID
        INNER JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
        LEFT OUTER JOIN Sys_AW_Transaction_Types tt
            ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AS_Transactions z
            ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
               z.Transaction_Date = d.Transaction_Date AND
               z.Transaction_Number = d.Transaction_Number
    WHERE t.AC_Statements_ID = @StatementID                 --AND
--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
    ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]


SET NOCOUNT OFF


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statements_Temp
--Purpose       :Retrieves Ad-Hoc Customer Statement data in Statements Report
--Tables        :AC_Statements_Temp, AC_Statement_Details_Temp
--Functionality :Prints only Customers with transactions owing
--Date          :2002/06/18
--Authors       :TB
--Version       :1.0.0
--MODS          :24/06/02 - Changed ORDER BY from CustomerID to t.FullName
--              :09/08/02 - Modified ORDER BY to include TransactionDate
--              :19/05/03 - Modified formatting CONVERT(int, d.Transaction_Date)
--              :           that ROUNDS THE DATE UP after 12:00 midday !!!!!!!,
--              :           to CONVERT(CHAR(10), d.Transaction_Date, 121)) that truncates
--              :02/11/04 - Trimmed Transaction_Number and Comment fields
--              :17/05/05 - Reworked ORDER BY to force grouping one customer's
--              :           transactions together when DUPLICATE CUSTOMER NAMES exist
--2004.3.5      :22/05/07 - Added ORDER BY clause and [TransactionNo] in the SORT ORDER
--              :22/05/07 - Added [CreditTerms] field
--              :22/05/07 - Added [TermsType] field
--              :15/06/07 - Added OrderNo and OrderNotes fields
--2004.4.2      :01/11/08 - Commented in WHERE clause to include transactions
--              :           that have ZERO owing amounts
--V6.3	RL	2017-09-18 - Added option to pull report for specific customer
--V6.3	RL	2017-09-18 - Added option to ignore zero balance statements. 
--						 Month end are now pulled for all customers with transactions for a specific month
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Statements_Temp]
    (
        @PeriodProceduresID int,
		@CustomerID			int,
		@ShowZeroBalance	int
    )

AS

SET NOCOUNT ON

IF @CustomerID = 0
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END
ELSE
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
			LEFT JOIN Sys_AC_Credit_Term_Types ctt
				ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
			LEFT OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Transaction_Listing
--Purpose       :Customer Transaction Listing
--Date          :2008/01/17
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AC_Customer_Transaction_Listing
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
	    @Option tinyint,
        @Sort tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '
   
    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' t.Total_Amount AS [Paid], '
    SET @sql = @sql + ' t.Payment_Amount AS [Allocated], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + u.UserName, ''''))) AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = t.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '

    IF @Option = 0
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 3 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 4 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 5 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 7 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 15 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 18 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 21 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 22) '
        END

    IF @Option = 1
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 3 '
        END

    IF @Option = 2
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 4 '
        END

    IF @Option = 3
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 7 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 21 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 22) '
        END

    IF @Option = 4
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 5 '
        END

    IF @Option = 5
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 15 '
        END

    IF @Option = 6
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 18 '
        END

    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END


    IF @Sort = 0        --Date Captured
        BEGIN
            SET @sql = @sql + ' ORDER BY [Captured] ASC '
        END

    IF @Sort = 1        --Transaction Date
        BEGIN
            SET @sql = @sql + ' ORDER BY [TranDate] ASC '
        END

    IF @Sort = 2        --Transaction Number
        BEGIN
            SET @sql = @sql + ' ORDER BY [TranNo] ASC '
        END

    IF @Sort = 3        --Customer
        BEGIN
            SET @sql = @sql + ' ORDER BY [Customer] ASC '
        END


    EXEC (@sql)




SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Enterprise_Customer_Ageing
--Purpose       :Fetch Enterprise Customer Ageing
--Date          :2007/03/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AC_Enterprise_Customer_Ageing
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' CompanyID, '
    SET @sql = @sql + ' SourceDB, '
    SET @sql = @sql + ' Filter, '
    SET @sql = @sql + ' Customer, '
    SET @sql = @sql + ' CustNo, '
    SET @sql = @sql + ' Balance, '
    SET @sql = @sql + ' Days0, '
    SET @sql = @sql + ' Days30, '
    SET @sql = @sql + ' Days60, '
    SET @sql = @sql + ' Days90, '
    SET @sql = @sql + ' ISNULL(Days120, 0) + ISNULL(Days150, 0) + ISNULL(Days180, 0) AS [Days120] '


    SET @sql = @sql + ' FROM AC_Enterprise_Customer_Ageing '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [SourceDB], [CustNo] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [SourceDB], [Customer] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Inactive_Customers
--Purpose       :Fetches Inactive Customers
--Functionality :Conditional upon - No Sales since Last_Sale_Date
--Date          :2007/08/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Inactive_Customers]
    (
        @FromDate			datetime,
        @SortOrder			tinyint,
        @SalespersonID		int,
        @SalesAreaID		int,
        @ActiveCustomers	tinyint,
        @GroupBy			tinyint,
--        @SortBy				tinyint,
        @CompanyID			int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

	IF @GroupBy = 1
		BEGIN
			SET @sql = @sql + ' r.[Description] AS [Group], '
		END

	IF @GroupBy = 2
		BEGIN
			SET @sql = @sql + ' s.[Description] AS [Group], '
		END

    SET @sql = @sql + ' c.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' c.Initials AS [Initials], '
    SET @sql = @sql + ' dbo.fn_AC_Customer_Balance(c.AC_Customers_ID) AS [Balance], '
    SET @sql = @sql + ' CONVERT(CHAR(10), dbo.fn_AC_Get_Last_Sale_Date(c.AC_Customers_ID), 121) as [LastSale], '
    SET @sql = @sql + ' c.Contact_Name AS [ContactName], '
    SET @sql = @sql + ' c.Work_Email AS [Email], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' c.Credit_Limit AS [CreditLimit], '
    SET @sql = @sql + ' c.Credit_Insurers_Limit AS [InsurerLimit], '
    SET @sql = @sql + ' c.Fax_No AS [FaxNo], '
    SET @sql = @sql + ' c.Cell_No AS [CellNo], '
    SET @sql = @sql + ' ISNULL(c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.City, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Street_Post_Code, '''') AS [StreetAddr], '
    SET @sql = @sql + ' a.[Description] AS [Active], '
    SET @sql = @sql + ' r.[Description] AS [Salesperson], '
    SET @sql = @sql + ' s.[Description] AS [SalesArea] '        

    SET @sql = @sql + ' FROM AC_Customers c '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a ' +
                      '         ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AS_Reps r ' +
                      '         ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Sales_Areas s ' +
                      '         ON c.Lup_AC_Sales_Areas_ID = s.Lup_AC_Sales_Areas_ID '

    SET @sql = @sql + ' WHERE c.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND dbo.fn_AC_Get_Last_Sale_Date(c.AC_Customers_ID) <= ' + '''' + CONVERT(varchar(30), @FromDate)  + '''' + ' '
 --   SET @sql = @sql + '   AND dbo.fn_AC_Customer_Balance(c.AC_Customers_ID) = 0 '


	IF @SalespersonID <> 0
		BEGIN
			SET @sql = @sql + ' AND c.Lup_AS_Reps_ID = ' + CONVERT(varchar(10), @SalespersonID) + ' '
		END
		
	IF @SalesAreaID <> 0
		BEGIN
			SET @sql = @sql + ' AND c.Lup_AC_Sales_Areas_ID = ' + CONVERT(varchar(10), @SalesAreaID) + ' '
		END
		
	IF @ActiveCustomers = 1
		BEGIN
			SET @sql = @sql + ' AND c.Slu_AW_Active_ID = 1'
		END

	IF @GroupBy = 0
		BEGIN
			IF @SortOrder = 0
				BEGIN
					SET @sql = @sql + ' ORDER BY [Customer] ASC '
				END

			ELSE    
				BEGIN
					SET @sql = @sql + ' ORDER BY [LastSale] DESC '
				END
		END

	IF @GroupBy = 1
		BEGIN
			IF @SortOrder = 0
				BEGIN
					SET @sql = @sql + ' ORDER BY r.[Description], [Customer] ASC '
				END

			ELSE    
				BEGIN
					SET @sql = @sql + ' ORDER BY r.[Description], [LastSale] DESC '
				END
		END

	IF @GroupBy = 2
		BEGIN
			IF @SortOrder = 0
				BEGIN
					SET @sql = @sql + ' ORDER BY s.[Description], [Customer] ASC '
				END

			ELSE    
				BEGIN
					SET @sql = @sql + ' ORDER BY s.[Description], [LastSale] DESC '
				END
		END
		
--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Nedbank_Invoice_Discounting
--Purpose       :Retrieves LAST Customer Period Procedure Statement data
--              :and APPENDS Current Month (subsequent) Payment/Refund/Adjustment
--              :transactions from AS_Transactions_Transactions table
--Date          :2006/08/11
--Authors       :TB
--MODS          :
--2004.3.1      :28/08/06 - Modified to SELECT ALL FROM AC_Customers
--2004.3.2      :15/09/06 - Added Settlement Discount transaction type when fetch
--              :           ALL UNPAID transactions SINCE Last Period Procedure Date
--              :22/09/06 - Added Insert UNALLOCATED PAYMENT transactions since
--              :           LAST Period Procedure Date
--2004.4.8      :27/05/10 - MODIFIED 'Insert PAYMENT/REFUND/JOURNAL transactions since
--              :           LAST Period Procedure Date' section WHERE clause from
--              :           tt.Date_Captured to t.Date_Captured (using AS_Transactions) !!!!! TPKZN
------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_RPT_AC_Nedbank_Invoice_Discounting
    (
        @CompanyID int,
        @Option tinyint,
        @ReturnValue int OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @LastPeriodProcedureID int,
            @LastPeriodProcedureDate DateTime


    SET @ReturnValue = 0


    --> Step 1: Get the date of the LAST Month-End done
	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date,
                 @LastPeriodProcedureID = AW_Period_Procedures_ID
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          AW_User_Companies_ID = @CompanyID
	ORDER BY Month_End_Date DESC

    --> Step 2: Initialize M/E date if this is the FIRST Month-End procedure
	IF @LastPeriodProcedureDate IS NULL OR @LastPeriodProcedureID IS NULL
        BEGIN
            SET @ReturnValue = 9
        END


    IF @ReturnValue = 0
        BEGIN
            IF @Option = 1        --> ALL CUSTOMERS NOW
                BEGIN
                    SELECT
                        AC_Customers_ID [CustomerID], 
                        REPLACE(ISNULL(Surname, ''), ',', ' ') AS [Customer],
                		ISNULL(Customer_Number, '') AS [CustomerNo],
                        ISNULL(Post_Box, '') AS [CustomerPostAddress],
                        ISNULL(Post_Office, '') AS [CustomerPostOffice],
                        ISNULL(City, '') AS [CustomerCity],
                        '' AS [State],
                        ISNULL(Post_Code, '') AS [CustomerPostCode],
                        ISNULL(Contact_Name, '') AS [Comment],
                        ISNULL(Work_Tel_No, '') AS [TelNo],
                        ISNULL(Credit_Limit, 0) AS [CreditLimit],
                        ISNULL(IDReg_Number, '') AS [IDRegNo]
                    FROM AC_Customers
                    ORDER BY Surname, AC_Customers_ID

                    SET @ReturnValue = 1

                END
        
            ELSE
            IF @Option = 2        --> Statement TRANSACTIONS
                BEGIN
        
                    DECLARE @AC_Statement_Details_Temp table
                        (
                            [AC_Customers_ID] [int] NULL ,
                            [AS_Transactions_ID] [int] NULL ,
                            [Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                            [Surname] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                            [Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                            [Transaction_Date] [datetime] NULL ,
                            [Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
                            [Due_Date] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                            [Customer_Reference] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
                            [Total_Amount] [money] DEFAULT 0 NULL ,
                            [Payment_Amount] [money] DEFAULT 0 NULL ,
                            [Balance] [money] DEFAULT 0 NULL
                        )
        
                    -------------------------------------------------------------------------------
            		--> Insert ALL UNPAID transactions at LAST Period Procedure Date
                    -------------------------------------------------------------------------------
            		INSERT INTO @AC_Statement_Details_Temp
            			(
                            AC_Customers_ID,
                            AS_Transactions_ID,
                            Customer_Number,
                            Surname,
                            Transaction_Number,
                            Transaction_Date,
                            Sys_AW_Transaction_Types_ID,
                            Due_Date,
                            Customer_Reference,
                            Total_Amount,
                            Payment_Amount,
                            Balance
                        )
                    SELECT 
                        s.AC_Customers_ID, 
                        t.AS_Transactions_ID,
                		ISNULL(c.Customer_Number, ''),
                        REPLACE(ISNULL(c.Surname, ''), ',', ' '),
                        d.Transaction_Number, 
                        d.Transaction_Date,
                        d.Sys_AW_Transaction_Types_ID,
                        '',
                        ISNULL(t.Customer_Reference, ''),
                        d.Amount,
                        d.Payment,
                        ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0)
                    FROM AC_Statements s 
                        INNER JOIN AC_Statement_Details d
                            ON s.AC_Statements_ID = d.AC_Statements_ID
                        INNER JOIN AC_Customers c
                            ON s.AC_Customers_ID = c.AC_Customers_ID
                        LEFT JOIN AS_Transactions t
                            ON t.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
                               t.Transaction_Date = d.Transaction_Date AND
                               t.Transaction_Number = d.Transaction_Number
                    WHERE s.AW_Period_Procedures_ID = @LastPeriodProcedureID AND
                          s.AW_User_Companies_ID = @CompanyID AND
                          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
                    ORDER BY c.Surname, s.AC_Customers_ID, d.Transaction_Date




-------------------------------------------------------------------------------
-- THIS SHOWS NORMAL CURRENT
-------------------------------------------------------------------------------
                    -------------------------------------------------------------------------------
            		--> Insert ALL UNPAID transactions SINCE Last Period Procedure Date
                    -------------------------------------------------------------------------------
            		INSERT INTO @AC_Statement_Details_Temp
            			(
                            AC_Customers_ID,
                            AS_Transactions_ID,
                            Customer_Number,
                            Surname,
                            Transaction_Number,
                            Transaction_Date,
                            Sys_AW_Transaction_Types_ID,
                            Due_Date,
                            Customer_Reference,
                            Total_Amount,
                            Payment_Amount,
                            Balance
                        )
                    SELECT
                        t.AC_Customers_ID, 
                        t.AS_Transactions_ID,
                		ISNULL(c.Customer_Number, ''),
                        REPLACE(ISNULL(c.Surname, ''), ',', ' '),
                        t.Transaction_Number, 
                        t.Transaction_Date,
                        t.Sys_AW_Transaction_Types_ID,
                        '',
                        ISNULL(t.Customer_Reference, ''),
                        t.Total_Amount,
                        t.Payment_Amount,
                        t.Total_Amount
                    FROM AS_Transactions t 
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.Transaction_Date > @LastPeriodProcedureDate AND
                          t.AW_User_Companies_ID = @CompanyID AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                          t.Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                          t.Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                          t.Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                          t.Sys_AW_Transaction_Types_ID = 15)    -- OR  --Interest Journal
--                          t.Sys_AW_Transaction_Types_ID = 18)    --Settlement Discount
                    ORDER BY c.Surname, t.AC_Customers_ID, t.Transaction_Date
-------------------------------------------------------------------------------
-->>>>>> OK up to HERE -->>>>>>
-------------------------------------------------------------------------------


                    -------------------------------------------------------------------------------
            		--> Insert UNALLOCATED PAYMENT transactions since LAST Period Procedure Date
                    -------------------------------------------------------------------------------
            		INSERT INTO @AC_Statement_Details_Temp
            			(
                            AC_Customers_ID,
                            AS_Transactions_ID,
                            Customer_Number,
                            Surname,
                            Transaction_Number,
                            Transaction_Date,
                            Sys_AW_Transaction_Types_ID,
                            Due_Date,
                            Customer_Reference,
                            Total_Amount,
                            Payment_Amount,
                            Balance
                        )
                    SELECT
                        t.AC_Customers_ID, 
                        t.AS_Transactions_ID,
                		ISNULL(c.Customer_Number, ''),
                        REPLACE(ISNULL(c.Surname, ''), ',', ' '),
                        t.Transaction_Number, 
                        t.Transaction_Date,
                        t.Sys_AW_Transaction_Types_ID,
                        '',
                        ISNULL(t.Customer_Reference, ''),
                        t.Total_Amount,
                        t.Payment_Amount,
                        ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)
                    FROM AS_Transactions t
                        LEFT JOIN AS_Transactions_Transactions tt
                            ON tt.Destination_AS_Transactions_ID = t.AS_Transactions_ID
                        LEFT JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.Transaction_Date > @LastPeriodProcedureDate AND
                          t.AW_User_Companies_ID = @CompanyID AND
                         (t.Sys_AW_Transaction_Types_ID = 7 OR        --POS Payment
                          t.Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
                          t.Sys_AW_Transaction_Types_ID = 22) AND     --EFT Payment
                          ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
                          tt.Source_AS_Transactions_ID IS NULL
                    ORDER BY c.Surname, t.AC_Customers_ID, t.Transaction_Date


                    -------------------------------------------------------------------------------
            		--> Insert PAYMENT/REFUND/JOURNAL transactions since LAST Period Procedure Date
                    -------------------------------------------------------------------------------
            		INSERT INTO @AC_Statement_Details_Temp
            			(
                            AC_Customers_ID,
                            AS_Transactions_ID,
                            Customer_Number,
                            Surname,
                            Transaction_Number,
                            Transaction_Date,
                            Sys_AW_Transaction_Types_ID,
                            Due_Date,
                            Customer_Reference,
                            Total_Amount,
                            Payment_Amount,
                            Balance
                        )
                    SELECT
                        t.AC_Customers_ID, 
                        t.AS_Transactions_ID,
                		ISNULL(c.Customer_Number, ''),
                        REPLACE(ISNULL(c.Surname, ''), ',', ' '),
                        cr.Transaction_Number, 
                        tt.Date_Captured,
                        t.Sys_AW_Transaction_Types_ID,
                        '',
                        ISNULL(cr.Customer_Reference, ''),
                        cr.Total_Amount,
                        cr.Payment_Amount,
                        tt.Amount
                    FROM AS_Transactions_Transactions tt
                        INNER JOIN AS_Transactions t
                            ON tt.Destination_AS_Transactions_ID = t.AS_Transactions_ID
                        INNER JOIN AS_Transactions cr
                            ON tt.Source_AS_Transactions_ID = cr.AS_Transactions_ID
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.Date_Captured > @LastPeriodProcedureDate AND                    -- tt. (Date_Captured) s/b t. (AS_Transactions Date_Captured) !!!!! TPKZN
                          tt.AW_User_Companies_ID = @CompanyID AND
                          tt.Source_AS_Transactions_ID IS NOT NULL AND
                         (t.Sys_AW_Transaction_Types_ID = 21 OR       --Back Office Payment
                          t.Sys_AW_Transaction_Types_ID = 22)         --EFT Payment
                    ORDER BY c.Surname, t.AC_Customers_ID, tt.Date_Captured


                    -------------------------------------------------------------------------------
            		--> SELECT ALL from @AC_Statement_Details_Temp
                    -------------------------------------------------------------------------------
                    SELECT 
                        AS_Transactions_ID AS [TranID],
                        AC_Customers_ID AS [CustomerID], 
                		Customer_Number AS [CustomerNo],
                        Surname AS [Customer],

                        Transaction_Number AS [TransactionNo], 
                        Transaction_Date AS [TranDate],

                        LEFT(CONVERT(CHAR(10), Transaction_Date, 101), 2) +
                            SUBSTRING(CONVERT(CHAR(10), Transaction_Date, 101), 4, 2) +
                            RIGHT(CONVERT(CHAR(10), Transaction_Date, 101), 2) AS [TransactionDate], 

                        CASE WHEN Sys_AW_Transaction_Types_ID = 3    --Invoice
                                 THEN 'I'
                             WHEN Sys_AW_Transaction_Types_ID = 4    --Refund
                                 THEN 'C'
                             WHEN Sys_AW_Transaction_Types_ID = 5    --Journal
                                 THEN 'A'
                             WHEN Sys_AW_Transaction_Types_ID = 7    --POS Payment
                                 THEN 'P'
                             WHEN Sys_AW_Transaction_Types_ID = 18   --Settlement
                                 THEN 'P'
                             WHEN Sys_AW_Transaction_Types_ID = 21   --BOF Payment
                                 THEN 'P'
                             WHEN Sys_AW_Transaction_Types_ID = 22   --EFT Payment
                                 THEN 'P'
                        END AS [Type],
        
                        Due_Date AS [DueDate],
                        Customer_Reference AS [PONumber],
        
--                         ISNULL(Total_Amount, 0) AS [Amount], 
--                         ISNULL(Payment_Amount, 0) AS [Payment], 
                        ISNULL(Balance, 0) AS [Balance]
                    FROM @AC_Statement_Details_Temp
                    ORDER BY Surname, AC_Customers_ID, Transaction_Date
                    -------------------------------------------------------------------------------
        
                    SET @ReturnValue = 2
        
                END
        END



SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Payment_Allocations
--Purpose       :Customer Payment Transaction Allocations
--Date          :2004/05/03
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------
--EXEC sp_RPT_AC_Payment_Allocations 1, 1, '2003/09/01 12:00:01 AM', '2003/09/30 11:59:59 PM'
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AC_Payment_Allocations
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


    SET @sql = ' SELECT '
   
    SET @sql = @sql + ' tp.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' talloc.Transaction_Date AS [Date], '
    SET @sql = @sql + ' th.Day_End AS [DayEnd], '
    SET @sql = @sql + ' tp.AS_Transaction_Payments_ID AS [TranPayID], '
    SET @sql = @sql + ' tr.AS_Transactions_Transactions_ID AS [TranTranID], '
    SET @sql = @sql + ' tr.Destination_AS_Transactions_ID AS [PaymentID], '
    SET @sql = @sql + ' tr.Source_AS_Transactions_ID AS [AllocationID], '

    SET @sql = @sql + ' th.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' th.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' th.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + csh.FirstName, '''') + ISNULL(csh.Surname, ''''))) AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' ISNULL(tp.Payor_Name, '''') AS [Payor],  '

    SET @sql = @sql + ' CASE WHEN talloc.Sys_AW_Transaction_Types_ID = 7 '
    SET @sql = @sql + '      THEN ''POS'' '
    SET @sql = @sql + '      WHEN talloc.Sys_AW_Transaction_Types_ID = 22 '
    SET @sql = @sql + '      THEN ''EFT'' '
    SET @sql = @sql + '      ELSE ''BOF'' '
    SET @sql = @sql + ' END AS [Location], '

    SET @sql = @sql + ' ci.[Description] AS [Institution], ' 
    SET @sql = @sql + ' tp.Sys_AW_Payment_Methods_ID as [MethodID], '
    SET @sql = @sql + ' pm.[Description] AS [Method], '
    SET @sql = @sql + ' ISNULL(tp.Card_Expiry_Date, '''') AS [Expiry], ' 
    SET @sql = @sql + ' ISNULL(tp.Card_Number, '''') AS [Card No], '
    SET @sql = @sql + ' ISNULL(tp.Authorisation_Number, '''') AS [Auth], ' 

    SET @sql = @sql + ' tp.Amount AS [Paid], '
    SET @sql = @sql + ' tr.Amount AS [Allocated], '
    SET @sql = @sql + ' th.Total_Amount AS [TranTotal], '
    SET @sql = @sql + ' th.Payment_Amount AS [TranPayment], '
    SET @sql = @sql + ' ISNULL(th.Total_Amount, 0) + ISNULL(th.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' u.UserName AS [User], '
    SET @sql = @sql + ' th.Cashed_Up '
    
    SET @sql = @sql + ' FROM AS_Transaction_Payments tp '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions_Transactions tr '
    SET @sql = @sql + '         ON tr.Destination_AS_Transactions_ID = tp.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions th '
    SET @sql = @sql + '         ON tr.Source_AS_Transactions_ID = th.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions talloc '
    SET @sql = @sql + '         ON tr.Destination_AS_Transactions_ID = talloc.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = th.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users csh '
    SET @sql = @sql + '          ON th.Lup_AS_Cashiers_ID = csh.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON th.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Payment_Methods pm '
    SET @sql = @sql + '         ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID ' 
    SET @sql = @sql + '     LEFT JOIN Slu_AS_Card_Institutions ci '
    SET @sql = @sql + '         ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON tp.User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE th.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


--     IF @ChkDates = 1    --From/To Dates
--         BEGIN
--             SET @sql = @sql + '  AND th.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
--             SET @sql = @sql + '  AND th.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
--         END

    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND tp.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND tp.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END

--    SET @sql = @sql + ' ORDER BY [DayEnd], [PaymentID], [AllocationID] ASC '
--    SET @sql = @sql + ' ORDER BY [PaymentID], [AllocationID], [DayEnd] ASC '
    SET @sql = @sql + ' ORDER BY [DayEnd], [PaymentID], [AllocationID] ASC '

    EXEC (@sql)



SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Prospect_Listing
--Purpose       :Prospect Listing
--Date          :2011/03/08
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AC_Prospect_Listing
    (
        @CompanyID int
    )
AS


SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Prospects_ID AS [ProspectID], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') AS [Surname], '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') AS [Tradename], '
    SET @sql = @sql + ' ISNULL(c.Head_Office, '''') AS [HeadOffice], '
    SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Prospects_ID) + '')'' AS [ProspectNo], '

    SET @sql = @sql + ' c.Contact_Name AS [Contact], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTel], '
    SET @sql = @sql + ' c.Fax_No AS [FaxTel], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '

    SET @sql = @sql + ' ctype.[Description] AS [CustomerType], '
    SET @sql = @sql + ' cgrp.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' atype.[Description] AS [AccountType], '
    SET @sql = @sql + ' astatus.[Description] AS [AccountStatus], '
--     SET @sql = @sql + ' ISNULL(c.Credit_Limit, 0) AS [CreditLimit], '
--     SET @sql = @sql + ' ct.[Description] AS [CreditTerms], '
    SET @sql = @sql + ' act.[Description] AS [Active] '
    
    SET @sql = @sql + ' FROM AC_Prospects c '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '          ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Credit_Term_Types ctt '
    SET @sql = @sql + '          ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Groups cgrp '
    SET @sql = @sql + '          ON c.Lup_AC_Customer_Groups_ID = cgrp.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Types ctype '
    SET @sql = @sql + '          ON c.Lup_AC_Customer_Types_ID = ctype.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Account_Types atype '
    SET @sql = @sql + '          ON c.Sys_AC_Account_Types_ID = atype.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Account_Status astatus '
    SET @sql = @sql + '          ON c.Sys_AC_Account_Status_ID = astatus.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Active act '
    SET @sql = @sql + '          ON c.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    SET @sql = @sql + ' ORDER BY [Surname] ASC '


    EXEC (@sql)


SET NOCOUNT OFF
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Sales_Analysis
--Purpose       :Retrieves Customer Sales Analysis for last rolling 12 months
--Functionality :Uses TABLE datatype
--              :    Conditional upon:
--              :        Customer Has_Sales
--Date          :2005/05/08
--Authors       :TB
--MODS:         :
--2004.3.7      :05/08/07 - Added grouping fields [HeaderID] and [Filter]
--2004.4.0      :16/07/08 - Added @ExcludeInterCo, @ExcludeCashAcc, @ExcludeInActive
--              :           input parameters - TW
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AC_Sales_Analysis
    (
        @Option tinyint,
        @ExcludeInterCo tinyint,
        @ExcludeCashAcc tinyint,
        @ExcludeInActive tinyint,
        @SortOrder tinyint,
        @EndDate datetime,
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartDate datetime

-- SET @Option = 1
-- SET @ExcludeInterCo = 1
-- SET @ExcludeCashAcc = 1
-- SET @ExcludeInActive = 1
-- SET @CompanyID = 1
-- SET @EndDate = '2005/03/31 23:59:59'
-- SET @Jan = '012005'
-- SET @Feb = '022005'
-- SET @Mar = '032005'
-- SET @Apr = '042004'
-- SET @May = '052004'
-- SET @Jun = '062004'
-- SET @Jul = '072004'
-- SET @Aug = '082004'
-- SET @Sep = '092004'
-- SET @Oct = '102004'
-- SET @Nov = '112004'
-- SET @Dec = '122004'

    SET @StartDate = DATEADD(yy, -1, @EndDate)

---------------------------------------------
--> using TABLE datatype
---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AC_Customers_Temp]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AC_Customers_Temp]

    DECLARE @ActiveCustomers table
                (
                    [AC_Customers_ID] int
                )

    INSERT INTO @ActiveCustomers
    SELECT DISTINCT AC_Customers_ID
    FROM AS_Transactions
    WHERE dbo.fn_AC_Customer_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    SELECT DISTINCT AC_Customers_ID
    INTO AC_Customers_Temp
    FROM @ActiveCustomers
    ORDER BY AC_Customers_ID

---------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Customers_ID AS [CustID], '


    IF @SortOrder = 0        -- 'Customer'
        SET @sql = @sql + ' o.AW_User_Companies_ID AS [HeaderID], ' +
                          ' o.Company_Name AS [Filter], '
    ELSE
    IF @SortOrder = 1        -- 'Sales Area'
        SET @sql = @sql + ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
                          ' o.[Description] AS [Filter], '
    ELSE
    IF @SortOrder = 2        -- 'Sales Person'
        SET @sql = @sql + ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
                          ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') AS [CustNo], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '   INNER JOIN AS_Transactions h '
    SET @sql = @sql + '       ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '     dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jan + ''' AND '
    SET @sql = @sql + '    (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '     h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [JAN], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '   INNER JOIN AS_Transactions h '
    SET @sql = @sql + '       ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '     dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Feb + ''' AND '
    SET @sql = @sql + '    (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '     h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [FEB], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Mar + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [MAR], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Apr + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [APR], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @May + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [MAY], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jun + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [JUN], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jul + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [JUL], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Aug + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [AUG], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Sep + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [SEP], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Oct + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [OCT], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Nov + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [NOV], '

    SET @sql = @sql + ' ISNULL(( '

    IF @Option = 0
        SET @sql = @sql + ' SELECT SUM(d.Quantity) '

    ELSE
    IF @Option = 1
        SET @sql = @sql + ' SELECT SUM(d.Extended_Amount) '

    ELSE
    IF @Option = 2
        SET @sql = @sql + ' SELECT SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) '

    SET @sql = @sql + '  FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '  WHERE h.AC_Customers_ID = c.AC_Customers_ID AND '
    SET @sql = @sql + '        dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Dec + ''' AND '
    SET @sql = @sql + '       (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '  GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [DEC] '

    SET @sql = @sql + ' FROM AC_Customers c '
    SET @sql = @sql + ' INNER JOIN AC_Customers_Temp temp ' +
                      '  ON c.AC_Customers_ID = temp.AC_Customers_ID '


    IF @SortOrder = 0        --'None'
        SET @sql = @sql + ' INNER JOIN AW_User_Companies o ' +
                          '  ON c.AW_User_Companies_ID = o.AW_User_Companies_ID '
    ELSE
    IF @SortOrder = 1        --'Sales Area'
        SET @sql = @sql + ' LEFT JOIN Lup_AC_Sales_Areas o ' +
                          '  ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @SortOrder = 2        --'Sales Person'
        SET @sql = @sql + ' LEFT JOIN Lup_AS_Reps o ' +
                          '  ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    SET @sql = @sql + '  WHERE c.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    -----------------------------------------------------------------
    -- Exclude Inter-Company Customers
    IF @ExcludeInterCo = 1
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
        END
    -----------------------------------------------------------------
    -- Exclude Cash Account Customers
    IF @ExcludeCashAcc = 1
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 1 '
        END
    -----------------------------------------------------------------
    -- Exclude Inactive Customers
    IF @ExcludeInActive = 1
        BEGIN
            SET @sql = @sql + '  AND c.Slu_AW_Active_ID = 1 '
        END
    -----------------------------------------------------------------


    SET @sql = @sql + ' ORDER BY [Filter], [Customer] '


--    PRINT @sql

    EXEC (@sql)


---------------------------------------------
--> NEW 20/10/03
---------------------------------------------
    DROP TABLE AC_Customers_Temp
---------------------------------------------








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_TopCustomer_Pareto
--Purpose       :
--Date          :2005/11/07
--Authors       :TB
--MODS:         :
--2004.3.8      :11/04/08 - Added @ExcludeInterCo input parameter to exclude
--              :           Inter-Company Customers
--2004.4.2      :23/01/08 - Fixed Divide by Zero CASE validation for [Discount%]
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AC_TopCustomer_Pareto
    (
        @StartDate as datetime,
        @EndDate as datetime,
        @SortOrder tinyint,
        @Option tinyint,
        @ExcludeInterCo tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    IF @Option = 0    -- Top 20% Customers
        BEGIN
            SET @sql = ' SELECT TOP 20 PERCENT WITH TIES '
        END
    ELSE
    IF @Option = 1    -- ALL Customers
        BEGIN
            SET @sql = ' SELECT  '
        END

    SET @sql = @sql + ' MAX(c.AW_User_Companies_ID) as [CompanyID], '
    SET @sql = @sql + ' MAX(c.AC_Customers_ID) as [CustomerID], '
    SET @sql = @sql + ' MAX(c.Customer_Number) AS [CustomerNo], '

    SET @sql = @sql + ' ISNULL(MAX(c.Surname), '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(MAX(c.Firstnames), '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), MAX(c.AC_Customers_ID)) + '')'''
    SET @sql = @sql + ' + '' ('' + ISNULL(MAX(c.Customer_Number), '''') + '')'' AS [Customer], '

    SET @sql = @sql + ' SUM(d.Quantity) AS [Qty], '

    SET @sql = @sql + ' SUM(d.Original_Price * d.Quantity) AS [GrossSales], '
    SET @sql = @sql + ' SUM((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) AS [Discount], '


    SET @sql = @sql + ' CASE WHEN SUM(d.Original_Price * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN SUM((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / SUM(d.Original_Price * d.Quantity) * 100 '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Discount%], '

    SET @sql = @sql + ' SUM(d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' SUM(d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '

    SET @sql = @sql + ' CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100 '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%] '
-- 
--     SET @sql = @sql + ' MAX(dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), p.Last_Cost)) as [Std GP %], '
-- 
--     SET @sql = @sql + ' MAX(CONVERT(CHAR(10), dbo.GetEffectiveDate(p.Price1_Effective_Date, p.Price2_Effective_Date, getdate()) , 121)) AS [Effective], '
--     SET @sql = @sql + ' MAX(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())) as [Unit Price], '

--     SET @sql = @sql + ' MAX(p.Last_Cost) AS [Last Cost], '
--     SET @sql = @sql + ' MAX(p.Average_Cost) AS [Avg Cost], '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Transaction_Date >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @sql = @sql + '  AND  h.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       h.Sys_AW_Transaction_Types_ID = 4)'


    -- Exclude Inter-Company Customers
    IF @ExcludeInterCo = 1
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    SET @sql = @sql + ' GROUP BY c.AC_Customers_ID '


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Qty] DESC '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [NetSales] DESC '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Cost] DESC '
        END
    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [GP] DESC '
        END
    ELSE
    IF @SortOrder = 4
        BEGIN
            SET @sql = @sql + ' ORDER BY [Customer] '
        END
    ELSE
    IF @SortOrder = 5
        BEGIN
            SET @sql = @sql + ' ORDER BY [CustomerNo] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER [Customer] '
        END

--PRINT @sql

EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_TranType_Audit_Trail
--Purpose       :Customer Transaction Types Audit Trail
--Date          :2004/10/25
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------
--EXEC sp_RPT_AC_TranType_Audit_Trail 1, 1, 388, 0, 0, '2003/11/01 12:00:01 AM', '2003/11/22 11:59:59 PM'
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_RPT_AC_TranType_Audit_Trail
    (
            @CompanyID int,
            @ChkAllCustomers int,
            @CustomerID int,
            @TranTypes tinyint,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 1627
-- SET @TranTypes = 0
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '

    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '

    SET @sql = @sql + ' h.Total_Cost AS [Cost], '
    SET @sql = @sql + ' h.Amount AS [Amount], '
    SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' h.Total_Discount_Amount AS [Discount], '
    SET @sql = @sql + ' h.Total_Amount AS [Total], '
    SET @sql = @sql + ' h.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) AS [Balance], '

    SET @sql = @sql + ' til.[Description] AS [Till], '
    SET @sql = @sql + ' ISNULL(cas.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(cas.Surname, '''') AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '

    SET @sql = @sql + ' h.Cashed_Up AS [Cashed Up], '
    SET @sql = @sql + ' h.Day_End AS [Day End], '
    SET @sql = @sql + ' LEFT(ISNULL(g.Description, ''''), 20) AS [GL Account], '
    SET @sql = @sql + ' h.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User], '
    SET @sql = @sql + ' act.[Description] AS [Active] '
    
    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users cas '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = cas.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN AB_Accounts g '
    SET @sql = @sql + '          ON h.AB_Accounts_ID = g.AB_Accounts_ID '

    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Active act '
    SET @sql = @sql + '          ON h.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    IF @TranTypes = 0          --ALL Transaction Types
        BEGIN
            SET @sql = @sql +
                ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
        END
    ELSE                       --Selected Transaction Type
        BEGIN
            SET @sql = @sql +
                ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
                '    AND h.Sys_AW_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypes) + ' '
        END


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY [Customer], [TranDate] ASC '


    EXEC (@sql)


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Transactions_Audit_Trail
--Purpose       :Customer Transactions Audit Trail Report
--Date          :2004/01/07
--Authors       :TB
--Version       :1.0.0
--MODS:         :11/10/04 - Replaced Transaction Type selection from ALL or SINGLE
--              :           to selected FINACIAL or ALL Transactions Types
--              :11/10/04 - Added CustomerID to Customer Name field
--              :11/10/04 - Added Customer Credit Terms fields
--2004.4.7      :13/09/09 - Added Stock Transfer TranType = 23
-------------------------------------------------------------------------------
--EXEC sp_RPT_AC_Transactions_Audit_Trail 1, 1, 388, 0, 0, '2003/11/01 12:00:01 AM', '2003/11/22 11:59:59 PM'
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AC_Transactions_Audit_Trail
    (
            @CompanyID int,
            @ChkAllCustomers int,
            @CustomerID int,
            @TranTypes tinyint,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 1627
-- SET @TranTypes = 0
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' c.Customer_Number AS [CustNo], '
    SET @sql = @sql + ' ct.[Description] AS [CreditTerms], '
    SET @sql = @sql + ' ctt.[Description] AS [TermsType], '
    SET @sql = @sql + ' ISNULL(c.Credit_Limit, 0) AS [CreditLimit], '
    SET @sql = @sql + ' cut.[Description] AS [CustomerType], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '

    SET @sql = @sql + ' h.Total_Cost AS [Cost], '
    SET @sql = @sql + ' h.Amount AS [Amount], '
    SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' h.Total_Discount_Amount AS [Discount], '
    SET @sql = @sql + ' h.Total_Amount AS [Total], '
    SET @sql = @sql + ' h.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) AS [Balance], '

    SET @sql = @sql + ' til.[Description] AS [Till], '
    SET @sql = @sql + ' ISNULL(cas.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(cas.Surname, '''') AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '

    SET @sql = @sql + ' h.Cashed_Up AS [Cashed Up], '
    SET @sql = @sql + ' h.Day_End AS [Day End], '
    SET @sql = @sql + ' LEFT(ISNULL(g.Description, ''''), 20) AS [GL Account], '
    SET @sql = @sql + ' h.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User], '
    SET @sql = @sql + ' act.[Description] AS [Active] '
    
    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users cas '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = cas.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '          ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AC_Credit_Term_Types ctt '
    SET @sql = @sql + '          ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Types cut '
    SET @sql = @sql + '          ON c.Lup_AC_Customer_Types_ID = cut.Lup_AC_Customer_Types_ID '

    SET @sql = @sql + '      LEFT JOIN AB_Accounts g '
    SET @sql = @sql + '          ON h.AB_Accounts_ID = g.AB_Accounts_ID '

    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Active act '
    SET @sql = @sql + '          ON h.Slu_AW_Active_ID = act.Slu_AW_Active_ID '


    SET @sql = @sql +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 4 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 5 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 7 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 15 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 18 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 21 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 22 '

    IF @TranTypes = 1          --ALL Transaction Types
        BEGIN
            SET @sql = @sql + 
                '    OR h.Sys_AW_Transaction_Types_ID = 1 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 2 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 13 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 16 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 17 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 23) '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ') '
        END


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY [Customer], [TranDate] ASC '


    EXEC (@sql)


SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Unallocated_Payments
--Purpose       :Returns Customer Unallocated Payment Allocations
--              :for Payments, Refunds, Journals
--Date          :2006/08/16
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AC_Unallocated_Payments
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @Option tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
   
    SET @sql = @sql + ' tt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.Transaction_Date AS [Date], '
    SET @sql = @sql + ' cr.Day_End AS [DayEnd], '
--    SET @sql = @sql + ' tp.AS_Transaction_Payments_ID AS [TranPayID], '
    SET @sql = @sql + ' tt.AS_Transactions_Transactions_ID AS [TranTranID], '
    SET @sql = @sql + ' tt.Destination_AS_Transactions_ID AS [PaymentID], '
    SET @sql = @sql + ' tt.Source_AS_Transactions_ID AS [AllocationID], '

    SET @sql = @sql + ' cr.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' cr.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' cr.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(ttyp.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + csh.FirstName, '''') + ISNULL(csh.Surname, ''''))) AS [Cashier], '

    SET @sql = @sql + ' CASE WHEN t.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '      WHEN t.Sys_AW_Transaction_Types_ID = 5 '
    SET @sql = @sql + '          THEN ''JNL'' '
    SET @sql = @sql + '      WHEN t.Sys_AW_Transaction_Types_ID = 7 '
    SET @sql = @sql + '          THEN ''POS'' '
    SET @sql = @sql + ' END AS [Location], '

    SET @sql = @sql + ' t.Total_Amount AS [Paid], '
    SET @sql = @sql + ' tt.Amount AS [Allocated], '
    SET @sql = @sql + ' t.Transaction_Number AS [ReceiptNo], '
    SET @sql = @sql + ' cr.Total_Amount AS [TranTotal], '
    SET @sql = @sql + ' ISNULL(cr.Total_Amount, 0) + ISNULL(tt.Amount, 0) AS [Difference], '
    SET @sql = @sql + ' cr.Payment_Amount AS [TranPayment], '
    SET @sql = @sql + ' ISNULL(cr.Total_Amount, 0) + ISNULL(cr.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + u.FirstName, '''') + ISNULL(u.Surname, ''''))) AS [User] '


    SET @sql = @sql + ' FROM AS_Transactions_Transactions tt '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions t '
    SET @sql = @sql + '         ON tt.Destination_AS_Transactions_ID = t.AS_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions cr '
    SET @sql = @sql + '         ON tt.Source_AS_Transactions_ID = cr.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON cr.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types ttyp '
    SET @sql = @sql + '          ON cr.Sys_AW_Transaction_Types_ID = ttyp.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users csh '
    SET @sql = @sql + '          ON cr.Lup_AS_Cashiers_ID = csh.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON cr.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON tt.User_ID = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE tt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       tt.Source_AS_Transactions_ID IS NOT NULL '


    IF @Option = 0
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 4 OR '       --Refund
            SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 5 OR '       --Journal
            SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 7) '         --Payment
        END


    IF @Option = 1
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 7 '         --Payment
        END


    IF @Option = 2
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 5 '         --Journal
        END



    IF @Option = 3
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 4 '         --Refund
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND tt.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND tt.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END


    SET @sql = @sql + ' ORDER BY [Customer], [PaymentID], [AllocationID] ASC '


    EXEC (@sql)




SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_RPT_AF_Casing_Credit_Inventory_GL
--Purpose       :Fetch Casing Credit GL Inventory transactions
--Date          :2011/07/10
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AF_Casing_Credit_Inventory_GL
    (
        @chkCFCDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' j.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' j.Job_No AS [Job No], '
    SET @sql = @sql + ' j.Job_Date AS [Date], '
    SET @sql = @sql + ' j.Billing_No AS [Refund No], '
    SET @sql = @sql + ' j.Billing_Date AS [CFC Date], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Customer], '
    SET @sql = @sql + ' f.Old_Code AS [Make], '
    SET @sql = @sql + ' j.Serial_No AS [Serial No], '
    SET @sql = @sql + ' p.Description AS [Casing Product], '
    SET @sql = @sql + ' sp.Description AS [Stock Product], '
    SET @sql = @sql + ' j.Casing_Credit AS [Casing Credit], '
    SET @sql = @sql + ' j.Stock_Cost AS [Stock Cost], '

    SET @sql = @sql + ' m.[Description] AS [Month], '
    SET @sql = @sql + ' y.[Description] AS [Year], '
    SET @sql = @sql + ' a.Description AS [GLAccount], '
    SET @sql = @sql + ' g.AB_Transaction_Date AS [GLDate], '
    SET @sql = @sql + ' g.AB_Transaction_Amount AS [GLAmount], '
    SET @sql = @sql + ' g.AB_Source_Ref AS [SourceRef], '
    SET @sql = @sql + ' g.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + ' e.UserName AS [User] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products sp '
    SET @sql = @sql + '         ON j.AP_Stock_Products_ID = sp.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AP_Product_Manufacturers f '
    SET @sql = @sql + '         ON j.Lup_AP_Product_Manufacturers_ID = f.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '     INNER JOIN dbo.AB_GL_Transactions g '
    SET @sql = @sql + '         ON j.Job_No = g.AB_Transaction_Ref '
    SET @sql = @sql + '     INNER JOIN dbo.AB_Accounts a '
    SET @sql = @sql + '         ON g.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON g.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON g.Slu_AW_Years_ID = y.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users e '
    SET @sql = @sql + '         ON a.[User_ID] = e.AW_Users_ID '

    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND j.AS_Transactions_ID IS NOT NULL '
    SET @sql = @sql + ' AND j.AP_Inventory_Adjustments_ID IS NOT NULL '
    SET @sql = @sql + ' AND j.Billing_Date = g.AB_Transaction_Date '
    SET @sql = @sql + ' AND g.Sys_AB_Transaction_Types_ID = 15 '


    IF @chkCFCDate = 1
        BEGIN
            SET @sql = @sql + ' AND j.Billing_Date >= ' + '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND j.Billing_Date <= ' + '''' + CONVERT(varchar(30), @ToDate) + '''' + ' '
        END


    SET @sql = @sql + ' ORDER BY [Customer], [CFC Date], [GLRefID] '




--PRINT @sql

EXEC (@sql)




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















-------------------------------------------------------------------------------
--Description   :sp_RPT_AF_Casing_Stock
--Purpose       :Fetch Casing Stock without Waybill
--Date          :2011/05/18
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AF_Casing_Stock
    (
        @chkJobDays tinyint,
        @JobDays smallint,
        @chkJobDate tinyint,
        @JobDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' j.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' j.Job_No AS [Job No], '
    SET @sql = @sql + ' Job_Date AS [Date], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Customer], '
    SET @sql = @sql + ' j.Order_No AS [Order No], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' m.Old_Code AS [Make], '
    SET @sql = @sql + ' j.Serial_No AS [Serial No], '
    SET @sql = @sql + ' i.Description AS [Instruction] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON j.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AF_Instructions i '
    SET @sql = @sql + '         ON j.Lup_AF_Instructions_ID = i.Lup_AF_Instructions_ID '

    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND j.AF_Waybills_ID IS NULL '
    SET @sql = @sql + ' AND j.AO_GRV_ID IS NULL '


    IF @chkJobDays = 1
        BEGIN
            SET @sql = @sql + ' AND j.Job_Date <= DATEADD(dd, ' + CONVERT(varchar(10), -@JobDays) + ', getdate()) '
        END
    ELSE
    IF @chkJobDate = 1
        BEGIN
            SET @sql = @sql + ' AND j.Job_Date <= ' + '''' + CONVERT(varchar(30), @JobDate) + '''' + ' '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' AND j.Job_Date <= DATEADD(dd, ' + CONVERT(varchar(10), -@JobDays) + ', getdate()) '
        END

    SET @sql = @sql + ' ORDER BY [Date], [Customer] '




--PRINT @sql

EXEC (@sql)


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_RPT_AF_Casing_vs_Stock_Product
--Purpose       :Fetch comparison of CFC Casing product vs Stock Product
--Date          :2011/05/18
--Authors       :TB
--MODS:         :
--2004.5.2      :09/07/11 - Added From/To date selection
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AF_Casing_vs_Stock_Product
    (
        @chkCFCDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' j.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' j.Job_No AS [Job No], '
    SET @sql = @sql + ' j.Job_Date AS [Date], '
    SET @sql = @sql + ' j.Billing_No AS [Refund No], '
    SET @sql = @sql + ' j.Billing_Date AS [CFC Date], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Customer], '
    SET @sql = @sql + ' m.Old_Code AS [Make], '
    SET @sql = @sql + ' j.Serial_No AS [Serial No], '
    SET @sql = @sql + ' p.Description AS [Casing Product], '
    SET @sql = @sql + ' sp.Description AS [Stock Product], '
    SET @sql = @sql + ' j.Casing_Credit AS [Casing Credit], '
    SET @sql = @sql + ' j.Stock_Cost AS [Stock Cost] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products sp '
    SET @sql = @sql + '         ON j.AP_Stock_Products_ID = sp.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON j.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '

    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND j.AS_Transactions_ID IS NOT NULL '
    SET @sql = @sql + ' AND j.AP_Inventory_Adjustments_ID IS NOT NULL '


    IF @chkCFCDate = 1
        BEGIN
            SET @sql = @sql + ' AND j.Billing_Date >= ' + '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND j.Billing_Date <= ' + '''' + CONVERT(varchar(30), @ToDate) + '''' + ' '
        END


    SET @sql = @sql + ' ORDER BY [Customer], [CFC Date] '




--PRINT @sql

EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















-------------------------------------------------------------------------------
--Description   :sp_RPT_AF_Outstanding_Jobs
--Purpose       :Fetch Outstanding Jobs at Factory prior to a date
--Date          :2011/05/12
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AF_Outstanding_Jobs
    (
        @chkJobDays tinyint,
        @JobDays smallint,
        @chkJobDate tinyint,
        @JobDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' j.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Factory], '
    SET @sql = @sql + ' j.Job_No AS [Job No], '
    SET @sql = @sql + ' Job_Date AS [Date], '
    SET @sql = @sql + ' j.AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' Waybill_Date AS [Waybill Date], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Customer], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' m.Old_Code AS [Make], '
    SET @sql = @sql + ' j.Serial_No AS [Serial No], '
    SET @sql = @sql + ' i.Description AS [Instruction] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON j.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AF_Instructions i '
    SET @sql = @sql + '         ON j.Lup_AF_Instructions_ID = i.Lup_AF_Instructions_ID '

    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND j.AF_Waybills_ID IS NOT NULL '
    SET @sql = @sql + ' AND j.AO_GRV_ID IS NULL '


    IF @chkJobDays = 1
        BEGIN
            SET @sql = @sql + ' AND j.Waybill_Date <= DATEADD(dd, ' + CONVERT(varchar(10), -@JobDays) + ', getdate()) '
        END
    ELSE
    IF @chkJobDate = 1
        BEGIN
            SET @sql = @sql + ' AND j.Waybill_Date <= ' + '''' + CONVERT(varchar(30), @JobDate) + '''' + ' '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' AND j.Waybill_Date <= DATEADD(dd, ' + CONVERT(varchar(10), -@JobDays) + ', getdate()) '
        END

    SET @sql = @sql + ' ORDER BY [Factory], [Waybill Date], [Customer] '




--PRINT @sql

EXEC (@sql)

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_RPT_AF_Uninvoiced_Jobs
--Purpose       :Fetch Uninvoiced Jobs
--Date          :2011/05/12
--Authors       :TB
--MODS:         :
--2004.5.3      :23/08/11 - Changed ORDER BY to list by CUSTOMER not FACTORY
--2004.5.5      :06/10/11 - Replaced ORDER BY with @SortOrder options
--              :06/10/11 - Replaced full GRV datetime with yyyy/mm/dd format
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AF_Uninvoiced_Jobs
    (
        @chkJobDays tinyint,
        @JobDays smallint,
        @chkJobDate tinyint,
        @JobDate datetime,
        @SortOrder tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' j.AF_Job_Tickets_ID AS [ID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Factory], '
    SET @sql = @sql + ' j.Job_No AS [Job No], '
    SET @sql = @sql + ' Job_Date AS [Date], '
    SET @sql = @sql + ' j.AO_GRV_ID AS [GRV No], '
    SET @sql = @sql + ' CONVERT(datetime, CONVERT(char(10), j.GRV_Date, 121)) [GRV Date], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('', '' + c.City, '''') AS [Customer], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' m.Old_Code AS [Make], '
    SET @sql = @sql + ' j.Serial_No AS [Serial No], '
    SET @sql = @sql + ' i.Description AS [Instruction] '

    SET @sql = @sql + ' FROM AF_Job_Tickets j '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON j.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON j.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON j.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '         ON j.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '     INNER JOIN Lup_AF_Instructions i '
    SET @sql = @sql + '         ON j.Lup_AF_Instructions_ID = i.Lup_AF_Instructions_ID '

    SET @sql = @sql + ' WHERE j.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND j.AO_GRV_ID IS NOT NULL '
    SET @sql = @sql + ' AND j.AS_Transactions_ID IS NULL '
    SET @sql = @sql + ' AND j.AP_Inventory_Adjustments_ID IS NULL '


    IF @chkJobDays = 1
        BEGIN
            SET @sql = @sql + ' AND j.GRV_Date <= DATEADD(dd, ' + CONVERT(varchar(10), -@JobDays) + ', getdate()) '
        END
    ELSE
    IF @chkJobDate = 1
        BEGIN
            SET @sql = @sql + ' AND j.GRV_Date <= ' + '''' + CONVERT(varchar(30), @JobDate) + '''' + ' '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' AND j.GRV_Date <= DATEADD(dd, ' + CONVERT(varchar(10), -@JobDays) + ', getdate()) '
        END


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Factory], [Customer], [GRV Date] '
        END

    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Customer], [GRV Date] '
        END

    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product] '
        END

    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [GRV Date], [Customer] '
        END





--PRINT @sql

EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















-------------------------------------------------------------------------------
--Description   :sp_RPT_AF_Unused_Job_Tickets
--Purpose       :Fetch Unused Job Ticket numbers
--Functionality :Uses T-SQL COALESCE statement
--Date          :2011/05/18
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AF_Unused_Job_Tickets
    (
        @StartNo int,
        @EndNo int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @counter int,
            @NumberList varchar(8000),
            @JobNo int


    ---------------------------------------------
    --> Using TABLE datatype
    ---------------------------------------------
    DECLARE @MissingNumbers table
                (
                    [JobNo] int
                )


    SET @counter = @StartNo
    SET @NumberList = ''

    WHILE @counter <= @EndNo
        BEGIN
            INSERT @MissingNumbers (JobNo) VALUES (@counter)
            SET @counter = @counter + 1
        END


    DELETE a
    FROM @MissingNumbers a
        INNER JOIN AF_Job_Tickets j
            ON a.JobNo = j.Job_No
    WHERE a.JobNo = j.Job_No


    SELECT @NumberList = COALESCE(@NumberList + ',' , '') + CONVERT(varchar(10), JobNo)
    FROM @MissingNumbers
    ORDER BY JobNo


--     DECLARE List_Cursor CURSOR FOR
--         SELECT JobNo
--         FROM @MissingNumbers
--         ORDER BY JobNo
-- 
--     OPEN List_Cursor
-- 
--     FETCH NEXT FROM List_Cursor 
--     INTO
--         @JobNo
-- 
--     WHILE @@FETCH_STATUS = 0
--         BEGIN
--             SET @NumberList = @NumberList + CONVERT(varchar(10), @JobNo) + ','
-- 
--             FETCH NEXT FROM List_Cursor 
--             INTO
--             @JobNo
--         END
-- 
--     CLOSE List_Cursor
--     DEALLOCATE List_Cursor


    IF LEFT(@NumberList, 1) = ','
        BEGIN
            SET @NumberList = REVERSE(LEFT(REVERSE(@NumberList), LEN(@NumberList) - 1))
        END


    SELECT @NumberList AS [Numbers]











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Account_Audit_Trail
--Purpose       :Supplier Account Audit Trail
--Date          :2004/03/18
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------
--EXEC sp_RPT_AO_Account_Audit_Trail 1, 1, 388, 0, '2003/11/01 12:00:01 AM', '2003/11/22 11:59:59 PM'
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AO_Account_Audit_Trail
    (
            @CompanyID int,
            @ChkAllSuppliers int,
            @SupplierID int,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllSuppliers = 1
-- SET @SupplierID = 1627
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(7000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Date_Captured, 121) AS [CalDay], '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + ' t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Document_Date, 121) AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [TranType], '
    SET @sql = @sql + ' t.Document_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(t.Supplier_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(t.Comment, '''') AS [Comment], '
    SET @sql = @sql + ' m.[Description] AS [Month], '
    SET @sql = @sql + ' y.[Description] AS [Year], '

    SET @sql = @sql + ' ISNULL(t.Trade_Discount_Total, 0) + ISNULL(t.Rebate_Discount_Total, 0) + ISNULL(t.Other_Discount_Total, 0) AS [Discount], '
    SET @sql = @sql + ' t.Net_Amount AS [Amount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' t.Date_Captured AS [Date Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AO_Transactions t '
    SET @sql = @sql + '      LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '          ON s.AO_Suppliers_ID = t.AO_Suppliers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      INNER JOIN Slu_AW_Months m '
    SET @sql = @sql + '      	 ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '      INNER JOIN Slu_AW_Years y '
    SET @sql = @sql + '      	 ON t.Slu_AW_Years_ID  = y.Slu_AW_Years_ID '

    SET @sql = @sql +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '   (t.Sys_AW_Transaction_Types_ID = 6 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 8 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 9 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 10 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 11 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 12) '

    IF @ChkAllSuppliers = 0    --Single Supplier Account
        BEGIN
            SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Document_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Document_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY t.AO_Suppliers_ID, t.Date_Captured ASC '


    EXEC (@sql)


SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Age_Analysis_Historical
--Purpose       :Extract Supplier Age Analysis up to Accounting Period Cut-Off
--              :                or optionally up to A Customer Month-End Procedure
--Functions     :fn_AO_Supplier_Period_Ageing_SUM_All     - up to Accounting Period
--              :fn_AO_Supplier_Procedure_Ageing_SUM_All  - up to Customer Month-End
--Date          :2005/09/22
--Authors       :TB
--MODS          :26/03/06 - Reworked as DYNAMIC SQL
--2004.2.7      :26/03/06 - Reworked using definitive cut-offs in both
--                          fn_AO_Supplier_Period_Ageing_SUM_All (now filters by Accounting Period only)
--                          fn_AO_Supplier_Procedure_Ageing_SUM_All (now filters by Date Captured only)
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Age_Analysis_Historical
	(
        @CompanyID 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,
        @ZeroBalances tinyint,
        @MonthEndCutoff tinyint,
        @PeriodProcedureID int
    )


AS

SET NOCOUNT ON


    DECLARE @MonthEndDate datetime,
            @sql varchar(8000)


    SELECT TOP 1 @MonthEndDate = Month_End_Date
    FROM AW_Period_Procedures
    WHERE AW_User_Companies_ID = @CompanyID AND
          AW_Period_Procedures_ID = @PeriodProcedureID


    IF @MonthEndDate IS NULL
        BEGIN
            SET @MonthEndDate = getdate()
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.[CompanyID], '
    SET @sql = @sql + ' a.[SupplierID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Supplier], '
    SET @sql = @sql + ' s.Supplier_Number AS [Supplier No], '
    SET @sql = @sql + ' s.Credit_Limit AS [Credit Limit], '
    SET @sql = @sql + ' ct.[Description] AS [Terms Type], '
    SET @sql = @sql + ' s.Default_Settlement_Discount AS [Default Settlement %], '
    SET @sql = @sql + ' s.Supplier_Contact AS [Contact], '
    SET @sql = @sql + ' s.Supplier_Telephone AS [TelNo], '
    SET @sql = @sql + ' s.Contact_Cellphone AS [CellNo], '
    SET @sql = @sql + ' s.Supplier_Fax AS [FaxNo], '
    SET @sql = @sql + ' s.Post_Box AS [Post Box], '
    SET @sql = @sql + ' s.Post_Office AS [Post Office], '
    SET @sql = @sql + ' s.Post_Code AS [Post Code], '
    SET @sql = @sql + ' s.Email_Address AS [Email], '
    SET @sql = @sql + ' s.Tax_Number AS [Tax No], '
    SET @sql = @sql + ' ISNULL(a.MarkedToPay, 0) AS [MarkedToPay], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [Bank Name], '
    SET @sql = @sql + ' ISNULL(s.Bank_Branch, '''') AS [Branch Name], '
    SET @sql = @sql + ' ISNULL(s.Bank_Branch_Code, '''') AS [Branch Code], '
    SET @sql = @sql + ' ISNULL(s.Account_Name, '''') AS [Account Name], '
    SET @sql = @sql + ' ISNULL(s.Account_Number, '''') AS [Account Number], '
    SET @sql = @sql + ' ISNULL(a.[Current], 0) + '
    SET @sql = @sql + ' ISNULL(a.[30 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[60 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[90 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[120 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[150 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[180+ Days], 0) AS [Balance], '
    SET @sql = @sql + ' a.[Current], '
    SET @sql = @sql + ' a.[30 Days], '
    SET @sql = @sql + ' a.[60 Days], '
    SET @sql = @sql + ' a.[90 Days], '
    SET @sql = @sql + ' a.[120 Days], '
    SET @sql = @sql + ' a.[150 Days], '
    SET @sql = @sql + ' a.[180+ Days], '
    SET @sql = @sql + ' ISNULL(a.[120 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[150 Days], 0) + '
    SET @sql = @sql + ' ISNULL(a.[180+ Days], 0) AS [120+ Days] '


    IF @MonthEndCutoff = 1        --As at SELECTED Customer Period Procedure
        BEGIN
            SET @sql = @sql + ' FROM dbo.fn_AO_Supplier_Procedure_Ageing_SUM_All '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM dbo.fn_AO_Supplier_Period_Ageing_SUM_All '
        END

    SET @sql = @sql + ' ( '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @CompanyID) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M1) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y1) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M2) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y2) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M3) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y3) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M4) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y4) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M5) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y5) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M6) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y6) + ', '
    SET @sql = @sql + ' ' + CONVERT(varchar(20), @M7) + ', '


    IF @MonthEndCutoff = 1        --As at last Customer Period Procedure
        BEGIN
            SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y7) + ', '
            SET @sql = @sql + '''' + CONVERT(varchar(30), @MonthEndDate) + ''''
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ' + CONVERT(varchar(20), @Y7) + ' '
        END



    SET @sql = @sql + ' ) a '


    SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '     ON s.AO_Suppliers_ID = a.SupplierID '
    SET @sql = @sql + ' LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '     ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + ' LEFT JOIN Slu_AW_Banks b '
    SET @sql = @sql + '     ON b.Slu_AW_Banks_ID = s.Slu_AW_Banks_ID '


    IF @ZeroBalances = 0        --DO NOT print ZERO BALANCES
        BEGIN
            SET @sql = @sql + ' WHERE ISNULL(a.[Current], 0) + '
            SET @sql = @sql + '     ISNULL(a.[30 Days], 0) + '
            SET @sql = @sql + '     ISNULL(a.[60 Days], 0) + '
            SET @sql = @sql + '     ISNULL(a.[90 Days], 0) + '
            SET @sql = @sql + '     ISNULL(a.[120 Days], 0) + '
            SET @sql = @sql + '     ISNULL(a.[150 Days], 0) + '
            SET @sql = @sql + '     ISNULL(a.[180+ Days], 0) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY Supplier '




    EXEC (@sql)



SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Consignment_Journal_CR1
--Purpose       :Supplier Consignment JNL Transactions by GL Allocations
--Date          :2015-06-05
--Authors       :RL
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Consignment_Journal_CR1]
    (
        --@Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @SortOrder tinyint,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID],  '
    SET @sql = @sql + ' s.Supplier_Name AS [SupplierName], '

    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') +
                                 '' ('' + ISNULL(s.Supplier_Number, '''') + '')'' +
                                 '' ('' + CONVERT(VARCHAR(10), s.AO_Suppliers_ID) + '') '' +
                                 ISNULL(s.Post_Box, '''') + '', '' +
                                 + ISNULL(s.Post_Office, '''') + '', '' +
                                 + ISNULL(s.Post_Code, '''')
                              AS [SupplierFull], '

    SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date],  '
    SET @sql = @sql + ' tt.Type_Code AS [Type],  '
    SET @sql = @sql + ' t.Supplier_Reference AS [Ref No],  '
    SET @sql = @sql + ' t.Document_Number AS [Doc No],  '

    SET @sql = @sql + ' CASE WHEN t.AO_GRV_ID > 0 '
    SET @sql = @sql + '      THEN t.AO_GRV_ID '
    SET @sql = @sql + '      ELSE 0 '
    SET @sql = @sql + ' END AS [GRV],  '

    SET @sql = @sql + ' t.Comment AS [Notes],  '
    SET @sql = @sql + ' t.Net_Amount AS [Net], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [VAT], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), t.Date_Captured, 121)) AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions_Log l '
            SET @sql = @sql + ' INNER JOIN AO_Transactions t '
            SET @sql = @sql + '     ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions t '
        END

    SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '     ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + ' LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '     ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + '     ON t.User_ID = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '

    --IF @TranLog = 1
    --    BEGIN
    --        SET @sql = @sql + '    (t.Sys_AW_Transaction_Types_ID = 8 OR '
    --        SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 9 OR '
    --        SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 10 OR '
    --        SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 12) AND '
    --    END
    --ELSE
    --    BEGIN
    --        SET @sql = @sql + '    (t.Sys_AW_Transaction_Types_ID = 8 OR '
    --        SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 9) AND '
    --    END

    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + '    (t.Sys_AW_Transaction_Types_ID = 31 OR '
            SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 32) AND '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '    (t.Sys_AW_Transaction_Types_ID = 31 OR '
            SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 32) AND '
        END


    SET @sql = @sql + '     t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '     t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    --IF @Option = 1    --Non-Crv and Multi-Spilt transactions only
    --    BEGIN
    --        SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
    --    END
    --ELSE
    --IF @Option = 2    --CRV transaction only
    --    BEGIN
    --        SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
    --    END


    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [SupplierFull], t.Document_Number '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [SupplierFull], t.Document_Date '
        END



    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Summary
--Purpose       :Purchase JNL CR1 Total Consignment Category Summary
--Date          :2015-06-05
--Authors       :RL
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Summary]
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     MAX(s.Supplier_Name) AS [Supplier], '
    SET @sql = @sql + '     p.Lup_AP_Purchase_Categories_ID AS [PurchCatID], '
    SET @sql = @sql + '     MAX(pc.[Description]) AS [PurchCat], '
    SET @sql = @sql + '     SUM(gd.Qty) AS [Qty], '
    SET @sql = @sql + '     SUM(gd.Net_Amount) AS [Net], '
    SET @sql = @sql + '     SUM(gd.Tax_Amount) AS [Tax], '
    SET @sql = @sql + '     SUM(gd.Total_Cost) AS [Total] '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions_Log l '
            SET @sql = @sql + '     INNER JOIN AO_Transactions t '
            SET @sql = @sql + '         ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions t '
        END


    SET @sql = @sql + '         LEFT JOIN AO_GRV gh '
    SET @sql = @sql + '             ON t.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN  AO_GRV_Details gd '
    SET @sql = @sql + '             ON gh.AO_GRV_ID = gd.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '             ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           t.AO_GRV_ID <> 0 AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND ' 
    --SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 8 OR '
    --SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 9) '
    SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 31 OR '
    SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 32) '

    SET @sql = @sql + '     GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID, p.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     ORDER BY [Supplier], [PurchCat] '



    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Supplier
--Purpose       :Supplier Consignment JNL CR1 SupplierPurchase Category Summary
--Date          :2015-06-05
--Authors       :RL
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Consignment_Journal_CR1_PurchCat_Supplier]
    (
        @SupplierID int,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     p.Lup_AP_Purchase_Categories_ID AS [PurchCatID], '
    SET @sql = @sql + '     MAX(pc.[Description]) AS [PurchCat], '
    SET @sql = @sql + '     SUM(gd.Net_Amount) AS [Net], '
    SET @sql = @sql + '     SUM(gd.Tax_Amount) AS [Tax], '
    SET @sql = @sql + '     SUM(gd.Total_Cost) AS [Total] '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions_Log l '
            SET @sql = @sql + '     INNER JOIN AO_Transactions t '
            SET @sql = @sql + '         ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions t '
        END


    SET @sql = @sql + '         LEFT JOIN AO_GRV gh '
    SET @sql = @sql + '             ON t.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN  AO_GRV_Details gd '
    SET @sql = @sql + '             ON gh.AO_GRV_ID = gd.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           t.AO_GRV_ID <> 0 AND '
    SET @sql = @sql + '           t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND '
    --SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 8 OR '
    --SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 9) '
    SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 31 OR '
    SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 32) '

    SET @sql = @sql + '     GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID, p.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     ORDER BY [PurchCat] '

    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Consignment_Journal_CR1_Summary
--Purpose       :Supplier Consignment JNL Transactions by GL Allocations Summary
--Date          :2015-06-05
--Authors       :RL
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Consignment_Journal_CR1_Summary]
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gl.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     SUM(gt.AB_Transaction_Amount) AS [GLTranAmount], '
    SET @sql = @sql + '     MAX(gl.[Description]) AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' INNER JOIN AO_Transactions_Log l '
            SET @sql = @sql + '     ON gt.AB_Transaction_Ref = l.AO_Transactions_ID '
            SET @sql = @sql + ' INNER JOIN AO_Transactions t '
            SET @sql = @sql + '     ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' INNER JOIN AO_Transactions t '
            SET @sql = @sql + '     ON gt.AB_Transaction_Ref = t.AO_Transactions_ID '
        END


    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '         t.AO_Transactions_ID = gt.AB_Transaction_Ref AND '


    --IF @TranLog = 1
    --    BEGIN
    --        SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 5 OR '
    --        SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 6 OR '
    --        SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 7 OR '
    --        SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 8) AND '
    --    END
    --ELSE
    --    BEGIN
    --        SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 5 OR '
    --        SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 6) AND '
    --    END


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 31 OR '
            SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 32) AND '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 31 OR '
            SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 32) AND '
        END

    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '

    IF @Option = 1    --Non-Crv and Multi-Spilt transactions only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
        END
    ELSE
    IF @Option = 2    --CRV transaction only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
        END

    SET @sql = @sql + '     GROUP BY gt.AW_User_Companies_ID, gl.AB_Accounts_ID '
    SET @sql = @sql + '     ORDER BY MAX(gl.[Description]) '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Comnsignment_Journal_CR3
--Purpose       :Purchase JNL CR3 Total Consignment Category Summary
--Date          :2015-06-05
--Authors       :RL
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Consignment_Journal_CR3]
    (
--        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     MAX(s.Supplier_Name) AS [Supplier], '
    SET @sql = @sql + '     p.Lup_AP_Purchase_Categories_ID AS [PurchCatID], '
    SET @sql = @sql + '     MAX(pc.[Description]) AS [PurchCat], '
    SET @sql = @sql + '     SUM(gd.Qty) AS [Qty], '
    SET @sql = @sql + '     SUM(gd.Net_Amount) AS [Net], '
    SET @sql = @sql + '     SUM(gd.Tax_Amount) AS [Tax], '
    SET @sql = @sql + '     SUM(gd.Total_Cost) AS [Total] '

    SET @sql = @sql + '     FROM AO_Transactions t '
    SET @sql = @sql + '         LEFT JOIN AO_GRV gh '
    SET @sql = @sql + '             ON t.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN  AO_GRV_Details gd '
    SET @sql = @sql + '             ON gh.AO_GRV_ID = gd.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '             ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           t.AO_GRV_ID <> 0 AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND ' 
    --SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 8 OR '
    --SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 9) '
    SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 31 OR '
    SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 32) '


--     IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
--         BEGIN
--             SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
--         END
--     ELSE
--     IF @Option = 2    --GRV transaction only
--         BEGIN
--             SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
--         END


    SET @sql = @sql + '     GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID, p.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     ORDER BY [Supplier], [PurchCat] '



    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Department_Purchases
--Purpose       :Retrieves Ad-Hoc Purchases data for Purchase by Department
--Tables        :
--Parameters    :
--Date          :2002/11/28
--Authors       :TB
--Version       :1.0.0
--MODS          :02/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
--              :02/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
--              :02/01/03 - Added [Month] and [Year] fields to SELECT
--              :15/04/04 - Added GRV field
--              :10/01/05 - Removed DISTINCT filter (Maureen) preventing multiples
--              :           of the same item printing on the report
--V6.2	RL	2016-07-01	:Excluded consignment GRV's
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AO_Department_Purchases]
    (
        @MonthID tinyint,
        @YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Period1 varchar(6)

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

--    SELECT DISTINCT
    SELECT
        t.AO_Suppliers_ID AS [ID], 
        pd.Lup_AP_Product_Departments_ID AS [DeptID],
        ISNULL(pd.[Description], '') AS [DeptName],
        ISNULL(s.Supplier_Name, '') AS [Supplier],
        ISNULL(t.Document_Date, '') AS [Date], 
        ISNULL(t.Document_Number, '') AS [Ref No],
        ISNULL(tt.Type_Code, '') AS [Type], 
        ISNULL(gl.[Description], '') AS [GL Account],

        t.Slu_AW_Months_ID AS [Month],
        t.Slu_AW_Years_ID AS [Year],

        ISNULL(p.[Description], '') AS [Product],
        ISNULL(t.AO_GRV_ID, 0) AS [GRV],
        ISNULL(gd.Qty, 0) AS [Qty],
        ISNULL(gd.Unit_Price, 0) AS [Unit Price],
        ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade],
        ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate],
        ISNULL(gd.Other_Discount_Amount, 0) AS [Other],
        ISNULL(gd.Net_Amount, 0) AS [Sub-Total],
        ISNULL(gd.Tax_Amount, 0) AS [Tax],
        ISNULL(gd.Total_Cost, 0) AS [Total],

        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Last_Cost
            ) as [GP %]

    FROM AO_Transactions t
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
        LEFT OUTER JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AB_Accounts gl
            ON t.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN AO_GRV gh
            ON t.AO_GRV_ID = gh.AO_GRV_ID
        INNER JOIN AO_GRV_Details gd
            On gh.AO_GRV_ID = gd.AO_GRV_ID
        INNER JOIN AP_Products p
            ON gd.AP_Products_ID = p.AP_Products_ID
        INNER JOIN Lup_AP_Product_Departments pd
            ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID

    WHERE t.AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) = @Period1 AND
--           t.Slu_AW_Months_ID = @MonthID AND
--           t.Slu_AW_Years_ID = @YearID
			gh.Sys_AW_Transaction_Types_ID <> 31 AND		--Consignment Goods Received
			gh.Sys_AW_Transaction_Types_ID <> 32 AND		--Consignment Goods Returned
			gh.Sys_AW_Transaction_Types_ID <> 34			--Consignment Sold

    ORDER BY pd.Lup_AP_Product_Departments_ID,
             t.AO_Suppliers_ID,             
             ISNULL(t.Document_Date, '')


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Enterprise_Supplier_Ageing
--Purpose       :Fetch Enterprise Supplier Ageing
--Date          :2008/10/27
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                   PROCEDURE sp_RPT_AO_Enterprise_Supplier_Ageing
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' CompanyID, '
    SET @sql = @sql + ' SourceDB, '
    SET @sql = @sql + ' Filter, '
    SET @sql = @sql + ' Supplier, '
    SET @sql = @sql + ' SuppNo, '
    SET @sql = @sql + ' Balance, '
    SET @sql = @sql + ' Days0, '
    SET @sql = @sql + ' Days30, '
    SET @sql = @sql + ' Days60, '
    SET @sql = @sql + ' Days90, '
    SET @sql = @sql + ' ISNULL(Days120, 0) + ISNULL(Days150, 0) + ISNULL(Days180, 0) AS [Days120] '


    SET @sql = @sql + ' FROM AO_Enterprise_Supplier_Ageing '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [SourceDB], [SuppNo] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [SourceDB], [Supplier] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Outstanding_Orders
--Purpose       :Retrieves Outstanding Orders by Supplier by Order
--Tables        :
--Parameters    :
--Date          :2003/12/27
--Authors       :TB
--Version       :1.0.0
--MODS          :02/04/04 - Added 'Complete' filter after 2004.0.1 !!!!!!!!!
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Outstanding_Orders
    (
        @FromDate datetime,
        @ToDate Datetime,
        @ChkAllSuppliers tinyint,
        @SupplierID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    IF @ChkAllSuppliers = 0    --Single Supplier Account
        BEGIN
            SELECT
                o.AW_User_Companies_ID AS [CompanyID],
                o.AO_Suppliers_ID AS [SupplierID],
                o.AW_Remote_Access_ID AS [RemoteID],
                o.AO_Orders_ID AS [OrderID],
                ISNULL(s.Supplier_Name, '') AS [Supplier],
                ISNULL(r.NodeName, '') AS [Originator],
                ISNULL(o.Order_Number, '') AS [OrderNo],
                o.Order_Date AS [OrderDate], 
                o.Date_Ordered AS [DateOrdered], 
                ISNULL(o.Our_Ref, '') AS [OurRef],
        
                --Header
                o.Supplier_Rep AS [SupplierRep],
                o.Supplier_Type AS [SupplierType],
                o.Confirmation AS [Confirmed],
                o.Confirmation_Date AS [ConfirmDate],
                o.Supplier_Reference AS [SupplierRef],
                o.Invoice_Type AS [InvType],
                o.Invoice_Total AS [InvTotal],
                o.Admin_Fee AS [AdminFee],
                o.Trade_Discount_Total AS [TDiscTotal],
                o.Rebate_Discount_Total AS [RDiscTotal],
                o.Other_Discount_Total AS [ODiscTotal],
                o.Net_Amount AS [NetTotal],
                o.Tax_Total AS [TaxTotal],
                o.Order_Total AS [OrderTotal],
        --        o.Sys_AO_Delivery_Methods_ID,
                m.[Description] AS [DeliverMethod],
                o.Send_To_Address AS [SendToAddr],
                o.Delivery_Addr1 AS [DelAddr1],
                o.Delivery_Addr2 AS [DelAddr2],
                o.Delivery_Addr3 AS [DelAddr3],
                o.Postal_Code AS [PostCode],
                o.Complete AS [Complete],
                o.Date_Captured AS [Captured],
                u.UserName AS [User],
        --        o.Slu_AW_Active_ID AS [OActive],
                                                    
                --Detail
        --        od.AP_Products_ID AS [],
                p.[Description] AS [Product],
                od.Lead_Time AS [LT],
                od.Order_Qty AS [Qty],
                od.Free_Qty AS [FreeQty],
                od.Back_Order_Qty AS [BOQty],
                od.Receipt_Date AS [ReceiveDate],
                od.Received_Qty AS [ReceiveQty],
                od.Unit_Price AS [UnitPrice],
        --        od.Trade_Discount_Formula_ID AS [],
                od.Trade_Discount_Amount AS [TDiscAmount],
                od.Trade_Discount_Percentage AS [TDiscPerc],
        --        od.Rebate_Formula_ID AS [],
                od.Rebate_Discount_Amount AS [RDiscAmount],
                od.Rebate_Discount_Percentage AS [RDiscPerc],
        --        od.Other_Discount_Formula_ID AS [],
                od.Other_Discount_Amount AS [ODiscAmount],
                od.Other_Discount_Percentage AS [ODiscPerc],
                od.Net_Amount AS [NetAmount],
        --        od.Sys_AW_Tax_Codes_ID AS [],
                od.Tax_Amount AS [TaxAmount],
                od.Total_Cost AS [TotalCost]
        --        od.Slu_AW_Active_ID AS [DActive]
        
            FROM AO_Orders o
                INNER JOIN AO_Order_Details od
                    ON o.AO_Orders_ID = od.AO_Orders_ID
                INNER JOIN AP_Products p
                    ON od.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN AO_Suppliers s
                    ON o.AO_Suppliers_ID = s.AO_Suppliers_ID
                LEFT JOIN AW_Remote_Access r
                    ON o.AW_Remote_Access_ID = r.AW_Remote_Access_ID
                LEFT JOIN Sys_AO_Delivery_Methods m
                    ON o.Sys_AO_Delivery_Methods_ID = m.Sys_AO_Delivery_Methods_ID
                LEFT JOIN dbo.AW_Users u
                    ON o.User_ID = u.AW_Users_ID
        
            WHERE o.AW_User_Companies_ID = @CompanyID AND
                  o.AO_Suppliers_ID = @SupplierID AND
                  o.Order_Date >= @FromDate AND
                  o.Order_Date <= @ToDate AND
                  o.Complete <> 1
            ORDER BY [CompanyID], [SupplierID], [RemoteID], [OrderID]
        END

    ELSE            --ALL Suppliers
        BEGIN
            SELECT
                o.AW_User_Companies_ID AS [CompanyID],
                o.AO_Suppliers_ID AS [SupplierID],
                o.AW_Remote_Access_ID AS [RemoteID],
                o.AO_Orders_ID AS [OrderID],
                ISNULL(s.Supplier_Name, '') AS [Supplier],
                ISNULL(r.NodeName, '') AS [Originator],
                ISNULL(o.Order_Number, '') AS [OrderNo],
                o.Order_Date AS [OrderDate], 
                o.Date_Ordered AS [DateOrdered], 
                ISNULL(o.Our_Ref, '') AS [OurRef],
        
                --Header
                o.Supplier_Rep AS [SupplierRep],
                o.Supplier_Type AS [SupplierType],
                o.Confirmation AS [Confirmed],
                o.Confirmation_Date AS [ConfirmDate],
                o.Supplier_Reference AS [SupplierRef],
                o.Invoice_Type AS [InvType],
                o.Invoice_Total AS [InvTotal],
                o.Admin_Fee AS [AdminFee],
                o.Trade_Discount_Total AS [TDiscTotal],
                o.Rebate_Discount_Total AS [RDiscTotal],
                o.Other_Discount_Total AS [ODiscTotal],
                o.Net_Amount AS [NetTotal],
                o.Tax_Total AS [TaxTotal],
                o.Order_Total AS [OrderTotal],
        --        o.Sys_AO_Delivery_Methods_ID,
                m.[Description] AS [DeliverMethod],
                o.Send_To_Address AS [SendToAddr],
                o.Delivery_Addr1 AS [DelAddr1],
                o.Delivery_Addr2 AS [DelAddr2],
                o.Delivery_Addr3 AS [DelAddr3],
                o.Postal_Code AS [PostCode],
                o.Complete AS [Complete],
                o.Date_Captured AS [Captured],
                u.UserName AS [User],
        --        o.Slu_AW_Active_ID AS [OActive],
                                                    
                --Detail
        --        od.AP_Products_ID AS [],
                p.[Description] AS [Product],
                od.Lead_Time AS [LT],
                od.Order_Qty AS [Qty],
                od.Free_Qty AS [FreeQty],
                od.Back_Order_Qty AS [BOQty],
                od.Receipt_Date AS [ReceiveDate],
                od.Received_Qty AS [ReceiveQty],
                od.Unit_Price AS [UnitPrice],
        --        od.Trade_Discount_Formula_ID AS [],
                od.Trade_Discount_Amount AS [TDiscAmount],
                od.Trade_Discount_Percentage AS [TDiscPerc],
        --        od.Rebate_Formula_ID AS [],
                od.Rebate_Discount_Amount AS [RDiscAmount],
                od.Rebate_Discount_Percentage AS [RDiscPerc],
        --        od.Other_Discount_Formula_ID AS [],
                od.Other_Discount_Amount AS [ODiscAmount],
                od.Other_Discount_Percentage AS [ODiscPerc],
                od.Net_Amount AS [NetAmount],
        --        od.Sys_AW_Tax_Codes_ID AS [],
                od.Tax_Amount AS [TaxAmount],
                od.Total_Cost AS [TotalCost]
        --        od.Slu_AW_Active_ID AS [DActive]
        
            FROM AO_Orders o
                INNER JOIN AO_Order_Details od
                    ON o.AO_Orders_ID = od.AO_Orders_ID
                INNER JOIN AP_Products p
                    ON od.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN AO_Suppliers s
                    ON o.AO_Suppliers_ID = s.AO_Suppliers_ID
                LEFT JOIN AW_Remote_Access r
                    ON o.AW_Remote_Access_ID = r.AW_Remote_Access_ID
                LEFT JOIN Sys_AO_Delivery_Methods m
                    ON o.Sys_AO_Delivery_Methods_ID = m.Sys_AO_Delivery_Methods_ID
                LEFT JOIN dbo.AW_Users u
                    ON o.User_ID = u.AW_Users_ID
        
            WHERE o.AW_User_Companies_ID = @CompanyID AND
                  o.Order_Date >= @FromDate AND
                  o.Order_Date <= @ToDate AND
                  o.Complete <> 1
            ORDER BY [CompanyID], [SupplierID], [RemoteID], [OrderID]
        END

SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










--exec sp_RPT_AO_Procurement_Manager 1, 1

-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Procurement_Manager
--Purpose       :Select Order Candidates Temp in Procurement Manager
--Date          :2003/10/01
--Authors       :TB
--Version       :1.0.0
--MODS          :02/10/03 - SET @Option = TAB in UI
--              :13/10/03 - Replaced Network_Identity_Number with AW_Remote_Access_ID
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AO_Procurement_Manager
    (
        @Option tinyint,
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @RemoteID int

--> Scan List
    IF @Option = 0
        BEGIN
            SELECT
                @CompanyID AS [CompanyID],
                a.AO_Order_Candidates_Temp_ID AS [ID],
                a.AP_Products_ID AS [ProductID],
                a.Order_Item AS [Order],
                b.Supplier_Name AS [Supplier],
                d.NodeName AS [Originator],
                a.Product_Description AS [Product],
                a.Product_Code as [Code],
                a.On_Hand AS [On Hand],
                a.Order_Qty AS [To Order],

                a.Selling AS [Selling],
                a.Trade_Discount AS [Disc %],
                a.Cost AS [Cost],
                a.Last_Cost AS [Last Cost],
                a.Total_Cost AS [Total Cost],

                a.Min_Stock_Level AS [MSL],
                a.Min_Order_Qty AS [Min],
                a.Max_Order_Qty AS [Max],
                a.Service_Level AS [SL],

                a.Notes AS [Notes],
                CONVERT(CHAR(10), a.Date_Captured, 121) AS [Captured],
                c.UserName AS [User]
            FROM AO_Order_Candidates_Temp a
                LEFT JOIN AO_Suppliers b
                    ON a.AO_Suppliers_ID = b.AO_Suppliers_ID
                LEFT JOIN AW_Users c
                    ON a.[User_ID] = c.AW_Users_ID
                LEFT JOIN AW_Remote_Access d
                    ON a.AW_Remote_Access_ID = d.AW_Remote_Access_ID
            WHERE a.AW_User_Companies_ID = @CompanyID
            ORDER BY [Supplier], [Originator], [Product]
        END

--> Shopping List
    ELSE
    IF @Option = 1
        BEGIN
            SELECT
                @CompanyID AS [CompanyID],
                b.AO_Order_Candidates_ID AS [ID],
                a.AP_Products_ID as [ProductID],
                b.Ready AS [Order],
                c.Supplier_Name AS [Supplier],
                f.NodeName AS [Originator],
                a.[Description] as [Product],
                a.Product_Code as [Code],
                ISNULL(a.On_Hand, 0) as [On Hand],
                b.Qty as [To Order],

                ISNULL(a.Price1_Price1, 0) AS [Selling],
                ISNULL(d.Trade_Disc_Perc, 0) AS [Disc %],
                ISNULL(b.Last_Cost, 0) AS [Cost],
                ISNULL(b.Last_Cost, 0) AS [Last Cost],
                ROUND(ISNULL(b.Qty, 0) * ISNULL(b.Last_Cost, 0), 2)  AS [Total Cost],

                ISNULL(a.Min_Stock_Level, 0) AS [MSL],
                ISNULL(a.Min_Order_Qty, 0) as [Min],
                ISNULL(a.Max_Order_Qty, 0) as [Max],
                a.Service_Level AS [SL],

                b.Notes AS [Notes],
                CONVERT(CHAR(10), b.Date_Captured, 121) AS [Captured],
                e.UserName AS [User]
            FROM AP_Products a
                INNER JOIN AO_Order_Candidates b
                    ON a.AP_Products_ID = b.AP_Products_ID
                LEFT JOIN AO_Suppliers c
                    ON b.AO_Suppliers_ID = c.AO_Suppliers_ID
                INNER JOIN AP_Products_Suppliers d
                    ON d.AP_Products_ID = b.AP_Products_ID AND
                       d.AO_Suppliers_ID = b.AO_Suppliers_ID
                LEFT JOIN AW_Users e
                    ON b.[User_ID] = e.AW_Users_ID
                LEFT JOIN AW_Remote_Access f
                    ON b.AW_Remote_Access_ID = f.AW_Remote_Access_ID
            WHERE b.AW_User_Companies_ID = @CompanyID
        --    ORDER BY [Supplier], [Description]
            ORDER BY c.Supplier_Name, a.[Description]
        END



SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Product_Purchase_Price_Variance
--Purpose       :Retrieves Purchase Price Variance by Supplier by Product
--Date          :2007/05/16
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AO_Product_Purchase_Price_Variance
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @ToMonthID tinyint,
    	@ToYearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

        DECLARE @StartPeriod varchar(6),
                @EndPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)


    SELECT
        t.AW_User_Companies_ID AS [CompanyID],
        t.AO_Suppliers_ID AS [SupplierID], 
        pd.Lup_AP_Product_Departments_ID AS [DeptID],
        ISNULL(pd.[Description], '') AS [DeptName],
        ISNULL(s.Supplier_Name, '') AS [Supplier],
        CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date], 

        ISNULL(t.Document_Number, '') AS [Ref No],
        ISNULL(tt.Type_Code, '') AS [Type], 
        ISNULL(gl.[Description], '') AS [GL Account],

        t.Slu_AW_Months_ID AS [Month],
        t.Slu_AW_Years_ID AS [Year],

        ISNULL(p.[Description], '') AS [Product],
        ISNULL(t.AO_GRV_ID, 0) AS [GRV],
        ISNULL(gd.Qty, 0) AS [Qty],
        ISNULL(gd.Unit_Price, 0) AS [Unit Price],
        ISNULL((gd.Unit_Price * gd.Qty), 0) AS [UnitAmount],

        ISNULL(p.Standard_Cost, 0) AS [StdCost],
        ISNULL(p.Standard_Disc1, 0) AS [StdDisc1],
        ISNULL(p.Standard_Disc2, 0) AS [StdDisc2],
        ISNULL((p.Standard_Cost * gd.Qty), 0) AS [UnitStd],

        ISNULL((gd.Unit_Price * gd.Qty), 0) - ISNULL((p.Standard_Cost * gd.Qty), 0) AS [StdVariance],

        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Last_Cost
            ) as [LastGP%],
        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Average_Cost
            ) as [AvgGP%],
        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Standard_Cost
            ) as [StdGP%]

    FROM AO_Transactions t
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
        LEFT OUTER JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AB_Accounts gl
            ON t.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN AO_GRV gh
            ON t.AO_GRV_ID = gh.AO_GRV_ID
        INNER JOIN AO_GRV_Details gd
            On gh.AO_GRV_ID = gd.AO_GRV_ID
        INNER JOIN AP_Products p
            ON gd.AP_Products_ID = p.AP_Products_ID
        INNER JOIN Lup_AP_Product_Departments pd
            ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID

    WHERE t.AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
    ORDER BY [Supplier], [SupplierID], [Product], [Date]


SET NOCOUNT OFF

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Product_Purchases
--Purpose       :Retrieves Supplier Purchases by Product
--Date          :2005/05/24
--Authors       :TB
--MODS          :10/06/05 - Replaced Discount AMOUNTS with Discount PERCENTAGES
--2004.4.0      :28/08/08 - Changes ORDER BY from [Supplier], [SupplierID], [Product]
--              :                              to [Product], [Supplier], [SupplierID]
--V6.0	RL	2014-05-09	:Added Document date and Supplier search options
--V6.2	RL	2016-07-01	:Excluded consignment GRV's
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AO_Product_Purchases]
    (
        @Option tinyint,
        @ChkPeriod int,
        @MonthID tinyint,
    	@YearID int,
        @ToMonthID tinyint,
    	@ToYearID int,
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @ChkAllSuppliers int,
		@SupplierID int              
    )

AS

SET NOCOUNT ON

	DECLARE @StartPeriod varchar(6),
			@EndPeriod varchar(6),
			@sql varchar(7000)

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)

    SET @sql = ' SELECT '

	SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
	SET @sql = @sql + ' p.AP_Products_ID AS [ProductID], '
	SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
	SET @sql = @sql + ' pd.Lup_AP_Product_Departments_ID AS [DeptID], '
	SET @sql = @sql + ' ISNULL(pd.[Description], '''') AS [DeptName], '
	SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier], '
	SET @sql = @sql + ' ISNULL(t.Document_Date, '''') AS [Date], '
	SET @sql = @sql + ' ISNULL(t.Document_Number, '''') AS [Ref No], '
	SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [Type], '
	SET @sql = @sql + ' ISNULL(gl.[Description], '''') AS [GL Account], '

	SET @sql = @sql + ' t.Slu_AW_Months_ID AS [Month], '
	SET @sql = @sql + ' t.Slu_AW_Years_ID AS [Year], '

	SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product], '
	SET @sql = @sql + ' ISNULL(t.AO_GRV_ID, 0) AS [GRV], '
	SET @sql = @sql + ' ISNULL(gd.Qty, 0) AS [Qty], '
	SET @sql = @sql + ' ISNULL(gd.Unit_Price, 0) AS [Unit Price], '

	SET @sql = @sql + ' ISNULL((gd.Unit_Price * gd.Qty), 0) AS [UnitAmount], '

	SET @sql = @sql + ' ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade], '
	SET @sql = @sql + ' ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate], '
	SET @sql = @sql + ' ISNULL(gd.Other_Discount_Amount, 0) AS [Other], '

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0 '
	SET @sql = @sql + '		THEN ROUND((gd.Trade_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2) '
	SET @sql = @sql + '		ELSE 0.00 '
	SET @sql = @sql + '		END AS [Trade%], '

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0 '
	SET @sql = @sql + '		THEN ROUND((gd.Rebate_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2) '
	SET @sql = @sql + '		ELSE 0.00 '
	SET @sql = @sql + '		END AS [Rebate%], '

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0 '
	SET @sql = @sql + '		THEN ROUND((gd.Other_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2) '
	SET @sql = @sql + '		ELSE 0.00 '
	SET @sql = @sql + '		END AS [Other%], '

	SET @sql = @sql + ' ISNULL(gd.Net_Amount, 0) AS [Sub-Total], '
	SET @sql = @sql + ' ISNULL(gd.Tax_Amount, 0) AS [Tax], '
	SET @sql = @sql + ' ISNULL(gd.Total_Cost, 0) AS [Total], '

	SET @sql = @sql + ' dbo.GetGrossMargin '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		p.Price1_Effective_Date, '
	SET @sql = @sql + '		p.Price1_Price1, '
	SET @sql = @sql + '		p.Price2_Effective_Date, '
	SET @sql = @sql + '		p.Price2_Price1, '
	SET @sql = @sql + '		getdate(), '
	SET @sql = @sql + '		p.Last_Cost '
	SET @sql = @sql + ' ) as [LastGP%], '
	SET @sql = @sql + ' dbo.GetGrossMargin '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		p.Price1_Effective_Date, '
	SET @sql = @sql + '		p.Price1_Price1, '
	SET @sql = @sql + '		p.Price2_Effective_Date, '
	SET @sql = @sql + '		p.Price2_Price1, '
	SET @sql = @sql + '		getdate(), '
	SET @sql = @sql + '		p.Average_Cost '
	SET @sql = @sql + ' ) as [AvgGP%], '
	SET @sql = @sql + ' dbo.GetGrossMargin '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		p.Price1_Effective_Date, '
	SET @sql = @sql + '		p.Price1_Price1, '
	SET @sql = @sql + '		p.Price2_Effective_Date, '
	SET @sql = @sql + ' p.Price2_Price1, '
	SET @sql = @sql + '		getdate(), '
	SET @sql = @sql + '		p.Standard_Cost '
	SET @sql = @sql + ' ) as [StdGP%] '

	SET @sql = @sql + ' FROM AO_Transactions t '
	SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
	SET @sql = @sql + '		ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
	SET @sql = @sql + ' LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
	SET @sql = @sql + '		ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + '	LEFT JOIN AB_Accounts gl '
	SET @sql = @sql + '		ON t.AB_Accounts_ID = gl.AB_Accounts_ID '
	SET @sql = @sql + ' INNER JOIN AO_GRV gh '
	SET @sql = @sql + '		ON t.AO_GRV_ID = gh.AO_GRV_ID '
	SET @sql = @sql + ' INNER JOIN AO_GRV_Details gd '
	SET @sql = @sql + '		On gh.AO_GRV_ID = gd.AO_GRV_ID '
	SET @sql = @sql + ' INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON gd.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + ' INNER JOIN Lup_AP_Product_Departments pd '
	SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '

	SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ''
	
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 31'		--Consignment Goods Received
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 32'		--Consignment Goods Returned
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 34'		--Consignment Sold

	IF @ChkPeriod = 1        --Accounting Period
	BEGIN
		SET @sql = @sql + ' AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) BETWEEN ' + @StartPeriod + ' AND ' + @EndPeriod + ''
    END      
          	      
	IF @ChkDates = 1               --From/To Dates
	BEGIN
		SET @sql = @sql + '  AND t.Document_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
		SET @sql = @sql + '  AND t.Document_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    END      
          
	IF @ChkAllSuppliers = 0        --Single Supplier Account
	BEGIN
		SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' '
    END      
          
         
--    ORDER BY [Supplier], [SupplierID], [Product], [Date]
	SET @sql = @sql + '     ORDER BY [Product], [Supplier], [ProductID], [Date] '

	EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Product_Suppliers
--Purpose       :Retrieves Product Purchases by Supplier
--Date          :2005/05/24
--Authors       :TB
--MODS          :10/06/05 - Replaced Discount AMOUNTS with Discount PERCENTAGES
--2004.4.0      :28/08/08 - Changes ORDER BY from [Product], [Supplier]
--              :                                 [Supplier], [Product]
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AO_Product_Suppliers
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @ToMonthID tinyint,
    	@ToYearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

        DECLARE @StartPeriod varchar(6),
                @EndPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)


    SELECT
        t.AW_User_Companies_ID AS [CompanyID],
        t.AO_Suppliers_ID AS [SupplierID], 
        pd.Lup_AP_Product_Departments_ID AS [DeptID],
        ISNULL(pd.[Description], '') AS [DeptName],
        ISNULL(s.Supplier_Name, '') AS [Supplier],
        ISNULL(t.Document_Date, '') AS [Date], 
        ISNULL(t.Document_Number, '') AS [Ref No],
        ISNULL(tt.Type_Code, '') AS [Type], 
        ISNULL(gl.[Description], '') AS [GL Account],

        t.Slu_AW_Months_ID AS [Month],
        t.Slu_AW_Years_ID AS [Year],

        ISNULL(p.[Description], '') AS [Product],
        ISNULL(t.AO_GRV_ID, 0) AS [GRV],
        ISNULL(gd.Qty, 0) AS [Qty],
        ISNULL(gd.Unit_Price, 0) AS [Unit Price],

        ISNULL((gd.Unit_Price * gd.Qty), 0) AS [UnitAmount],

        ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade],
        ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate],
        ISNULL(gd.Other_Discount_Amount, 0) AS [Other],

        CASE WHEN (gd.Unit_Price * gd.Qty) <> 0
             THEN ROUND((gd.Trade_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)
             ELSE 0.00
             END AS [Trade%],

        CASE WHEN (gd.Unit_Price * gd.Qty) <> 0
             THEN ROUND((gd.Rebate_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)
             ELSE 0.00
             END AS [Rebate%],

        CASE WHEN (gd.Unit_Price * gd.Qty) <> 0
             THEN ROUND((gd.Other_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)
             ELSE 0.00
             END AS [Other%],

        ISNULL(gd.Net_Amount, 0) AS [Sub-Total],
        ISNULL(gd.Tax_Amount, 0) AS [Tax],
        ISNULL(gd.Total_Cost, 0) AS [Total],

        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Last_Cost
            ) as [LastGP%],
        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Average_Cost
            ) as [AvgGP%],
        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Standard_Cost
            ) as [StdGP%]

    FROM AO_Transactions t
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
        LEFT OUTER JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AB_Accounts gl
            ON t.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN AO_GRV gh
            ON t.AO_GRV_ID = gh.AO_GRV_ID
        INNER JOIN AO_GRV_Details gd
            On gh.AO_GRV_ID = gd.AO_GRV_ID
        INNER JOIN AP_Products p
            ON gd.AP_Products_ID = p.AP_Products_ID
        INNER JOIN Lup_AP_Product_Departments pd
            ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID

    WHERE t.AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) BETWEEN @StartPeriod AND @EndPeriod
--    ORDER BY [Product], [Supplier], [SupplierID], [Date]
    ORDER BY [Supplier], [Product], [SupplierID], [Date]


SET NOCOUNT OFF

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR1
--Purpose       :Supplier Purchase JNL Transactions by GL Allocations
--Date          :2007/04/20
--Authors       :TB
--MODS          :02/12/04 - Added Sort Order
--              :15/01/05 - Removed the JOIN to the GL Transactions. This is
--              :           now taken care of in the Subreport showing the splits
--2004.3.8      :27/04/08 - Added delinquent transactions from AO_Transactions_Log
--              :           using new input parameter @TranLog
--              :27/04/08 - Added User Name
--              :30/04/08 - Added Supplier Journals and Payments to Transaction Log
------------------------------------------------------------------------------

CREATE                      PROCEDURE sp_RPT_AO_Purchases_Journal_CR1
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @SortOrder tinyint,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID],  '
    SET @sql = @sql + ' s.Supplier_Name AS [SupplierName], '

    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') +
                                 '' ('' + ISNULL(s.Supplier_Number, '''') + '')'' +
                                 '' ('' + CONVERT(VARCHAR(10), s.AO_Suppliers_ID) + '') '' +
                                 ISNULL(s.Post_Box, '''') + '', '' +
                                 + ISNULL(s.Post_Office, '''') + '', '' +
                                 + ISNULL(s.Post_Code, '''')
                              AS [SupplierFull], '

    SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date],  '
    SET @sql = @sql + ' tt.Type_Code AS [Type],  '
    SET @sql = @sql + ' t.Supplier_Reference AS [Ref No],  '
    SET @sql = @sql + ' t.Document_Number AS [Doc No],  '

    SET @sql = @sql + ' CASE WHEN t.AO_GRV_ID > 0 '
    SET @sql = @sql + '      THEN t.AO_GRV_ID '
    SET @sql = @sql + '      ELSE 0 '
    SET @sql = @sql + ' END AS [GRV],  '

    SET @sql = @sql + ' t.Comment AS [Notes],  '
    SET @sql = @sql + ' t.Net_Amount AS [Net], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [VAT], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), t.Date_Captured, 121)) AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions_Log l '
            SET @sql = @sql + ' INNER JOIN AO_Transactions t '
            SET @sql = @sql + '     ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions t '
        END


    SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '     ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + ' LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '     ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + '     ON t.User_ID = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + '    (t.Sys_AW_Transaction_Types_ID = 8 OR '
            SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 9 OR '
            SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 10 OR '
            SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 12) AND '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '    (t.Sys_AW_Transaction_Types_ID = 8 OR '
            SET @sql = @sql + '     t.Sys_AW_Transaction_Types_ID = 9) AND '
        END


    SET @sql = @sql + '     t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '     t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
        END
    ELSE
    IF @Option = 2    --GRV transaction only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
        END


    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [SupplierFull], t.Document_Number '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [SupplierFull], t.Document_Date '
        END



    EXEC (@sql)


SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR1_GRV
--Purpose       :Supplier Purchase JNL Transactions by GL Splits
--Date          :2007/04/20
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Purchases_Journal_CR1_GRV
    (
    	@GRVID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     gd.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.[Description] AS [Product], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     pc.[Description] AS [PurchCat], '
    SET @sql = @sql + '     gd.Qty AS [Qty], '
    SET @sql = @sql + '     gd.Unit_Price AS [UnitPrice], '
    SET @sql = @sql + '     gd.Net_Amount AS [Net], '
    SET @sql = @sql + '     gd.Tax_Amount AS [Tax], '
    SET @sql = @sql + '     gd.Total_Cost AS [Total] '

    SET @sql = @sql + '     FROM AO_GRV_Details gd '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE gd.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           gd.AO_GRV_ID = ' + CONVERT(varchar(10), @GRVID) + ' '



    EXEC (@sql)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Summary
--Purpose       :Purchase JNL CR1 Total Purchase Category Summary
--Date          :2007/04/22
--Authors       :TB
--MODS          :
--2004.3.8      :27/04/08 - Added delinquent transactions from AO_Transactions_Log
--              :           using new input parameter @TranLog
------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Summary
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     MAX(s.Supplier_Name) AS [Supplier], '
    SET @sql = @sql + '     p.Lup_AP_Purchase_Categories_ID AS [PurchCatID], '
    SET @sql = @sql + '     MAX(pc.[Description]) AS [PurchCat], '
    SET @sql = @sql + '     SUM(gd.Qty) AS [Qty], '
    SET @sql = @sql + '     SUM(gd.Net_Amount) AS [Net], '
    SET @sql = @sql + '     SUM(gd.Tax_Amount) AS [Tax], '
    SET @sql = @sql + '     SUM(gd.Total_Cost) AS [Total] '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions_Log l '
            SET @sql = @sql + '     INNER JOIN AO_Transactions t '
            SET @sql = @sql + '         ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions t '
        END


    SET @sql = @sql + '         LEFT JOIN AO_GRV gh '
    SET @sql = @sql + '             ON t.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN  AO_GRV_Details gd '
    SET @sql = @sql + '             ON gh.AO_GRV_ID = gd.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '             ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           t.AO_GRV_ID <> 0 AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND ' 
    SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 8 OR '
    SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 9) '

    SET @sql = @sql + '     GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID, p.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     ORDER BY [Supplier], [PurchCat] '



    EXEC (@sql)


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Supplier
--Purpose       :Supplier Purchase JNL CR1 SupplierPurchase Category Summary
--Date          :2007/04/22
--Authors       :TB
--MODS          :
--2004.3.8      :27/04/08 - Added delinquent transactions from AO_Transactions_Log
--              :           using new input parameter @TranLog
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AO_Purchases_Journal_CR1_PurchCat_Supplier
    (
        @SupplierID int,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     p.Lup_AP_Purchase_Categories_ID AS [PurchCatID], '
    SET @sql = @sql + '     MAX(pc.[Description]) AS [PurchCat], '
    SET @sql = @sql + '     SUM(gd.Net_Amount) AS [Net], '
    SET @sql = @sql + '     SUM(gd.Tax_Amount) AS [Tax], '
    SET @sql = @sql + '     SUM(gd.Total_Cost) AS [Total] '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions_Log l '
            SET @sql = @sql + '     INNER JOIN AO_Transactions t '
            SET @sql = @sql + '         ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' FROM AO_Transactions t '
        END


    SET @sql = @sql + '         LEFT JOIN AO_GRV gh '
    SET @sql = @sql + '             ON t.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN  AO_GRV_Details gd '
    SET @sql = @sql + '             ON gh.AO_GRV_ID = gd.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           t.AO_GRV_ID <> 0 AND '
    SET @sql = @sql + '           t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND '
    SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 8 OR '
    SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 9) '

    SET @sql = @sql + '     GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID, p.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     ORDER BY [PurchCat] '

    EXEC (@sql)


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR1_Splits
--Purpose       :Supplier Purchase JNL Transactions by GL Splits
--Date          :2007/04/20
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Purchases_Journal_CR1_Splits
    (
    	@TranID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gl.[Description] AS [GL Account], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '

    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           gt.AB_Transaction_Ref = ' + CONVERT(varchar(10), @TranID) + ' '



    EXEC (@sql)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR1_Summary
--Purpose       :Supplier Purchase JNL Transactions by GL Allocations Summary
--Date          :2007/04/20
--Authors       :TB
--MODS          :
--2004.3.8      :27/04/08 - Added delinquent transactions from AO_Transactions_Log
--              :           using new input parameter @TranLog
--              :30/04/08 - Added Supplier Journals and Payments to Transaction Log
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AO_Purchases_Journal_CR1_Summary
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @TranLog tinyint
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gl.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     SUM(gt.AB_Transaction_Amount) AS [GLTranAmount], '
    SET @sql = @sql + '     MAX(gl.[Description]) AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + ' INNER JOIN AO_Transactions_Log l '
            SET @sql = @sql + '     ON gt.AB_Transaction_Ref = l.AO_Transactions_ID '
            SET @sql = @sql + ' INNER JOIN AO_Transactions t '
            SET @sql = @sql + '     ON t.AO_Transactions_ID = l.AO_Transactions_ID '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' INNER JOIN AO_Transactions t '
            SET @sql = @sql + '     ON gt.AB_Transaction_Ref = t.AO_Transactions_ID '
        END


    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '         t.AO_Transactions_ID = gt.AB_Transaction_Ref AND '


    IF @TranLog = 1
        BEGIN
            SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 5 OR '
            SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 6 OR '
            SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 7 OR '
            SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 8) AND '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 5 OR '
            SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 6) AND '
        END


    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '

    IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
        END
    ELSE
    IF @Option = 2    --GRV transaction only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
        END

    SET @sql = @sql + '     GROUP BY gt.AW_User_Companies_ID, gl.AB_Accounts_ID '
    SET @sql = @sql + '     ORDER BY MAX(gl.[Description]) '


    EXEC (@sql)


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_CR3
--Purpose       :Purchase JNL CR3 Total Purchase Category Summary
--Date          :2007/04/25
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AO_Purchases_Journal_CR3
    (
--        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     MAX(s.Supplier_Name) AS [Supplier], '
    SET @sql = @sql + '     p.Lup_AP_Purchase_Categories_ID AS [PurchCatID], '
    SET @sql = @sql + '     MAX(pc.[Description]) AS [PurchCat], '
    SET @sql = @sql + '     SUM(gd.Qty) AS [Qty], '
    SET @sql = @sql + '     SUM(gd.Net_Amount) AS [Net], '
    SET @sql = @sql + '     SUM(gd.Tax_Amount) AS [Tax], '
    SET @sql = @sql + '     SUM(gd.Total_Cost) AS [Total] '

    SET @sql = @sql + '     FROM AO_Transactions t '
    SET @sql = @sql + '         LEFT JOIN AO_GRV gh '
    SET @sql = @sql + '             ON t.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN  AO_GRV_Details gd '
    SET @sql = @sql + '             ON gh.AO_GRV_ID = gd.AO_GRV_ID '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON gd.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '             ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '         LEFT JOIN Lup_AP_Purchase_Categories pc'
    SET @sql = @sql + '             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           t.AO_GRV_ID <> 0 AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' AND ' 
    SET @sql = @sql + '          (t.Sys_AW_Transaction_Types_ID = 8 OR '
    SET @sql = @sql + '           t.Sys_AW_Transaction_Types_ID = 9) '


--     IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
--         BEGIN
--             SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
--         END
--     ELSE
--     IF @Option = 2    --GRV transaction only
--         BEGIN
--             SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
--         END


    SET @sql = @sql + '     GROUP BY t.AW_User_Companies_ID, t.AO_Suppliers_ID, p.Lup_AP_Purchase_Categories_ID '

    SET @sql = @sql + '     ORDER BY [Supplier], [PurchCat] '



    EXEC (@sql)


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_Non_GRV
--Purpose       :Supplier Purchase JNL Transactions by GL Allocations
--Date          :2004/10/15
--Authors       :TB
--MODS          :02/12/04 - Added Sort Order
--              :15/01/05 - Removed the JOIN to the GL Transactions. This is
--              :           now taken care of in the Subreport showing the splits
--2004.3.8      :04/03/08 - Added Date_Captured as [TranDate] to narrow splits select 
------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_RPT_AO_Purchases_Journal_Non_GRV
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @SortOrder tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID],  '
    SET @sql = @sql + '     s.Supplier_Name AS [SupplierName], '

    SET @sql = @sql + '     ISNULL(s.Supplier_Name, '''') +
                             '' ('' + ISNULL(s.Supplier_Number, '''') + '')'' +
                             '' ('' + CONVERT(VARCHAR(10), s.AO_Suppliers_ID) + '') '' +
                             ISNULL(s.Post_Box, '''') + '', '' +
                             + ISNULL(s.Post_Office, '''') + '', '' +
                             + ISNULL(s.Post_Code, '''')
                              AS [SupplierFull], '



    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date],  '
    SET @sql = @sql + '     tt.Type_Code AS [Type],  '
    SET @sql = @sql + '     t.Supplier_Reference AS [Ref No],  '
    SET @sql = @sql + '     t.Document_Number AS [Doc No],  '

    SET @sql = @sql + '     CASE WHEN t.AO_GRV_ID > 0 '
    SET @sql = @sql + '          THEN t.AO_GRV_ID '
    SET @sql = @sql + '          ELSE NULL '
    SET @sql = @sql + '          END AS [GRV],  '

    SET @sql = @sql + '     t.Comment AS [Notes],  '
    SET @sql = @sql + '     t.Net_Amount AS [Net], '
    SET @sql = @sql + '     t.Total_Tax_Amount AS [VAT], '
    SET @sql = @sql + '     t.Total_Amount AS [Total], '
    SET @sql = @sql + '     t.Settlement_Discount AS [SettleDisc], '
    SET @sql = @sql + '     t.Payment_Amount AS [Payment],  '
    SET @sql = @sql + '     t.To_Be_Paid AS [PayBool], '
    SET @sql = @sql + '     t.To_Be_Paid_Amount AS [ToBePaid], '
    SET @sql = @sql + '     t.Remittance_Balance AS [RemitBalance], '
    SET @sql = @sql + '     t.Date_Captured AS [TranDate] '

    SET @sql = @sql + '     FROM AO_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '         ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '     WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '        (t.Sys_AW_Transaction_Types_ID = 8 OR '
    SET @sql = @sql + '         t.Sys_AW_Transaction_Types_ID = 9) AND '
    SET @sql = @sql + '         t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
        END
    ELSE
    IF @Option = 2    --GRV transaction only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
        END


    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [SupplierFull], t.Document_Number '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [SupplierFull], t.Document_Date '
        END



    EXEC (@sql)


SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_Non_GRV_Splits
--Purpose       :Supplier Purchase JNL Transactions by GL Splits
--Date          :2005/01/15
--Authors       :TB
--MODS          :
--2004.3.8      :04/03/08 - Added Date_Captured as @TranDate to narrow splits select 
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Purchases_Journal_Non_GRV_Splits
    (
    	@TranID int,
        @TranDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gl.[Description] AS [GL Account], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '

    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           gt.AB_Transaction_Ref = ' + CONVERT(varchar(10), @TranID) + ' AND '
    SET @sql = @sql + '           CONVERT(CHAR(19), gt.Date_Captured) = ' + '''' + CONVERT(CHAR(19), @TranDate) + ''''



    EXEC (@sql)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Purchases_Journal_Non_GRV_Summary
--Purpose       :Supplier Purchase JNL Transactions by GL Allocations Summary
--Date          :2004/10/15
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Purchases_Journal_Non_GRV_Summary
    (
        @Option tinyint,
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gl.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     SUM(gt.AB_Transaction_Amount) AS [GLTranAmount], '
    SET @sql = @sql + '     MAX(gl.[Description]) AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     INNER JOIN AO_Transactions t '
    SET @sql = @sql + '         ON gt.AB_Transaction_Ref = t.AO_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '         t.AO_Transactions_ID = gt.AB_Transaction_Ref AND '
    SET @sql = @sql + '        (gt.Sys_AB_Transaction_Types_ID = 5 OR '
    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 6) AND '
    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '

    IF @Option = 1    --Non-Grv and Multi-Spilt transactions only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) = 0 '
        END
    ELSE
    IF @Option = 2    --GRV transaction only
        BEGIN
            SET @sql = @sql + '  AND ISNULL(t.AO_GRV_ID, 0) <> 0 '
        END

    SET @sql = @sql + '     GROUP BY gt.AW_User_Companies_ID, gl.AB_Accounts_ID '
    SET @sql = @sql + '     ORDER BY MAX(gl.[Description]) '


    EXEC (@sql)


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Remittance_Ageing
--Purpose       :Extract Supplier Remittance for ONE Supplier
--Date          :2003/12/25
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AO_Remittance_Ageing
	(
        @SupplierID int,
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int,
        @AgeTotal money OUTPUT,
        @Age0 money OUTPUT,
        @Age30 money OUTPUT,
        @Age60 money OUTPUT,
        @Age90 money OUTPUT,
        @Age120 money OUTPUT,
        @Age150 money OUTPUT,
        @Age180 money OUTPUT
	)

AS

    SET NOCOUNT ON

    DECLARE @Period varchar(6),
            @Period1 varchar(6),
            @Period2 varchar(6),
            @Period3 varchar(6),
            @Period4 varchar(6),
            @Period5 varchar(6),
            @Period6 varchar(6),
            @Period7 varchar(6),
            @Balance money

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
    SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@M2, @Y2)
    SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@M3, @Y3)
    SET @Period4 = dbo.fn_AB_Get_Ending_GL_Period(@M4, @Y4)
    SET @Period5 = dbo.fn_AB_Get_Ending_GL_Period(@M5, @Y5)
    SET @Period6 = dbo.fn_AB_Get_Ending_GL_Period(@M6, @Y6)
    SET @Period7 = dbo.fn_AB_Get_Ending_GL_Period(@M7, @Y7)

    SET @AgeTotal = 0
    SET @Age0 = 0
    SET @Age30 = 0
    SET @Age60 = 0
    SET @Age90 = 0
    SET @Age120 = 0
    SET @Age150 = 0
    SET @Age180 = 0

    DECLARE @AO_Ageing table
        (
            AO_Suppliers_ID int,
            [Period] varchar(6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
            [Balance] money
        )

--> selects OUTSTANDING AGEING TOTALS
    INSERT INTO @AO_Ageing
        (
            AO_Suppliers_ID,
            Period,
            Balance
        )
	SELECT
        AO_Suppliers_ID AS [SupplierID],
        MAX(dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(Slu_AW_Years_ID))) AS [Period],
        SUM(Total_Amount) + SUM(Payment_Amount) AS [Balance]
    FROM AO_Transactions
    WHERE AO_Suppliers_ID = @SupplierID AND
          ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
          dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(Slu_AW_Years_ID)) <= @Period1
    GROUP BY AO_Suppliers_ID, dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(Slu_AW_Years_ID))
    ORDER BY [Period] DESC


	DECLARE Supplier_Temp_Cursor CURSOR FOR
        (
            SELECT
                Period,
                ISNULL(Balance, 0)
            FROM @AO_Ageing
        )

    OPEN Supplier_Temp_Cursor

    	FETCH NEXT FROM Supplier_Temp_Cursor 
    	INTO
            @Period,
            @Balance
    	
    	WHILE @@FETCH_STATUS = 0
    	BEGIN
            BEGIN
                IF @Period1 = @Period
                    BEGIN
                        SET @Age0 = @Balance
                    END
                ELSE
                IF @Period2 = @Period
                    BEGIN
                         SET @Age30 = @Balance
                    END
                ELSE
                IF @Period3 = @Period
                    BEGIN
                         SET @Age60 = @Balance
                    END
                ELSE
                IF @Period4 = @Period
                    BEGIN
                         SET @Age90 = @Balance
                    END
                ELSE
                IF @Period5 = @Period
                    BEGIN
                         SET @Age120 = @Balance
                    END
                ELSE
                IF @Period6 = @Period
                    BEGIN
                         SET @Age150 = @Balance
                    END
                ELSE
                    BEGIN
                        SET @Age180 = @Age180 + @Balance
                    END
            END


        	FETCH NEXT FROM Supplier_Temp_Cursor 
        	INTO
                @Period,
                @Balance

    	END
	
	CLOSE Supplier_Temp_Cursor
	DEALLOCATE Supplier_Temp_Cursor

    SET @AgeTotal = ISNULL(@Age0, 0) +
                    ISNULL(@Age30, 0) +
                    ISNULL(@Age60, 0) +
                    ISNULL(@Age90, 0) +
                    ISNULL(@Age120, 0) +
                    ISNULL(@Age150, 0) +
                    ISNULL(@Age180, 0)


SET NOCOUNT ON






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












--EXEC sp_RPT_AO_Remittance_Transactions '2003/12/25 11:59:59 PM', 1, 20, 0, 10, 2003, 9, 2003, 8, 2003, 7, 2003, 6, 2003, 5, 2003, 4, 2003

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Remittance_Transactions
--Purpose       :Extract Supplier Remittance for ONE Supplier
--Date          :2003/12/25
--Authors       :TB
--Version       :1.0.0
--MODS          :24/07/04 - Added [Month] and [Year] fields - Autowiel
--2004.3.4      :07/03/07 - Changed @ToBePaid input parameter datatype from
--              :           bit to tinyint
--2004.5.0      :11/03/11 - Formatted [Document Date] field
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AO_Remittance_Transactions
	(
        @SupplierID int,
        @ToBePaid tinyint,
    	@MonthID tinyint,
    	@YearID int
    )

AS

SET NOCOUNT ON

    DECLARE @Period varchar(6)

    SET @Period = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    IF @ToBePaid = 1    --1 = Print only flagged To_Be_Paid transactions
        BEGIN
    		SELECT
                t.AO_Suppliers_ID AS [SupplierID],
                t.AO_Transactions_ID as [ID], 
                s.Supplier_Name AS [Supplier],
                s.Supplier_Number AS [Supplier No],
            	s.Credit_Limit AS [Credit Limit],
            	ct.[Description] AS [Terms Type],
            	s.Default_Settlement_Discount AS [Default Settlement %],
            	s.Supplier_Contact AS [Contact],
               	s.Supplier_Telephone AS [TelNo],
            	s.Contact_Cellphone AS [CellNo],
            	s.Supplier_Fax AS [FaxNo],
                s.Post_Box AS [Post Box],
                s.Post_Office AS [Post Office],
                s.Post_Code AS [Post Code],
                s.Email_Address AS [Email],
                s.Tax_Number AS [Tax No],
                tt.[Description] AS [Type],
                t.Document_Number AS [Document No],
                CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Document Date], 
                t.Slu_AW_Months_ID AS [MonthID],
                t.Slu_AW_Years_ID AS [YearID],
                dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(t.Slu_AW_Years_ID)) AS [Period],
                ISNULL(t.Total_Amount, 0) AS [Amount],
                ISNULL(t.Payment_Amount, 0) AS [Payment],
                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Owing],
                t.Settlement_Discount AS [Settlement],
                t.To_Be_Paid AS [Pay],
                ISNULL(t.To_Be_Paid_Amount, 0) - ISNULL(t.Settlement_Discount, 0) AS [Pay Amount],
                t.Remittance_Balance AS [Balance],
                t.Date_Captured,
                t.[User_ID],
                m.[Description] AS [Month],
                y.[Description] AS [Year]
            FROM AO_Transactions t
                INNER JOIN AO_Suppliers s
                    ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
                INNER JOIN dbo.Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN Slu_AW_Credit_Terms ct
                    ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
                LEFT JOIN Slu_AW_Months m
                    ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID

            WHERE t.AO_Suppliers_ID = @SupplierID AND
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(t.Slu_AW_Years_ID)) <= @Period AND
                  ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
                  t.To_Be_Paid <> 0 AND        --0 = Don't pay
                 (t.Sys_AW_Transaction_Types_ID = 6 OR     --Supplier Settlement Discount
                  t.Sys_AW_Transaction_Types_ID = 8 OR     --Purchase Invoice
                  t.Sys_AW_Transaction_Types_ID = 9 OR     --Purchase Refund
                  t.Sys_AW_Transaction_Types_ID = 10 OR    --Purchase Journal
                  t.Sys_AW_Transaction_Types_ID = 12)      --Supplier Payment
--              ((t.Sys_AW_Transaction_Types_ID <> 12 AND
--                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0) OR
--                t.Sys_AW_Transaction_Types_ID = 12)
            ORDER BY [Document Date]
        END

    ELSE    --@ToBePaid = 0    --0 = Print ALL unpaid transactions
        BEGIN
    		SELECT
                t.AO_Suppliers_ID AS [SupplierID],
                t.AO_Transactions_ID as [ID], 
                s.Supplier_Name AS [Supplier],
                s.Supplier_Number AS [Supplier No],
            	s.Credit_Limit AS [Credit Limit],
            	ct.[Description] AS [Terms Type],
            	s.Default_Settlement_Discount AS [Default Settlement %],
            	s.Supplier_Contact AS [Contact],
               	s.Supplier_Telephone AS [TelNo],
            	s.Contact_Cellphone AS [CellNo],
            	s.Supplier_Fax AS [FaxNo],
                s.Post_Box AS [Post Box],
                s.Post_Office AS [Post Office],
                s.Post_Code AS [Post Code],
                s.Email_Address AS [Email],
                s.Tax_Number AS [Tax No],
                tt.[Description] AS [Type],
                t.Document_Number AS [Document No],
                CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Document Date], 
                t.Slu_AW_Months_ID AS [MonthID],
                t.Slu_AW_Years_ID AS [YearID],
                dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(t.Slu_AW_Years_ID)) AS [Period],
                ISNULL(t.Total_Amount, 0) AS [Amount],
                ISNULL(t.Payment_Amount, 0) AS [Payment],
                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Owing],
                t.Settlement_Discount AS [Settlement],
                t.To_Be_Paid AS [Pay],
                ISNULL(t.To_Be_Paid_Amount, 0) - ISNULL(t.Settlement_Discount, 0) AS [Pay Amount],
                t.Remittance_Balance AS [Balance],
                t.Date_Captured,
                t.[User_ID],
                m.[Description] AS [Month],
                y.[Description] AS [Year]
            FROM AO_Transactions t
                INNER JOIN AO_Suppliers s
                    ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
                INNER JOIN dbo.Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN Slu_AW_Credit_Terms ct
                    ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
                LEFT JOIN Slu_AW_Months m
                    ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID

            WHERE t.AO_Suppliers_ID = @SupplierID AND
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, dbo.fn_AW_Get_Year_From_YearID(t.Slu_AW_Years_ID)) <= @Period AND
                  ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
                 (t.Sys_AW_Transaction_Types_ID = 6 OR     --Supplier Settlement Discount
                  t.Sys_AW_Transaction_Types_ID = 8 OR     --Purchase Invoice
                  t.Sys_AW_Transaction_Types_ID = 9 OR     --Purchase Refund
                  t.Sys_AW_Transaction_Types_ID = 10 OR    --Purchase Journal
                  t.Sys_AW_Transaction_Types_ID = 12)      --Supplier Payment
--              ((t.Sys_AW_Transaction_Types_ID <> 12 AND
--                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0) OR
--                t.Sys_AW_Transaction_Types_ID = 12)
            ORDER BY [Document Date]
        END


SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Accounts_Temp
--Purpose       :Retrieves Ad-Hoc Supplier Remittance data in Remittance Report
--Tables        :AO_Remittances_Temp, AO_Remittance_Details_Temp
--Parameters    :
--Date          :2002/06/20
--Authors       :TB
--Version       :1.0.0
--MODS          :15/08/02 - Added Supplier Bank Details for Age Analysis
--              :25/10/02 - Validated balance of money fields with ISNULL and
--              :           NB NB NB ALL INSNULL validations MUST BE ALIASED
--              :06/01/04 - Added Print ZERO Balances input parameter
------------------------------------------------------------------------------

CREATE                     PROCEDURE sp_RPT_AO_Supplier_Accounts_Temp
    (
        @PeriodProceduresID int,
        @chkZeroBal tinyint
    )

AS

SET NOCOUNT ON

    IF @chkZeroBal = 1    --Print ZERO Balances
        BEGIN
            SELECT DISTINCT
                t.AO_Suppliers_ID AS [SupplierID], 
                t.Supplier,
        		ISNULL(t.Supplier_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AO_Suppliers_ID) + ')' AS [SupplierNo],
            	t.Credit_Limit,
            	t.Credit_Terms,
            	t.Default_Settlement_Discount,
            	t.Supplier_Contact,
               	t.Supplier_Telephone,
            	t.Contact_Cellphone,
            	t.Supplier_Fax,
                t.Post_Box AS [SupplierPostAddress],
                t.Post_Office AS [SupplierPostOffice],
                t.Post_Code AS [SupplierPostCode],
                t.Email_Address AS [SupplierEmail],
                (ISNULL(t.[Current], 0) +
                ISNULL(t.[30Days], 0) +
                ISNULL(t.[60Days], 0) +
                ISNULL(t.[90Days], 0) +
                ISNULL(t.[120Days], 0) +
                ISNULL(t.[150Days], 0) +
                ISNULL(t.[180+Days], 0)) AS [AccountBalance],
                ISNULL(t.To_Be_Paid_Total, 0) AS [To_Be_Paid_Total],
                ISNULL(t.[Current], 0) AS [Current],
                ISNULL(t.[30Days], 0) AS [30Days],
                ISNULL(t.[60Days], 0) AS [60Days],
                ISNULL(t.[90Days], 0) AS [90Days],
                (ISNULL(t.[120Days], 0) +
                 ISNULL(t.[150Days], 0) +
                 ISNULL(t.[180+Days], 0)) AS [120+Days],
        -- NEW 15/08/02 -----------------------------------------
                ISNULL(b.[Description], '') AS [Bank Name],
                ISNULL(s.Bank_Branch, '') AS [Branch Name],
                ISNULL(s.Bank_Branch_Code, '') AS [Branch Code],
                ISNULL(s.Account_Name, '') AS [Account Name],
                ISNULL(s.Account_Number, '') AS [Account Number]
        ---------------------------------------------------------
            FROM AO_Remittances_Temp t 
                LEFT JOIN AO_Suppliers s
                    ON s.AO_Suppliers_ID = t.AO_Suppliers_ID
                LEFT JOIN Slu_AW_Banks b
                    ON b.Slu_AW_Banks_ID = s.Slu_AW_Banks_ID
            WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID
            ORDER BY t.Supplier        --SupplierID (24/06/02)

        END

    ELSE                --DO NOT Print ZERO Balances
        BEGIN
            SELECT DISTINCT
                t.AO_Suppliers_ID AS [SupplierID], 
                t.Supplier,
        		ISNULL(t.Supplier_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AO_Suppliers_ID) + ')' AS [SupplierNo],
            	t.Credit_Limit,
            	t.Credit_Terms,
            	t.Default_Settlement_Discount,
            	t.Supplier_Contact,
               	t.Supplier_Telephone,
            	t.Contact_Cellphone,
            	t.Supplier_Fax,
                t.Post_Box AS [SupplierPostAddress],
                t.Post_Office AS [SupplierPostOffice],
                t.Post_Code AS [SupplierPostCode],
                t.Email_Address AS [SupplierEmail],
                (ISNULL(t.[Current], 0) +
                ISNULL(t.[30Days], 0) +
                ISNULL(t.[60Days], 0) +
                ISNULL(t.[90Days], 0) +
                ISNULL(t.[120Days], 0) +
                ISNULL(t.[150Days], 0) +
                ISNULL(t.[180+Days], 0)) AS [AccountBalance],
                ISNULL(t.To_Be_Paid_Total, 0) AS [To_Be_Paid_Total],
                ISNULL(t.[Current], 0) AS [Current],
                ISNULL(t.[30Days], 0) AS [30Days],
                ISNULL(t.[60Days], 0) AS [60Days],
                ISNULL(t.[90Days], 0) AS [90Days],
                (ISNULL(t.[120Days], 0) +
                 ISNULL(t.[150Days], 0) +
                 ISNULL(t.[180+Days], 0)) AS [120+Days],
        -- NEW 15/08/02 -----------------------------------------
                ISNULL(b.[Description], '') AS [Bank Name],
                ISNULL(s.Bank_Branch, '') AS [Branch Name],
                ISNULL(s.Bank_Branch_Code, '') AS [Branch Code],
                ISNULL(s.Account_Name, '') AS [Account Name],
                ISNULL(s.Account_Number, '') AS [Account Number]
        ---------------------------------------------------------
            FROM AO_Remittances_Temp t 
                LEFT JOIN AO_Suppliers s
                    ON s.AO_Suppliers_ID = t.AO_Suppliers_ID
                LEFT JOIN Slu_AW_Banks b
                    ON b.Slu_AW_Banks_ID = s.Slu_AW_Banks_ID
            WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID AND
                 (ISNULL(t.[Current], 0) +
                 ISNULL(t.[30Days], 0) +
                 ISNULL(t.[60Days], 0) +
                 ISNULL(t.[90Days], 0) +
                 ISNULL(t.[120Days], 0) +
                 ISNULL(t.[150Days], 0) +
                 ISNULL(t.[180+Days], 0)) <> 0
            ORDER BY t.Supplier        --SupplierID (24/06/02)

        END




SET NOCOUNT OFF



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Age_Analysis
--Purpose       :Supplier Age Analysis report
--Functionality :Combines INTERIM and PERIOD PROCEDURE options 
--Date          :2007/03/09
--Authors       :TB
--MODS          :
--2004.4.2      :27/11/08 - Added ISNULL validation on all ageing fields
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AO_Supplier_Age_Analysis
    (
        @PeriodProceduresID int,
        @PrintZeroBalances tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + ' t.FullName AS [Supplier], '
    SET @sql = @sql + ' t.Supplier_Number AS [SupplierNo], '
    SET @sql = @sql + ' t.Post_Address AS [SupplierPostAddress], '
    SET @sql = @sql + ' t.Post_Office AS [SupplierPostOffice], '
    SET @sql = @sql + ' t.Post_Code AS [SupplierPostCode], '
    SET @sql = @sql + ' t.Email_Address AS [SupplierEmail], '
    SET @sql = @sql + ' ISNULL(t.Account_Balance, 0) AS [AccountBalance], '
    SET @sql = @sql + ' ISNULL(t.[Current], 0) AS [Current], '
    SET @sql = @sql + ' ISNULL(t.[30Days], 0) AS [30Days], '
    SET @sql = @sql + ' ISNULL(t.[60Days], 0) AS [60Days], '
    SET @sql = @sql + ' ISNULL(t.[90Days], 0) AS [90Days], '
    SET @sql = @sql + ' (ISNULL(t.[120Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[150Days], 0) + '
    SET @sql = @sql + '  ISNULL(t.[180+Days], 0)) AS [120+Days], '
    SET @sql = @sql + ' c.Supplier_Contact, '
    SET @sql = @sql + ' c.Supplier_Telephone, '
    SET @sql = @sql + ' c.Credit_Limit, '
    SET @sql = @sql + ' c.Supplier_Fax, '
    SET @sql = @sql + ' c.Contact_Cellphone, '
    SET @sql = @sql + ' tt.[Description] AS [Terms], '
    SET @sql = @sql + ' s.[Description] AS [Status] '

    IF @PeriodProceduresID = 0
        BEGIN
            SET @sql = @sql +
               ' FROM AO_Statements_Temp t '
        END
    ELSE
        BEGIN
            SET @sql = @sql +
               ' FROM AO_Statements t '
        END


    SET @sql = @sql +
        ' INNER JOIN AO_Suppliers c ' +
        '     ON t.AO_Suppliers_ID = c.AO_Suppliers_ID ' +
        ' LEFT JOIN Sys_AC_Account_Status s ' +
        '     ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID ' +
        ' LEFT JOIN Slu_AW_Credit_Terms tt ' +
        '     ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID ' +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
        '       AND t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '


    IF @PrintZeroBalances = 0
        BEGIN
            SET @sql = @sql + '       AND ISNULL(t.Account_Balance, 0) <> 0 '
        END

    SET @sql = @sql + ' ORDER BY t.FullName '



    EXEC (@sql)




SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Journals_GL
--Purpose       :Supplier Journal Transactions by GL Allocations
--Date          :2004/12/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE          PROCEDURE sp_RPT_AO_Supplier_Journals_GL
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gt.AB_GL_Transactions_ID AS [GLTranID], '
    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gt.AB_Source_Ref AS [GLSourceRefID], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount], '
    SET @sql = @sql + '     t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID],  '
    SET @sql = @sql + '     s.Supplier_Name AS [SupplierName], '
    SET @sql = @sql + '     s.Supplier_Number AS [SupplierNo], '

    SET @sql = @sql + '     ISNULL(s.Supplier_Name, '''') +
                             '' ('' + ISNULL(s.Supplier_Number, '''') + '')'' +
                             '' ('' + CONVERT(VARCHAR(10), s.AO_Suppliers_ID) + '') '' +
                             ISNULL(s.Post_Box, '''') + '', '' +
                             + ISNULL(s.Post_Office, '''') + '', '' +
                             + ISNULL(s.Post_Code, '''')
                              AS [SupplierFull], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date],  '
    SET @sql = @sql + '     tt.Type_Code AS [Type],  '
    SET @sql = @sql + '     t.Supplier_Reference AS [Ref No],  '
    SET @sql = @sql + '     t.Document_Number AS [Doc No],  '

    SET @sql = @sql + '     t.Comment AS [Notes],  '
    SET @sql = @sql + '     t.Net_Amount AS [Net], '
    SET @sql = @sql + '     t.Total_Tax_Amount AS [VAT], '
    SET @sql = @sql + '     t.Total_Amount AS [Total], '
    SET @sql = @sql + '     t.Payment_Amount AS [Payment],  '
    SET @sql = @sql + '     gl.[Description] AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     INNER JOIN AO_Transactions t '
    SET @sql = @sql + '         ON gt.AB_Transaction_Ref = t.AO_Transactions_ID '
--    SET @sql = @sql + '         ON gt.AB_Source_Ref = t.Document_Number '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '         ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '         t.AO_Transactions_ID = gt.AB_Transaction_Ref AND '
--    SET @sql = @sql + '         t.Document_Number = gt.AB_Source_Ref AND '
    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 7 AND '
    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    SET @sql = @sql + '     ORDER BY [SupplierFull], gt.AB_Transaction_Ref '


    EXEC (@sql)


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Journals_GL_Summary
--Purpose       :Supplier Journal Transactions by GL Allocations Summary
--Date          :2004/12/03
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE          PROCEDURE sp_RPT_AO_Supplier_Journals_GL_Summary
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gl.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     SUM(gt.AB_Transaction_Amount) AS [GLTranAmount], '
    SET @sql = @sql + '     MAX(gl.[Description]) AS [GL Account] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     INNER JOIN AO_Transactions t '
    SET @sql = @sql + '         ON gt.AB_Transaction_Ref = t.AO_Transactions_ID '
--    SET @sql = @sql + '         ON gt.AB_Source_Ref = t.Document_Number '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '

    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '         t.AO_Transactions_ID = gt.AB_Transaction_Ref AND '
--    SET @sql = @sql + '         t.Document_Number = gt.AB_Source_Ref AND '
    SET @sql = @sql + '         gt.Sys_AB_Transaction_Types_ID = 7 AND '
    SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    SET @sql = @sql + '     GROUP BY gt.AW_User_Companies_ID, gl.AB_Accounts_ID '
    SET @sql = @sql + '     ORDER BY MAX(gl.[Description]) '


    EXEC (@sql)


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Ledger
--Purpose       :Supplier Account Audit Trail
--Functionality :Shows ALL transactions INCLUDING those FULLY PAID
--Date          :2004/03/18
--Authors       :TB
--Version       :1.0.0
--MODS:         :21/11/04 - Added ACCOUNTING PERIOD filter to DATE filter with
--              :           fn_AO_BFWD_Supplier_Date_Balance and
--              :           fn_AO_BFWD_Supplier_Period_Balance to fetch BFWD
--2004.3.5      :22/06/07 - Removed CONVERT(varchar(10), for @StartPeriod in
--              :           calling dbo.fn_AO_BFWD_Supplier_Period_Balance
-------------------------------------------------------------------------------
--EXEC sp_RPT_AO_Supplier_Ledger 1, 1, 118, 0, '2004/07/30 12:00:01 AM', '2004/10/28 11:59:59 PM', 1, 10, 5
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_RPT_AO_Supplier_Ledger
    (
            @CompanyID int,
            @ChkAllSuppliers int,
            @SupplierID int,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime,
            @ChkPeriod int,
            @MonthID tinyint,
            @YearID int
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllSuppliers = 1
-- SET @SupplierID = 1627
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'
-- SET @ChkPeriod = 0
-- SET @MonthID = '2003/01/01 12:00:01 AM'
-- SET @YearID = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(7000),
            @StartPeriod varchar(6),
            @Month tinyint,
            @Year int


    SET @Month = @MonthID - 1
    SET @Year = @YearID
    
    IF @Month < 1
        BEGIN
            SET @Month = 12
            SET @Year = @Year - 1
        END

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@Month, @Year)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Date_Captured, 121) AS [CalDay], '
    SET @sql = @sql + ' dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) AS [Period], '
    SET @sql = @sql + ' t.AO_Transactions_ID AS [TranID], '

    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') + '' '' + '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), s.AO_Suppliers_ID) + '')'' AS [Supplier], '

    SET @sql = @sql + ' ISNULL(s.Supplier_Number, '''') AS [SupplierNo], '
    SET @sql = @sql + ' ct.[Description] AS [CreditTerms], '
    SET @sql = @sql + ' ISNULL(s.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' ISNULL(s.Post_Box, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(s.Post_Office, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(s.Post_Code, '''') AS [Address], '

    IF @ChkDates = 1               --From/To Dates
        BEGIN
            SET @sql = @sql + ' dbo.fn_AO_BFWD_Supplier_Date_Balance(t.AO_Suppliers_ID, ' +
                                    '''' + CONVERT(varchar(30), @StartDate) + '''' +
                               ') AS [BFWD], '
        END

    IF @ChkPeriod = 1              --Accounting Period
        BEGIN
--             SET @sql = @sql + ' dbo.fn_AO_BFWD_Supplier_Period_Balance(t.AO_Suppliers_ID, ' +
--                                     '''' + CONVERT(varchar(10), @StartPeriod) + '''' +
--                                ') AS [BFWD], '
            SET @sql = @sql + ' dbo.fn_AO_BFWD_Supplier_Period_Balance(t.AO_Suppliers_ID, ' +
                                    '''' + @StartPeriod + '''' +
                               ') AS [BFWD], '
        END

    SET @sql = @sql + ' CONVERT(CHAR(10), t.Document_Date, 121) AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [TranType], '
    SET @sql = @sql + ' t.Document_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(t.Supplier_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(t.Comment, '''') AS [Comment], '
    SET @sql = @sql + ' ISNULL(t.AO_GRV_ID, '''') AS [GRV], '

    SET @sql = @sql + ' m.[Description] AS [Month], '
    SET @sql = @sql + ' y.[Description] AS [Year], '

    SET @sql = @sql + ' ISNULL(t.Trade_Discount_Total, 0) + ISNULL(t.Rebate_Discount_Total, 0) + ISNULL(t.Other_Discount_Total, 0) AS [Discount], '
    SET @sql = @sql + ' t.Net_Amount AS [Amount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' t.Date_Captured AS [Date Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AO_Transactions t '
    SET @sql = @sql + '      LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '          ON s.AO_Suppliers_ID = t.AO_Suppliers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      INNER JOIN Slu_AW_Months m '
    SET @sql = @sql + '      	 ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '      INNER JOIN Slu_AW_Years y '
    SET @sql = @sql + '      	 ON t.Slu_AW_Years_ID  = y.Slu_AW_Years_ID '
    SET @sql = @sql + '      LEFT JOIN Slu_AW_Credit_Terms ct '
    SET @sql = @sql + '          ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID '

    SET @sql = @sql +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '   (t.Sys_AW_Transaction_Types_ID = 6 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 8 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 9 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 10 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 11 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 12) '

    IF @ChkAllSuppliers = 0        --Single Supplier Account
        BEGIN
            SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' '
        END


    IF @ChkDates = 1               --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Document_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Document_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '

            SET @sql = @sql + ' ORDER BY s.Supplier_Name, t.AO_Suppliers_ID, t.Date_Captured ASC '
        END
    ELSE
    IF @ChkPeriod = 1              --Accounting Period
        BEGIN
            SET @sql = @sql + '  AND t.Slu_AW_Months_ID = ' + '''' + CONVERT(varchar(10), @MonthID) + '''' + ' '
            SET @sql = @sql + '  AND t.Slu_AW_Years_ID = ' + '''' + CONVERT(varchar(10), @YearID) + '''' + ' '

            SET @sql = @sql + ' ORDER BY s.Supplier_Name, t.AO_Suppliers_ID, [Period] ASC '
        END



    EXEC (@sql)


SET NOCOUNT OFF

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Payments
--Purpose       :Supplier Payment and Source Transactions
--Functionality :Will only print Supplier Payments from 2004.2.0 upwards
--Date          :2004/12/04
--Authors       :TB
--Version       :1.0.0
--MODS          :06/03/05 - Added Settlement_Discount field
--2004.3.7      :12/10/07 - Added [Paid] (Payment - Stellement) field
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AO_Supplier_Payments
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     st.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     st.Tran_Ref_No AS [TranRefID], '
    SET @sql = @sql + '     tt.Type_Code AS [Type], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date], '
    SET @sql = @sql + '     st.AO_Transactions_Transactions_ID AS [TranTranID], '
    SET @sql = @sql + '     st.Source_AO_Transactions_ID AS [SourceTranID], '
    SET @sql = @sql + '     st.Destination_AO_Transactions_ID AS [DestinationTranID], '

    SET @sql = @sql + '     ISNULL(s.Supplier_Name, '''') +
                             '' ('' + CONVERT(VARCHAR(10), s.AO_Suppliers_ID) + '') '' +
                             ISNULL(s.Post_Box, '''') + '', '' +
                             + ISNULL(s.Post_Office, '''') + '', '' +
                             + ISNULL(s.Post_Code, '''')
                              AS [SupplierFull], '
    SET @sql = @sql + '     s.Supplier_Number AS [SupplierNo], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT z.Type_Code '
    SET @sql = @sql + '     FROM AO_Transactions x'
    SET @sql = @sql + '         INNER JOIN Sys_AW_Transaction_Types z '
    SET @sql = @sql + '             ON x.Sys_AW_Transaction_Types_ID = z.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     WHERE x.AO_Transactions_ID = st.Source_AO_Transactions_ID '
    SET @sql = @sql + ' ) AS [SourceType], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT Supplier_Reference '
    SET @sql = @sql + '     FROM AO_Transactions '
    SET @sql = @sql + '     WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID '
    SET @sql = @sql + ' ) AS [SourceRefNo], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT Document_Number '
    SET @sql = @sql + '     FROM AO_Transactions '
    SET @sql = @sql + '     WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID '
    SET @sql = @sql + ' ) AS [SourceDocNo], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT Document_Date '
    SET @sql = @sql + '     FROM AO_Transactions '
    SET @sql = @sql + '     WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID '
    SET @sql = @sql + ' ) AS [SourceDocDate], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Total_Amount), 0) '
    SET @sql = @sql + '     FROM AO_Transactions '
    SET @sql = @sql + '     WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID '
    SET @sql = @sql + ' ) AS [SourceTotal], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Payment_Amount), 0) '
    SET @sql = @sql + '     FROM AO_Transactions '
    SET @sql = @sql + '     WHERE AO_Transactions_ID = st.Source_AO_Transactions_ID '
    SET @sql = @sql + ' ) AS [SourcePayment], '

    SET @sql = @sql + '     st.Amount AS [Allocated], '
    SET @sql = @sql + '     t.Total_Amount AS [Total], '
    SET @sql = @sql + '     t.Settlement_Discount AS [Settlement], '
    SET @sql = @sql + '     t.Payment_Amount AS [Payment], '
    SET @sql = @sql + '     t.Payment_Amount + t.Settlement_Discount AS [Paid], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID],  '
    SET @sql = @sql + '     t.Supplier_Reference AS [Ref No],  '
    SET @sql = @sql + '     t.Document_Number AS [Doc No],  '
    SET @sql = @sql + '     st.Date_Captured AS [Captured] '

    SET @sql = @sql + '     FROM AO_Transactions_Transactions st '
    SET @sql = @sql + '         LEFT JOIN AO_Transactions t '
    SET @sql = @sql + '             ON st.Destination_AO_Transactions_ID = t.AO_Transactions_ID '
    SET @sql = @sql + '         LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '             ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '         LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '             ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '     WHERE st.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '        (st.Tran_Ref_No <> '''' OR '
    SET @sql = @sql + '         st.Tran_Ref_No IS NULL) AND '
    SET @sql = @sql + '         t.Sys_AW_Transaction_Types_ID = 12 AND '
    SET @sql = @sql + '         t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '         t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    SET @sql = @sql + '     ORDER BY [SupplierFull], st.Tran_Ref_No, st.Source_AO_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Payments_Audit_Trail
--Purpose       :Supplier Payments from AO_Transactions
--Functionality :
--Date          :2005/09/08
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE          PROCEDURE sp_RPT_AO_Supplier_Payments_Audit_Trail
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    SELECT DISTINCT
           t.AW_User_Companies_ID AS [CompanyID],
           tt.Type_Code AS [Type],
           t.Sys_AW_Transaction_Types_ID AS [TranType],
           CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date],
           m.Description AS [Method],
           ISNULL(b.Description, '') + ' (' + ISNULL(cb.Account_Number, '') + ')' AS [Bank],
           ISNULL(s.Supplier_Name, '') + ' ' +
                 CONVERT(VARCHAR(10), s.AO_Suppliers_ID) +
                 ISNULL(s.Post_Box, '') + ' ,' +
                 ISNULL(s.Post_Office, '') + ', ' +
                 ISNULL(s.Post_Code, '') + ' (' +
                 ISNULL(s.Supplier_Number, '') + ') (' +
                 CONVERT(varchar(10), t.AO_Suppliers_ID) + ')' AS [SupplierFull],
           t.Total_Amount AS [Total],
           t.Settlement_Discount AS [Settlement],
           t.Payment_Amount AS [Payment],
           t.Supplier_Reference AS [Ref No],
           t.Document_Number AS [Doc No],
           t.Date_Captured AS [Captured]
    
    FROM AO_Transactions t
        LEFT JOIN AO_Transaction_Payments p
            ON t.AO_Transactions_ID = p.AO_Transactions_ID
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AW_Company_Banks cb
            ON p.AW_Company_Banks_ID = cb.AW_Company_Banks_ID
        LEFT JOIN Slu_AW_Banks b
            ON cb.Slu_AW_Banks_ID = b.Slu_AW_Banks_ID
        LEFT JOIN Sys_AW_Payment_Methods m
            ON p.Sys_AW_Payment_Methods_ID = m.Sys_AW_Payment_Methods_ID

    WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.Sys_AW_Transaction_Types_ID = 12 AND
          t.Slu_AW_Months_ID = @MonthID AND
          t.Slu_AW_Years_ID = @YearID

    ORDER BY [SupplierFull], [Date]


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Payments_GL
--Purpose       :Supplier Payment Transactions by GL Allocations Summary
--Date          :2004/12/04
--Authors       :TB
--Version       :1.0.0
--MODS          :08/09/05 - Fixed SQL Syntax error converting the varchar value
--              :           to a column of data type int for gt.AB_Source_Ref
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Supplier_Payments_GL
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @ABSourceRef varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gl.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount], '
    SET @sql = @sql + '     gl.[Description] AS [GL Account] '

    SET @sql = @sql + ' FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '

    SET @sql = @sql + ' WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--    SET @sql = @sql + '         gt.AB_Source_Ref = ' + @ABSourceRef + ' AND '
    SET @sql = @sql + '       gt.AB_Source_Ref = ''' + @ABSourceRef + ''' AND '
    SET @sql = @sql + '       gt.Sys_AB_Transaction_Types_ID = 8 AND '
    SET @sql = @sql + '       gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '       gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '

    SET @sql = @sql + ' ORDER BY gl.[Description] '


    EXEC (@sql)


SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Payments_GL_Control_Amount
--Purpose       :Supplier Payment GL Creditors Control Amount
--Date          :2007/06/24
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AO_Supplier_Payments_GL_Control_Amount
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID int,
        @ABSourceRef varchar(20),
        @GLAmount money OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @Trade_Creditors_Control_ID int


    -------------------------------------------------------
--> Get the Trade Creditors Control Account ID
    -------------------------------------------------------    
    SELECT @Trade_Creditors_Control_ID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 201    -- Trade Creditors Control


    SELECT @GLAmount = AB_Transaction_Amount
    FROM AB_GL_Transactions
    WHERE AW_User_Companies_ID = @CompanyID AND
          AB_Source_Ref = @ABSourceRef AND
          Sys_AB_Transaction_Types_ID = 8 AND
          Slu_AW_Months_ID = @MonthID AND
          Slu_AW_Years_ID = @YearID AND
          AB_Accounts_ID = @Trade_Creditors_Control_ID



SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Products
--Purpose       :Retrieves Product Purchases by Supplier
--Date          :2008/08/07
--Authors       :TB
--MODS          :
--V6.0	RL	2014-05-09	:Added Document date and Supplier search options
--V6.2	RL	2016-07-01	:Excluded consignment GRV's
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AO_Supplier_Products]
    (
        @Option tinyint,
        @ChkPeriod int,
        @MonthID tinyint,
    	@YearID int,
        @ToMonthID tinyint,
    	@ToYearID int,
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @ChkAllSuppliers int,
		@SupplierID int              
    )

AS

SET NOCOUNT ON

        DECLARE @StartPeriod varchar(6),
                @EndPeriod varchar(6),
				@sql varchar(8000)

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)


	SET @sql = ' SELECT '
	
	SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID],'
	SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID],'
	SET @sql = @sql + ' pd.Lup_AP_Product_Departments_ID AS [DeptID],'
	SET @sql = @sql + ' ISNULL(pd.[Description], '''') AS [DeptName], '
	SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier],'
	SET @sql = @sql + ' ISNULL(t.Document_Date, '''') AS [Date],'
	SET @sql = @sql + ' ISNULL(t.Document_Number, '''') AS [Ref No],'
	SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [Type],'
	SET @sql = @sql + ' ISNULL(gl.[Description], '''') AS [GL Account],'

	SET @sql = @sql + ' t.Slu_AW_Months_ID AS [Month],'
	SET @sql = @sql + ' t.Slu_AW_Years_ID AS [Year],'

	SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product],'
	SET @sql = @sql + ' ISNULL(t.AO_GRV_ID, 0) AS [GRV],'
	SET @sql = @sql + ' ISNULL(gd.Qty, 0) AS [Qty],'
	SET @sql = @sql + ' ISNULL(gd.Unit_Price, 0) AS [Unit Price],'

	SET @sql = @sql + ' ISNULL((gd.Unit_Price * gd.Qty), 0) AS [UnitAmount],'

	SET @sql = @sql + ' ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade],'
	SET @sql = @sql + ' ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate],'
	SET @sql = @sql + ' ISNULL(gd.Other_Discount_Amount, 0) AS [Other],'

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0'
	SET @sql = @sql + '		THEN ROUND((gd.Trade_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)'
	SET @sql = @sql + '		ELSE 0.00'
	SET @sql = @sql + '		END AS [Trade%],'

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0'
	SET @sql = @sql + '		THEN ROUND((gd.Rebate_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)'
	SET @sql = @sql + '		ELSE 0.00'
	SET @sql = @sql + '		END AS [Rebate%],'

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0'
	SET @sql = @sql + '		THEN ROUND((gd.Other_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)'
	SET @sql = @sql + '		ELSE 0.00'
	SET @sql = @sql + '		END AS [Other%],'

	SET @sql = @sql + ' ISNULL(gd.Net_Amount, 0) AS [Sub-Total],'
	SET @sql = @sql + ' ISNULL(gd.Tax_Amount, 0) AS [Tax],'
	SET @sql = @sql + ' ISNULL(gd.Total_Cost, 0) AS [Total],'

	SET @sql = @sql + ' dbo.GetGrossMargin'
	SET @sql = @sql + ' ('
	SET @sql = @sql + '		p.Price1_Effective_Date,'
	SET @sql = @sql + '		p.Price1_Price1,'
	SET @sql = @sql + '		p.Price2_Effective_Date,'
	SET @sql = @sql + '		p.Price2_Price1,'
	SET @sql = @sql + '		getdate(),'
	SET @sql = @sql + '		p.Last_Cost'
	SET @sql = @sql + '	) as [LastGP%],'
	SET @sql = @sql + ' dbo.GetGrossMargin'
	SET @sql = @sql + ' ('
	SET @sql = @sql + '		p.Price1_Effective_Date,'
	SET @sql = @sql + '		p.Price1_Price1,'
	SET @sql = @sql + '		p.Price2_Effective_Date,'
	SET @sql = @sql + '		p.Price2_Price1,'
	SET @sql = @sql + '		getdate(),'
	SET @sql = @sql + '		p.Average_Cost'
	SET @sql = @sql + ' ) as [AvgGP%],'
	SET @sql = @sql + '	dbo.GetGrossMargin'
	SET @sql = @sql + ' ('
	SET @sql = @sql + '		p.Price1_Effective_Date,'
	SET @sql = @sql + '		p.Price1_Price1,'
	SET @sql = @sql + '		p.Price2_Effective_Date,'
	SET @sql = @sql + '		p.Price2_Price1,'
	SET @sql = @sql + '		getdate(),'
	SET @sql = @sql + '		p.Standard_Cost'
	SET @sql = @sql + ' ) as [StdGP%]'

	SET @sql = @sql + ' FROM AO_Transactions t'
	SET @sql = @sql + ' LEFT JOIN AO_Suppliers s'
	SET @sql = @sql + '		ON t.AO_Suppliers_ID = s.AO_Suppliers_ID'
	SET @sql = @sql + '	LEFT OUTER JOIN Sys_AW_Transaction_Types tt'
	SET @sql = @sql + '		ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID'
	SET @sql = @sql + ' LEFT JOIN AB_Accounts gl'
	SET @sql = @sql + '		ON t.AB_Accounts_ID = gl.AB_Accounts_ID'
	SET @sql = @sql + ' INNER JOIN AO_GRV gh'
	SET @sql = @sql + '		ON t.AO_GRV_ID = gh.AO_GRV_ID'
	SET @sql = @sql + ' INNER JOIN AO_GRV_Details gd'
	SET @sql = @sql + '		On gh.AO_GRV_ID = gd.AO_GRV_ID'
	SET @sql = @sql + ' INNER JOIN AP_Products p'
	SET @sql = @sql + '		ON gd.AP_Products_ID = p.AP_Products_ID'
	SET @sql = @sql + ' INNER JOIN Lup_AP_Product_Departments pd'
	SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID'

	SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ''
	
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 31'		--Consignment Goods Received
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 32'		--Consignment Goods Returned
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 34'		--Consignment Sold

	IF @ChkPeriod = 1        --Accounting Period
	BEGIN
		SET @sql = @sql + ' AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) BETWEEN ' + @StartPeriod + ' AND ' + @EndPeriod + ''
    END      
          	      
	IF @ChkDates = 1               --From/To Dates
	BEGIN
		SET @sql = @sql + '  AND t.Document_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ''
		SET @sql = @sql + '  AND t.Document_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    END      
          
	IF @ChkAllSuppliers = 0        --Single Supplier Account
	BEGIN
		SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ''
    END      
         
	SET @sql = @sql + ' ORDER BY [Supplier], [Product], [SupplierID], [Date]'

	EXEC (@sql)
--Select @sql
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Purchases_Journal
--Purpose       :Supplier Transaction data for Purchase JNL
--Date          :2004/04/16
--Authors       :TB
--Version       :1.0.0
--MODS          :13/10/04 - Added more fields for new Landscape layout
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Supplier_Purchases_Journal
    (
        @MonthID tinyint,
    	@YearID int,
        @CompanyID as int
    )

AS

SET NOCOUNT ON


    SELECT
        t.AW_User_Companies_ID AS [CompanyID],
        t.AO_Transactions_ID AS [TranID],
        t.AO_Suppliers_ID AS [SupplierID], 
        s.Supplier_Name AS [SupplierName],
        s.Supplier_Name + ISNULL(' (' + s.Supplier_Number + ') ', '') +
            ' (' + CONVERT(VARCHAR(12), s.AO_Suppliers_ID) + ')' +
            ISNULL(' - ' + s.Post_Box + ', ' + s.Post_Office + ', ' + s.Post_Code, '') AS [SupplierFull],
        CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date], 
        tt.Type_Code AS [Type], 
        t.Supplier_Reference AS [Ref No], 
        t.Document_Number AS [Doc No], 

        CASE WHEN t.AO_GRV_ID > 0
             THEN t.AO_GRV_ID
             ELSE NULL
             END AS [GRV], 

        t.Comment AS [Notes], 
        t.Net_Amount AS [Net],
        t.Total_Tax_Amount AS [VAT],
        t.Total_Amount AS [Total],
        t.Settlement_Discount AS [SettleDisc],
        t.Payment_Amount AS [Payment], 
        g.[Description] AS [GL Account],
        t.To_Be_Paid AS [PayBool],
        t.To_Be_Paid_Amount AS [ToBePaid],
        t.Remittance_Balance AS [RemitBalance]
    FROM AO_Transactions t
         LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
         LEFT OUTER JOIN Sys_AW_Transaction_Types tt
             ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
         LEFT JOIN AB_Accounts g
             ON t.AB_Accounts_ID = g.AB_Accounts_ID
    WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.Slu_AW_Months_ID = @MonthID AND
          t.Slu_AW_Years_ID = @YearID AND
         (t.Sys_AW_Transaction_Types_ID = 8 OR
          t.Sys_AW_Transaction_Types_ID = 9)
    ORDER BY t.AO_Suppliers_ID, t.Document_Date


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Purchases_Journal_CR1
--Purpose       :Supplier Transaction data for Purchase JNL from Period Procedure
--              :Transaction Details (AO_Statement_Details)
--Date          :2007/04/18
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AO_Supplier_Purchases_Journal_CR1
    (
        @PeriodProceduresID int,
        @CompanyID as int
    )

AS

SET NOCOUNT ON


    SELECT
        t.AW_User_Companies_ID AS [CompanyID],
        t.AO_Transactions_ID AS [TranID],
        t.AO_Suppliers_ID AS [SupplierID], 
        s.Supplier_Name AS [SupplierName],
        ISNULL(s.Supplier_Number, '') AS [SupplierNo],
        s.Supplier_Name + ISNULL(' (' + s.Supplier_Number + ') ', '') +
            ' (' + CONVERT(VARCHAR(12), s.AO_Suppliers_ID) + ')' +
            ISNULL(' - ' + s.Post_Box + ', ' + s.Post_Office + ', ' + s.Post_Code, '') AS [SupplierFull],
        CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date], 

        CONVERT(varchar(70), (CONVERT(varchar(50), t.Document_Date) + CONVERT(varchar(20), t.AO_GRV_ID))) AS [DateGRVID], 

        CONVERT(varchar(70), (CONVERT(varchar(50), t.Document_Date) + CONVERT(varchar(20), t.Document_Number))) AS [DateDocNo], 

        ISNULL(tt.Type_Code, '') AS [Type], 
        ISNULL(t.Supplier_Reference, '') AS [Ref No], 
        ISNULL(t.Document_Number, '') AS [Doc No], 

        CASE WHEN t.AO_GRV_ID > 0
             THEN t.AO_GRV_ID
             ELSE NULL
             END AS [GRVID], 

        ISNULL(t.Comment, '') AS [Notes], 
        ISNULL(t.Net_Amount, 0) AS [Net],
        ISNULL(t.Total_Tax_Amount, 0) AS [VAT],
        ISNULL(t.Total_Amount, 0) AS [Total],
        ISNULL(t.Settlement_Discount, 0) AS [SettleDisc],
        ISNULL(t.Payment_Amount, 0) AS [Payment], 

        CASE WHEN ISNULL(t.AO_GRV_ID, 0) = 0
             THEN gl.[Description]
             ELSE ''
             END AS [GL Account],

        ISNULL(p.[Description], '') AS [Product],
        ISNULL(p.Product_Code, '') AS [Code],
        ISNULL(gd.Qty, 0) AS [Qty],
        ISNULL(gd.Unit_Price, 0) AS [UnitPrice],

        ISNULL(gd.Net_Amount, 0) AS [NetAmount],
        ISNULL(gd.Tax_Amount, 0) AS [TaxAmount],
        ISNULL(gd.Total_Cost, 0) AS [TotalCost],

        ISNULL(pc.[Description], '') AS [PurchCat]

    FROM AO_Statement_Details t
         LEFT JOIN AO_Statements sh
            ON t.AO_Statements_ID = sh.AO_Statements_ID
         LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
         LEFT OUTER JOIN Sys_AW_Transaction_Types tt
             ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
         LEFT JOIN AO_GRV_Details gd
             ON t.AO_GRV_ID = gd.AO_GRV_ID
         LEFT JOIN AP_Products p
             ON gd.AP_Products_ID = p.AP_Products_ID
         LEFT JOIN AB_Accounts gl
             ON t.AB_Accounts_ID = gl.AB_Accounts_ID
         LEFT JOIN Lup_AP_Purchase_Categories pc
             ON p.Lup_AP_Purchase_Categories_ID = pc.Lup_AP_Purchase_Categories_ID

    WHERE t.AW_User_Companies_ID = @CompanyID AND
          sh.AW_Period_Procedures_ID = @PeriodProceduresID AND
         (t.Sys_AW_Transaction_Types_ID = 8 OR
          t.Sys_AW_Transaction_Types_ID = 9)
    ORDER BY [SupplierFull], [DateGRVID]


SET NOCOUNT OFF





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Purchases_Temp
--Purpose       :Retrieves Ad-Hoc Supplier Transaction data for Purchase JNL
--Tables        :
--Parameters    :
--Date          :2002/08/19
--Authors       :TB
--Version       :1.0.0
--MODS          :05/09/02 - Fixed LEFT JOIN table alias for AB_Accounts (d to g)
--              :25/10/02 - Removed CONVERT(datetime, CONVERT(int, d.Transaction_Date))
--              :           This expression ROUNDS UP dates after 12 noon to NEXT DAY
--2004.3.8      :20/04/08 - Modified ORDER BY clauses for SQL 2005 Upgrade Advisor
------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AO_Supplier_Purchases_Temp
    (
        @PeriodProceduresID int,
        @StartDate as datetime,
        @EndDate as datetime,
        @CompanyID as int
    )

AS

SET NOCOUNT ON


    SELECT
        t.AO_Suppliers_ID AS [ID], 
        t.Supplier + ISNULL(' (' + t.Supplier_Number + ') ', '') +
            ' (' + CONVERT(VARCHAR(12), t.AO_Suppliers_ID) + ')' +
            ISNULL(' - ' + Post_Box + ', ' + Post_Office + ', ' + Post_Code, '') AS [Supplier],
--        CONVERT(datetime, CONVERT(int, d.Transaction_Date)) AS [Date], 
        d.Transaction_Date AS [Date],     
        tt.Type_Code AS [Type], 
        d.Transaction_Number AS [Ref No], 
        aot.Net_Amount AS [Net],
        aot.Total_Tax_Amount AS [VAT],
        aot.Total_Amount AS [Total],
        ISNULL(d.Amount, 0) AS [Amount], 
        ISNULL(d.Payment, 0) AS [Payment], 
        ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
        ISNULL(g.[Description], '') AS [GL Account],
        (ISNULL(t.[Current], 0) +
        ISNULL(t.[30Days], 0) +
        ISNULL(t.[60Days], 0) +
        ISNULL(t.[90Days], 0) +
        ISNULL(t.[120Days], 0) +
        ISNULL(t.[150Days], 0) +
        ISNULL(t.[180+Days], 0)) AS [AccountBalance],
        d.To_Be_Paid AS [PayBool],
        d.To_Be_Paid_Amount AS [ToBePaid],
        d.Remittance_Balance AS [RemitBalance]
    FROM AO_Remittances_Temp t 
         JOIN AO_Remittance_Details_Temp d
             ON t.AO_Remittances_Temp_ID = d.AO_Remittances_Temp_ID
         JOIN AO_Transactions aot
            ON aot.AO_Transactions_ID = d.AO_Transactions_ID
         LEFT OUTER JOIN Sys_AW_Transaction_Types tt
             ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
         LEFT JOIN AB_Accounts g
             ON d.AB_Accounts_ID = g.AB_Accounts_ID
    WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID AND
         (ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0 AND
         (DATEDIFF(d, Transaction_Date, @StartDate) < 0 AND
          DATEDIFF(d, Transaction_Date, @EndDate) >= 0)) OR
         (ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) = 0 AND
         (DATEDIFF(d, Transaction_Date, @StartDate) < 0 AND
          DATEDIFF(d, Transaction_Date, @EndDate) >= 0)) AND
          t.AW_User_Companies_ID = @CompanyID
    ORDER BY [Supplier], [Date]

    --DATEDIFF >= 0 if Document_Date prior to @EndDate
    --DATEDIFF < 0 if Document_Date after @StartDate
    --DATEDIFF = 0 if Document_Date = @Date

SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Remittance
--Purpose       :Extract Supplier Remittance for ONE Supplier
--Date          :2003/12/21
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AO_Supplier_Remittance
	(
        @CompanyID int,
        @SupplierID int,
        @AllUnflagged bit,
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
	)

AS

SET NOCOUNT ON

	DECLARE
        @PeriodProcedureID int,
        @SupplierName varchar(90),
        @SupplierNumber varchar(10),
    	@CreditLimit money,
    	@CreditTerms varchar(20),
    	@SettleDisc decimal(7, 2),
    	@SupplierContact varchar(30),
       	@SuppTel varchar(12),
    	@SuppCel varchar(12),
    	@SuppFax varchar(12),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @WorkEmail varchar(40),
        @AccountBalance money,
        @RemittanceID int,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @ToBePaidTotal money,
        @Period1 varchar(6)


    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)

    SET @PeriodProcedureID = 0


    DECLARE @AO_Remittance_Details_Temp table
        (
            AO_Remittance_Details_Temp_ID int IDENTITY (1, 1) NOT NULL ,
            AO_Remittances_Temp_ID int NULL ,
            AO_Transactions_ID int NULL ,
            AB_Accounts_ID int NULL ,
            Transaction_Date datetime NULL ,
            Sys_AW_Transaction_Types_ID int NULL ,
            Transaction_Number varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Amount money NULL ,
            Payment money NULL ,
            Settlement_Discount money NULL ,
            To_Be_Paid bit NULL ,
            To_Be_Paid_Amount money NULL ,
            Remittance_Balance money NULL ,
            Date_Captured datetime NULL ,
            User_ID int NULL ,
            AW_User_Companies_ID int NOT NULL 
        )

    DECLARE @AO_Remittances_Temp table
        (
            AO_Remittances_Temp_ID int IDENTITY (1, 1) NOT NULL ,
            AW_Period_Procedures_ID int NULL ,
            AO_Suppliers_ID int NULL ,
            Supplier varchar(92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Supplier_Number varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Credit_Limit money NULL ,
            Credit_Terms varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Default_Settlement_Discount decimal(7, 2) NULL ,
            Supplier_Contact varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Supplier_Telephone varchar(12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Contact_Cellphone varchar(12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Supplier_Fax varchar(12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Post_Box varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Post_Office varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Post_Code varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Email_Address varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
            Amount money NULL ,
            Payment money NULL ,
            Account_Balance money NULL ,
            To_Be_Paid_Total money NULL ,
            BalCurrent money NULL ,
            Bal30Days money NULL ,
            Bal60Days money NULL ,
            Bal90Days money NULL ,
            Bal120Days money NULL ,
            Bal150Days money NULL ,
            Bal180Days money NULL ,
            Date_Captured datetime NULL ,
            User_ID int NULL ,
            AW_User_Companies_ID int NOT NULL
        )
    

	DECLARE Supplier_Temp_Cursor CURSOR FOR
        (
        --> Select ALL Suppliers
            SELECT DISTINCT        --DISTINCT = NB
                s.AO_Suppliers_ID,
                ISNULL(s.Supplier_Name,'') AS Supplier,
            	s.Credit_Limit,
            	ct.[Description],
            	s.Default_Settlement_Discount,
            	s.Supplier_Contact,
               	s.Supplier_Telephone,
            	s.Contact_Cellphone,
            	s.Supplier_Fax,
                s.Post_Box,
                s.Post_Office,
                s.Post_Code,
                s.Email_Address,
                Supplier_Number
            FROM AO_Suppliers s
                INNER JOIN AO_Transactions t
                    ON s.AO_Suppliers_ID = t.AO_Suppliers_ID
                LEFT JOIN Slu_AW_Credit_Terms ct
                    ON s.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
            WHERE dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @Period1 AND
                  t.AO_Suppliers_ID = @SupplierID
        )

	OPEN Supplier_Temp_Cursor

    	FETCH NEXT FROM Supplier_Temp_Cursor 
    	INTO
            @SupplierID,
            @SupplierName,
        	@CreditLimit,
        	@CreditTerms,
        	@SettleDisc,
        	@SupplierContact,
           	@SuppTel,
        	@SuppCel,
        	@SuppFax,
            @PostBox,
            @PostOffice,            @PostCode,
            @WorkEmail,
            @SupplierNumber
    	
    	WHILE @@FETCH_STATUS = 0
    	BEGIN

    		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
            FROM dbo.fn_AO_Supplier_Period_Ageing_Values
                    (
                    	@SupplierID, 
                    	@M1, @Y1,
                    	@M2, @Y2,
                    	@M3, @Y3,
                    	@M4, @Y4,
                    	@M5, @Y5,
                    	@M6, @Y6,
                    	@M7, @Y7
                    ) 

            SET @AccountBalance = @AgeCurrent + 
                                  @Age30Days + 
                                  @Age60Days + 
                                  @Age90Days + 
                                  @Age120Days + 
                                  @Age150Days + 
                                  @Age180Days


            IF @AllUnflagged = 1    --1 = Print only flagged To_Be_Paid transactions
                BEGIN
                    SELECT @ToBePaidTotal = SUM(ISNULL(To_Be_Paid_Amount, 0))
                    FROM AO_Transactions
                    WHERE AO_Suppliers_ID = @SupplierID AND
                            Total_Amount <> -(Payment_Amount) AND
                            To_Be_Paid <> 0 AND        --0 = Don't pay
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                           (Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement Discount
                            Sys_AW_Transaction_Types_ID = 8 OR     --Purchase Invoice
                            Sys_AW_Transaction_Types_ID = 9 OR     --Purchase Refund
                            Sys_AW_Transaction_Types_ID = 10 OR    --Purchase Journal
                            Sys_AW_Transaction_Types_ID = 12)      --Supplier Payment
                END
            ELSE    --@AllUnflagged = 0    --0 = Print ALL unpaid transactions
                BEGIN
                    SELECT @ToBePaidTotal = SUM(ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0))
                    FROM AO_Transactions
                    WHERE AO_Suppliers_ID = @SupplierID AND
                            Total_Amount <> -(Payment_Amount) AND
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                           (Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement Discount
                            Sys_AW_Transaction_Types_ID = 8 OR     --Purchase Invoice
                            Sys_AW_Transaction_Types_ID = 9 OR     --Purchase Refund
                            Sys_AW_Transaction_Types_ID = 10 OR    --Purchase Journal
                            Sys_AW_Transaction_Types_ID = 12)      --Supplier Payment
                END

        --> Insert ALL Suppliers        
    		INSERT INTO @AO_Remittances_Temp
    			(
                    AW_Period_Procedures_ID,
                    AO_Suppliers_ID,
                    Supplier,
                    Supplier_Number,
                	Credit_Limit,
                	Credit_Terms,
                	Default_Settlement_Discount,
                	Supplier_Contact,
                   	Supplier_Telephone,
                	Contact_Cellphone,
                	Supplier_Fax,
                    Post_Box,
                    Post_Office,
                    Post_Code,
                    Email_Address,
                    AW_User_Companies_ID,
                    Amount,
                    Payment,
                    Account_Balance,
                    To_Be_Paid_Total,
                    BalCurrent,
                    Bal30Days,
                    Bal60Days,
                    Bal90Days,
                    Bal120Days,
                    Bal150Days,
                    Bal180Days
                )
    		VALUES
    			(
                    @PeriodProcedureID,    --initialized to 0 ??
                    @SupplierID,
                    RTRIM(LTRIM(@SupplierName)),
                    @SupplierNumber,
                	@CreditLimit,
                	@CreditTerms,
                	@SettleDisc,
                	@SupplierContact,
                   	@SuppTel,
                	@SuppCel,
                	@SuppFax,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @CompanyID,
                    @AgeAmount,
                    @AgePayment,
                    @AccountBalance,
                    @ToBePaidTotal,
                    @AgeCurrent,
                    @Age30Days,
                    @Age60Days,
                    @Age90Days,
                    @Age120Days,
                    @Age150Days,
                    @Age180Days
                )

    	  	SELECT @RemittanceID = Scope_Identity()

            IF @AllUnflagged = 1    --1 = Insert only flagged To_Be_Paid transactions
                BEGIN
            		INSERT INTO @AO_Remittance_Details_Temp
            			(
                            AO_Remittances_Temp_ID,
                            AO_Transactions_ID,
                            AB_Accounts_ID,
                            Transaction_Date,
                            Sys_AW_Transaction_Types_ID,
                            Transaction_Number,
                            Amount,
                            Payment,
                            Settlement_Discount,
                            To_Be_Paid,
                            To_Be_Paid_Amount,
                            Remittance_Balance,
                            [User_ID],
                            AW_User_Companies_ID
                        )
                    SELECT 
                            @RemittanceID,
                            AO_Transactions_ID,
                            AB_Accounts_ID,
                            Document_Date,
                            Sys_AW_Transaction_Types_ID,
                            Document_Number,
                            Total_Amount,
                            Payment_Amount,
                            Settlement_Discount,
                            To_Be_Paid,
                            To_Be_Paid_Amount,
                            Remittance_Balance,
                            [User_ID],
                            AW_User_Companies_ID
                    FROM AO_Transactions
                    WHERE AO_Suppliers_ID = @SupplierID AND
                            Total_Amount <> -(Payment_Amount) AND
                            To_Be_Paid <> 0 AND                    --0 = Don't pay
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                           (Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement Discount
                            Sys_AW_Transaction_Types_ID = 8 OR     --Purchase Invoice
                            Sys_AW_Transaction_Types_ID = 9 OR     --Purchase Refund
                            Sys_AW_Transaction_Types_ID = 10 OR    --Purchase Journal
                            Sys_AW_Transaction_Types_ID = 12)      --Supplier Payment
                END
            ELSE    --@AllUnflagged = 0    --0 = Insert ALL UNPAID transactions
                BEGIN
            		INSERT INTO @AO_Remittance_Details_Temp
            			(
                            AO_Remittances_Temp_ID,
                            AO_Transactions_ID,
                            AB_Accounts_ID,
                            Transaction_Date,
                            Sys_AW_Transaction_Types_ID,
                            Transaction_Number,
                            Amount,
                            Payment,
                            Settlement_Discount,
                            To_Be_Paid,
                            To_Be_Paid_Amount,
                            Remittance_Balance,
                            [User_ID],
                            AW_User_Companies_ID
                        )
                    SELECT 
                            @RemittanceID,
                            AO_Transactions_ID,
                            AB_Accounts_ID,
                            Document_Date,
                            Sys_AW_Transaction_Types_ID,
                            Document_Number,
                            Total_Amount,
                            Payment_Amount,
                            Settlement_Discount,
                            To_Be_Paid,
                            To_Be_Paid_Amount,
                            Remittance_Balance,
                            [User_ID],
                            AW_User_Companies_ID
                            
                    FROM AO_Transactions
                    WHERE AO_Suppliers_ID = @SupplierID AND
                            Total_Amount <> -(Payment_Amount) AND
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @Period1 AND
                           (Sys_AW_Transaction_Types_ID = 6 OR    --Supplier Settlement Discount
                            Sys_AW_Transaction_Types_ID = 8 OR     --Purchase Invoice
                            Sys_AW_Transaction_Types_ID = 9 OR     --Purchase Refund
                            Sys_AW_Transaction_Types_ID = 10 OR    --Purchase Journal
                            Sys_AW_Transaction_Types_ID = 12)      --Supplier Payment
                END

        --> Clear the Ageing Balances of THIS Customer
        --> In the event that the next Customers has ZERO ageing
            SET @AgePayment = 0
            SET @AgeAmount = 0
            SET @AgeCurrent = 0
            SET @Age30Days = 0
            SET @Age60Days = 0
            SET @Age90Days = 0
            SET @Age120Days = 0
            SET @Age150Days = 0
            SET @Age180Days = 0

        	FETCH NEXT FROM Supplier_Temp_Cursor 
        	INTO
                @SupplierID,
                @SupplierName,
            	@CreditLimit,
            	@CreditTerms,
            	@SettleDisc,
            	@SupplierContact,
               	@SuppTel,
            	@SuppCel,
            	@SuppFax,
                @PostBox,
                @PostOffice,
                @PostCode,
                @WorkEmail,
                @SupplierNumber

    	END
	
	CLOSE Supplier_Temp_Cursor
	DEALLOCATE Supplier_Temp_Cursor



    IF @AllUnflagged = 1    --1 = Print only flagged To_Be_Paid transactions
        BEGIN
            SELECT 
--                CONVERT(datetime, CONVERT(int, d.Transaction_Date)) AS [TransactionDate], 
                d.Transaction_Date AS [TransactionDate], 
                tt.[Description] AS [Type], 
                d.Transaction_Number AS [TransactionNo], 
                ISNULL(d.Amount, 0) AS [Amount], 
                ISNULL(d.Payment, 0) AS [Payment], 
                ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
                t.AO_Suppliers_ID AS [SupplierID], 
                t.Supplier AS [Supplier],
        		ISNULL(t.Supplier_Number, '') + '(' + CONVERT(VARCHAR(12), t.AO_Suppliers_ID) + ')' AS [SupplierNo],
            	t.Credit_Limit,
            	t.Credit_Terms,
            	t.Default_Settlement_Discount,
            	t.Supplier_Contact,
               	t.Supplier_Telephone,
            	t.Contact_Cellphone,
            	t.Supplier_Fax,
                t.Post_Box AS [SupplierPostAddress],
                t.Post_Office AS [SupplierPostOffice],
                t.Post_Code AS [SupplierPostCode],
                t.Email_Address AS [SupplierEmail],
                (ISNULL(t.[BalCurrent], 0) +
                ISNULL(t.[Bal30Days], 0) +
                ISNULL(t.[Bal60Days], 0) +
                ISNULL(t.[Bal90Days], 0) +
                ISNULL(t.[Bal120Days], 0) +
                ISNULL(t.[Bal150Days], 0) +
                ISNULL(t.[Bal180Days], 0)) AS [AccountBalance],
        --        t.Account_Balance AS [AccountBalance],
                d.To_Be_Paid AS [PayBool],
                d.Settlement_Discount AS [Settlement],
--                d.To_Be_Paid_Amount AS [ToBePaid],
                ISNULL(d.To_Be_Paid_Amount, 0) - ISNULL(d.Settlement_Discount, 0) AS [ToBePaid],
                d.Remittance_Balance AS [RemitBalance],
                t.BalCurrent AS [Current],
                t.Bal30Days AS [30Days],
                t.Bal60Days AS [60Days],
                t.Bal90Days AS [90Days],
                (ISNULL(t.Bal120Days, 0) +
                 ISNULL(t.Bal150Days, 0) +
                 ISNULL(t.Bal180Days, 0)) AS [120Days]
            FROM @AO_Remittances_Temp t 
                JOIN @AO_Remittance_Details_Temp d
                    ON t.AO_Remittances_Temp_ID = d.AO_Remittances_Temp_ID
                LEFT OUTER JOIN Sys_AW_Transaction_Types tt
                    ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
            WHERE t.AO_Suppliers_ID = @SupplierID AND
                  ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0 AND
                  d.To_Be_Paid <> 0    --0 = Don't pay
            ORDER BY [TransactionDate], [SupplierID]
        END

    ELSE    --@AllUnflagged = 0    --0 = Print ALL transactions
        BEGIN
            SELECT 
--                CONVERT(datetime, CONVERT(int, d.Transaction_Date)) AS [TransactionDate], 
                d.Transaction_Date AS [TransactionDate],  
                tt.[Description] AS [Type], 
                d.Transaction_Number AS [TransactionNo], 
                ISNULL(d.Amount, 0) AS [Amount], 
                ISNULL(d.Payment, 0) AS [Payment], 
                ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
                t.AO_Suppliers_ID AS [SupplierID], 
                t.Supplier AS [Supplier],
        		ISNULL(t.Supplier_Number, '') + '(' + CONVERT(VARCHAR(12), t.AO_Suppliers_ID) + ')' AS [SupplierNo],
            	t.Credit_Limit,
            	t.Credit_Terms,
            	t.Default_Settlement_Discount,
            	t.Supplier_Contact,
               	t.Supplier_Telephone,
            	t.Contact_Cellphone,
            	t.Supplier_Fax,
                t.Post_Box AS [SupplierPostAddress],
                t.Post_Office AS [SupplierPostOffice],
                t.Post_Code AS [SupplierPostCode],
                t.Email_Address AS [SupplierEmail],
                (ISNULL(t.[BalCurrent], 0) +
                ISNULL(t.[Bal30Days], 0) +
                ISNULL(t.[Bal60Days], 0) +
                ISNULL(t.[Bal90Days], 0) +
                ISNULL(t.[Bal120Days], 0) +
                ISNULL(t.[Bal150Days], 0) +
                ISNULL(t.[Bal180Days], 0)) AS [AccountBalance],
        --        t.Account_Balance AS [AccountBalance],
                d.To_Be_Paid AS [PayBool],
                d.Settlement_Discount AS [Settlement],
--                d.To_Be_Paid_Amount AS [ToBePaid],
                ISNULL(d.To_Be_Paid_Amount, 0) - ISNULL(d.Settlement_Discount, 0) AS [ToBePaid],
                d.Remittance_Balance AS [RemitBalance],
                t.BalCurrent AS [Current],
                t.Bal30Days AS [30Days],
                t.Bal60Days AS [60Days],
                t.Bal90Days AS [90Days],
                (ISNULL(t.Bal120Days, 0) +
                 ISNULL(t.Bal150Days, 0) +
                 ISNULL(t.Bal180Days, 0)) AS [120Days]
            FROM @AO_Remittances_Temp t 
                JOIN @AO_Remittance_Details_Temp d
                    ON t.AO_Remittances_Temp_ID = d.AO_Remittances_Temp_ID
                LEFT OUTER JOIN Sys_AW_Transaction_Types tt
                    ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
            WHERE t.AO_Suppliers_ID = @SupplierID AND
                  ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
            ORDER BY [TransactionDate], [SupplierID]
        END


SET NOCOUNT OFF


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Remittance_Summary
--Purpose       :Unpaid Supplier Transactions and Remittance Advice Summary
--Date          :2008/01/29
--Authors       :TB 
--Mods          :
--2004.5.0      :21/04/11 - Renamed @Option to @Filter and added new @Option
--              :           to show ALL or transactions marked to pay
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AO_Supplier_Remittance_Summary
    (
        @CompanyID int,
        @Option tinyint,
        @Filter tinyint,
        @MonthID tinyint,
        @YearID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6)


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID as [CompanyID], '

    IF @Filter = 0
        SET @sql = @sql +
            ' o.Lup_AO_Supplier_Types_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '
    ELSE
    IF @Filter = 1
        SET @sql = @sql +
            ' o.Lup_AO_Supplier_Groups_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '
    ELSE
    IF @Filter = 2
        SET @sql = @sql +
            ' o.Sys_AC_Account_Status_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '

    SET @sql = @sql + ' t.AO_Suppliers_ID AS [Supplier_ID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Supplier], '
    SET @sql = @sql + ' t.Document_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(datetime, CONVERT(CHAR(10), t.Document_Date, 121)) AS [Date], '
    SET @sql = @sql + ' m.[Description] AS [Month], '
    SET @sql = @sql + ' y.[Description] AS [Year], '
    SET @sql = @sql + ' t.AO_GRV_ID AS [GRV], '
    SET @sql = @sql + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) AS [Total], '
    SET @sql = @sql + ' ISNULL(t.Payment_Amount, 0) AS [Paid], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Owing], '
    SET @sql = @sql + ' ISNULL(t.Settlement_Discount, 0) AS [Settlement], '
    SET @sql = @sql + ' ISNULL(t.To_Be_Paid, 0) AS [Post], '
    SET @sql = @sql + ' ISNULL(t.To_Be_Paid_Amount, 0) AS [Payable], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) - ISNULL(t.To_Be_Paid_Amount,0) + ISNULL(t.Settlement_Discount,0) AS [Outstanding] '
    SET @sql = @sql + ' FROM AO_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID '

    IF @Filter = 0
        SET @sql = @sql +
            '     LEFT JOIN Lup_AO_Supplier_Types o ' +
            '         ON s.Lup_AO_Supplier_Types_ID = o.Lup_AO_Supplier_Types_ID '
    ELSE
    IF @Filter = 1
        SET @sql = @sql +
            '     LEFT JOIN Lup_AO_Supplier_Groups o ' +
            '         ON s.Lup_AO_Supplier_Groups_ID = o.Lup_AO_Supplier_Groups_ID '
    ELSE
    IF @Filter = 2
        SET @sql = @sql +
            '     LEFT JOIN Sys_AC_Account_Status o ' +
            '         ON s.Sys_AC_Account_Status_ID = o.Sys_AC_Account_Status_ID '

    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '      (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND '
    SET @sql = @sql + '      (t.Sys_AW_Transaction_Types_ID = 6 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 8 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 9 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 10) AND '
    SET @sql = @sql + '       dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''


    IF @Option = 1
        BEGIN
            SET @sql = @sql + '   AND t.To_Be_Paid = 1 '
        END


    SET @sql = @sql + ' ORDER BY [HeaderID], [Supplier], [Date] '


    EXEC (@sql)


SET NOCOUNT OFF

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Remittances_Temp
--Purpose       :Retrieves Ad-Hoc Supplier Remittance data in Remittance Report
--Tables        :AO_Remittances_Temp, AO_Remittance_Details_Temp
--Parameters    :
--Date          :2002/06/20
--Authors       :TB
--Version       :1.0.0
--MODS          :17/07/02 - Inserted @AllUnflagged to INSERT ALL transactions
--              :           or only FLAGGED (for payment) transactions
--              :25/10/02 - Removed CONVERT(datetime, CONVERT(int, d.Transaction_Date))
--              :           This expression ROUNDS UP dates after 12 noon to NEXT DAY
--              :17/12/03 - Added NEW Settlement_Discount field in AO_Transactions
--              :24/07/04 - Added [Month] and [Year] fields - Autowiel
--              :24/10/04 - Changed SORT ORDER to d.Transaction_Number, d.Transaction_Date
--              :           instead of d.Transaction_Date only to assist with recons
--              :24/10/04 - Changed to new DYNAMIC format
--              :13/11/04 - Added Supplier Name (t.Supplier) as PRIMARY sort order
--              :13/11/04 - Replaced t.Supplier with t.Supplier_Number in [SupplierNo]
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AO_Supplier_Remittances_Temp
    (
        @PeriodProceduresID int,
        @AllUnflagged bit,
        @SortOrder tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '
--    SET @sql = @sql + '     CONVERT(datetime, CONVERT(int, d.Transaction_Date)) AS [TransactionDate], '

    SET @sql = @sql + '     d.Transaction_Date AS [TransactionDate], '
    SET @sql = @sql + '     tt.[Description] AS [Type], '
    SET @sql = @sql + '     d.Transaction_Number AS [TransactionNo], '
    SET @sql = @sql + '     ISNULL(d.Amount, 0) AS [Amount], '
    SET @sql = @sql + '     ISNULL(d.Payment, 0) AS [Payment], '
    SET @sql = @sql + '     ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], '
    SET @sql = @sql + '     t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + '     t.Supplier AS [Supplier], '
    SET @sql = @sql + '     ISNULL(t.Supplier_Number, '''') +
                             ''('' + CONVERT(VARCHAR(10), t.AO_Suppliers_ID) + '') ''
                              AS [SupplierNo], '
    SET @sql = @sql + '     t.Credit_Limit, '
    SET @sql = @sql + '     t.Credit_Terms, '
    SET @sql = @sql + '     t.Default_Settlement_Discount, '
    SET @sql = @sql + '     t.Supplier_Contact, '
    SET @sql = @sql + '     t.Supplier_Telephone, '
    SET @sql = @sql + '     t.Contact_Cellphone, '
    SET @sql = @sql + '     t.Supplier_Fax, '
    SET @sql = @sql + '     t.Post_Box AS [SupplierPostAddress], '
    SET @sql = @sql + '     t.Post_Office AS [SupplierPostOffice], '
    SET @sql = @sql + '     t.Post_Code AS [SupplierPostCode], '
    SET @sql = @sql + '     t.Email_Address AS [SupplierEmail], '
    SET @sql = @sql + '     (ISNULL(t.[Current], 0) + '
    SET @sql = @sql + '      ISNULL(t.[30Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[60Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[90Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[120Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[150Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[180+Days], 0)) AS [AccountBalance], '
--    SET @sql = @sql + '     t.Account_Balance AS [AccountBalance], '
    SET @sql = @sql + '     d.To_Be_Paid AS [PayBool], '
    SET @sql = @sql + '     d.Settlement_Discount AS [Settlement], '
--    SET @sql = @sql + '     d.To_Be_Paid_Amount AS [ToBePaid], '
    SET @sql = @sql + '     ISNULL(d.To_Be_Paid_Amount, 0) - ISNULL(d.Settlement_Discount, 0) AS [ToBePaid], '
    SET @sql = @sql + '     d.Remittance_Balance AS [RemitBalance], '
    SET @sql = @sql + '     t.[Current], '
    SET @sql = @sql + '     t.[30Days], '
    SET @sql = @sql + '     t.[60Days], '
    SET @sql = @sql + '     t.[90Days], '
    SET @sql = @sql + '     (ISNULL(t.[120Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[150Days], 0) + '
    SET @sql = @sql + '      ISNULL(t.[180+Days], 0)) AS [120+Days], '
    SET @sql = @sql + '     m.[Description] AS [Month], '
    SET @sql = @sql + '     y.[Description] AS [Year] '

    SET @sql = @sql + ' FROM AO_Remittances_Temp t '
    SET @sql = @sql + '     JOIN AO_Remittance_Details_Temp d '
    SET @sql = @sql + '         ON t.AO_Remittances_Temp_ID = d.AO_Remittances_Temp_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '         ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     INNER JOIN AO_Transactions st '
    SET @sql = @sql + '         ON d.AO_Transactions_ID = st.AO_Transactions_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON st.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON st.Slu_AW_Years_ID = y.Slu_AW_Years_ID '
    SET @sql = @sql + ' WHERE t.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @PeriodProceduresID) + ' '
    SET @sql = @sql + '   AND ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0 '


    IF @AllUnflagged = 1    -- 1 = Print only flagged transactions
        BEGIN
            SET @sql = @sql + '  AND d.To_Be_Paid <> 0 '
        END


    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY t.Supplier, t.AO_Suppliers_ID, d.Transaction_Number '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY t.Supplier, t.AO_Suppliers_ID, d.Transaction_Date '
        END
    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY t.Supplier, t.AO_Suppliers_ID, st.Slu_AW_Years_ID, st.Slu_AW_Months_ID, d.Transaction_Date '
        END


    EXEC (@sql)






SET NOCOUNT OFF










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Transactions_Audit_Trail
--Purpose       :Supplier Transactions Audit Trail Report
--Date          :2003/12/15
--Authors       :TB
--Version       :1.0.0
--MODS:         :28/10/04 - Added Accounting Period filter
--V6.4	RL	2018-04-19	:Hide Zero transaction payments that are created by the system!!!!
-------------------------------------------------------------------------------
--EXEC sp_RPT_AO_Transactions_Audit_Trail 1, 1, 118, 0, '2004/07/30 12:00:01 AM', '2004/10/28 11:59:59 PM', 1, 10, 5
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Transactions_Audit_Trail]
    (
            @CompanyID int,
            @ChkAllSuppliers int,
            @SupplierID int,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime,
            @ChkPeriod int,
            @MonthID tinyint,
            @YearID int
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllSuppliers = 1
-- SET @SupplierID = 1627
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(7000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Date_Captured, 121) AS [CalDay], '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + ' t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Document_Date, 121) AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [TranType], '
    SET @sql = @sql + ' t.Document_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(t.Supplier_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(t.Comment, '''') AS [Comment], '

--     SET @sql = @sql + ' LEFT(ISNULL(gl.Description, ''''), 20) AS [GL Account], '
--     SET @sql = @sql + ' gl.[Description] AS [GL Account], '
--    SET @sql = @sql + ' ISNULL(glt.Transaction_Code, '''') AS [GLTranType], '
--     SET @sql = @sql + ' gt.AB_Source_Ref AS [Ref No], '
--     SET @sql = @sql + ' gt.AB_Transaction_Date AS [Date], '
--     SET @sql = @sql + ' m.[Description] AS [Month], '
--     SET @sql = @sql + ' y.[Description] AS [Year], '
--     SET @sql = @sql + ' gt.[Description] AS [Description], '
--     SET @sql = @sql + ' gt.AB_Transaction_Amount AS [Amount], '

    SET @sql = @sql + ' ISNULL(t.Trade_Discount_Total, 0) + ISNULL(t.Rebate_Discount_Total, 0) + ISNULL(t.Other_Discount_Total, 0) AS [Discount], '
    SET @sql = @sql + ' t.Net_Amount AS [Amount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AO_Transactions t '
    SET @sql = @sql + '      LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '          ON s.AO_Suppliers_ID = t.AO_Suppliers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '
--     SET @sql = @sql + '      LEFT JOIN AB_GL_Transactions gt '
--     SET @sql = @sql + '      	 ON t.AO_Transactions_ID = gt.AB_Transaction_Ref '
--     SET @sql = @sql + '      LEFT JOIN AB_Accounts gl '
--     SET @sql = @sql + '          ON t.AB_Accounts_ID = gl.AB_Accounts_ID '
--     SET @sql = @sql + '      LEFT JOIN Sys_AB_Transaction_Types glt '
--     SET @sql = @sql + '          ON gt.Sys_AB_Transaction_Types_ID = glt.Sys_AB_Transaction_Types_ID '
--     SET @sql = @sql + '      INNER JOIN Slu_AW_Months m '
--     SET @sql = @sql + '      	 ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
--     SET @sql = @sql + '      INNER JOIN Slu_AW_Years y '
--     SET @sql = @sql + '      	 ON t.Slu_AW_Years_ID  = y.Slu_AW_Years_ID '

    SET @sql = @sql +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '   (t.Sys_AW_Transaction_Types_ID = 6 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 8 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 9 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 10 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 11 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 12) '

--         '   (gt.Sys_AB_Transaction_Types_ID = 5 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 6 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 7 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 8 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 25) '

    IF @ChkAllSuppliers = 0        --Single Supplier Account
        BEGIN
            SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' '
        END


    IF @ChkDates = 1               --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Document_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Document_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    IF @ChkPeriod = 1              --Accounting Period
        BEGIN
            SET @sql = @sql + '  AND t.Slu_AW_Months_ID = ' + '''' + CONVERT(varchar(20), @MonthID) + '''' + ' '
            SET @sql = @sql + '  AND t.Slu_AW_Years_ID = ' + '''' + CONVERT(varchar(30), @YearID) + '''' + ' '
        END


		--V6.4 RL Hide Zero transaction payments that are created by the system!!!!
		SET @sql = @sql + 'AND t.AO_Transactions_ID NOT IN (SELECT AO_Transactions_ID FROM AO_Transactions WHERE Sys_AW_Transaction_Types_ID = 12 And Total_Amount = 0)'

    SET @sql = @sql + ' ORDER BY t.Date_Captured ASC '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















--sp_RPT_AP_Barcode_Labels 1, -1, 8, -1, -1, -1, -1, 0, 0, 0
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Barcode_Labels
--Purpose       :Inventory Barcode Labels
--Date          :2005/10/18
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AP_Barcode_Labels
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(4000),
            @SQL varchar(4000)

	SET @Filter = ''
    SET @SQL = ''


    	IF @SupplierID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    		END
    --> Manufacturer
    	IF @ManufacturerID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    		END
    --> Type
    	IF @TypeID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    		END
    --> Group
    	IF @GroupID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    		END
    --> Department
    	IF @DepartmentID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    		END
    --> Location
    	IF @LocationID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
        	END

		IF @Filter = ''
            BEGIN
				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
				SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END

        IF @OnHandOnly = 1
            BEGIN
    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                    convert(varchar(20), @CompanyID) +
                                  ' AND ' + ' p.On_Hand <> 0 '
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.On_Hand <> 0 '
            END


        IF @NonStock = 1
            BEGIN
                SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Description], '
        SET @SQL = @SQL + ' p.Product_Code AS [ProductCode], '
        SET @SQL = @SQL + ' p.On_Hand AS [OnHand], '
        SET @sql = @sql + ' ISNULL(p.Product_Code, '''') '
        SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')'' AS [CompositeCode] '
        SET @SQL = @SQL + ' FROM AP_Products p '
        SET @SQL = @SQL + @Filter

        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY p.[Description] '
            END


    EXEC (@SQL)



SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :[sp_RPT_AP_Barcode_Labels_Print]
--Purpose       :Barcode Labels Print
--Date          :2013/07/17
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Barcode_Labels_Print]
	(
    	@CompanyID int,
    	@AP_Products_ID int,
    	@AO_GRV_ID int,
        @Qty int
	)
AS

SET NOCOUNT ON

	DECLARE @Filter varchar(4000),
            @SQL varchar(4000),
            @NonStock int,
            @Sort int

	SET @Filter = ''
    SET @SQL = ''
	SET @NonStock = 0
	SET @Sort = 0
		
	SELECT @NonStock = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarExcludeNoNStock'

	SELECT @Sort = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarOrdProductCode'

	IF @Filter = ''
    BEGIN
		SET @Filter = ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
	END
	ELSE
	BEGIN
		SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
	END

	IF @NonStock = 1
	BEGIN
		SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
	END

	IF @AP_Products_ID <> 0
	BEGIN
    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Description], '
        SET @SQL = @SQL + ' p.Product_Code AS [ProductCode], '
        SET @SQL = @SQL + ' ''' + CONVERT(varchar(20), @Qty) + ''' AS [OnHand], '
        SET @sql = @sql + ' ISNULL(p.Product_Code, '''') '
        SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')'' AS [CompositeCode] '
        SET @SQL = @SQL + ' FROM AP_Products p '
        --SET @SQL = @SQL + ' WHERE p.AP_Products_ID = Cast( ''' + @AP_Products_ID + ''',varchar(10))'
        SET @SQL = @SQL + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(20), @AP_Products_ID) + ''
        SET @SQL = @SQL + ' AND IsNull(p.Slu_AW_YesNo_Levy_Item,0) = 0 '
       
        SET @SQL = @SQL + @Filter
    END    
	ELSE
	BEGIN
    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Description], '
        SET @SQL = @SQL + ' p.Product_Code AS [ProductCode], '
        SET @SQL = @SQL + ' d.Qty AS [OnHand], '
        SET @sql = @sql + ' ISNULL(p.Product_Code, '''') '
        SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')'' AS [CompositeCode] '
        SET @SQL = @SQL + ' FROM AP_Products p '
        SET @SQL = @SQL + ' INNER JOIN AO_GRV_Details d ON '
        SET @SQL = @SQL + ' p.AP_Products_ID = d.AP_Products_ID '        
        SET @SQL = @SQL + ' INNER JOIN AO_GRV g ON '
        SET @SQL = @SQL + ' g.AO_GRV_ID = d.AO_GRV_ID '        
        --SET @SQL = @SQL + ' WHERE g.AO_GRV_ID = Cast( ''' + @AO_GRV_ID + ''' ,varchar(10)) +'
        SET @SQL = @SQL + ' WHERE g.AO_GRV_ID = ' + CONVERT(varchar(20), @AO_GRV_ID) +''
        SET @SQL = @SQL + ' AND IsNull(p.Slu_AW_YesNo_Levy_Item,0) = 0 '               
        SET @SQL = @SQL + @Filter		
	END
        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY p.[Description] '
            END


    EXEC (@SQL)
    --Select @SQL

SET NOCOUNT OFF	



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Bin_Allocation_History
--Purpose       :Returns Bin Allocation History
--Date          :2016-07-27
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Bin_Allocation_History]
    (
        @FromBin_ID			int,
        @ToBin_ID			int,        
        @FromDate			datetime,
        @ToDate				datetime,
        @CompanyID			int
    )
AS

SET NOCOUNT ON

IF ( (@FromBin_ID = 0) AND (@ToBin_ID = 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
END

IF ( (@FromBin_ID <> 0) AND (@ToBin_ID <> 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	AND h.From_Lup_AP_Product_Bins_ID = @FromBin_ID
	AND h.To_Lup_AP_Product_Bins_ID = @ToBin_ID
END

IF ( (@FromBin_ID = 0) AND (@ToBin_ID <> 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	AND h.To_Lup_AP_Product_Bins_ID = @ToBin_ID	
END

IF ( (@FromBin_ID <> 0) AND (@ToBin_ID = 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	AND h.From_Lup_AP_Product_Bins_ID = @FromBin_ID	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Cardex_Print
--Purpose       :Product Cardex print fro ONE Product
--Functionality :    uses UNION ALL
--Date          :2004/10/22
--Authors       :TB
--MODS:         :
--2004.3.4      :08/03/07 - Replaced gh.Supplier_Reference with
--              :           gh.Delivery_Note_Number to show Supplier Invoice Number
--2004.3.9      :13/06/08 - Changed [Supplier/Customer] field in ADJUSTMENTS section
--              :           and inserted [Note] from AP_Inventory_Adjustments table
--2004.4.2      :23/10/08 - Change SALES section from Sales Cost to Selling Price - RM
--              :           and [Cost] to [Total]
--2004.5.1      :02/06/11 - Added h.Sys_AW_Transaction_Types_ID = 29 as 'GRVFAC'
--              :           in GOODS RECEIVED for Casing Tracking Factory GRV's
--              :15/06/11 - Added h.Sys_AW_Transaction_Types_ID = 23 as 'TRF IN/OUT'
--              :           in SALES section CASE statement for [TYPE] field
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 31 as 'CRV' and 
--              :            h.Sys_AW_Transaction_Types_ID = 32 as 'CRN' for consignment stock
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 33 as 'CON N' and 
--							h.Sys_AW_Transaction_Types_ID = 34 as 'CON S' and 
--              :           h.Sys_AW_Transaction_Types_ID = 35 as 'CON R' for consignment stock sales
--V6.3	RL	:2016-06-07		Changed fn_AP_BFWD_Inventory_On_Hand to only call once. Speed issue
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Cardex_Print]

    (
        @StartDate as datetime,
        @ProductID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql			Varchar(8000)
    DECLARE @BFWD			Decimal(9,3)
    DECLARE @DefaultBin		Varchar(50)    

-- SET @StartDate = '2002/01/01 00:00:01'
-- SET @ProductID = 1

	SELECT @DefaultBin = [Description]
	FROM Lup_AP_Product_Bins
	WHERE Lup_AP_Product_Bins_ID = 1

	IF ISNULL(@DefaultBin,'') = ''
		SET @DefaultBin = '<None>'

-------------------------------------------------------------------------------
-- GOODS RECEIVED
-------------------------------------------------------------------------------

	SELECT @BFWD = dbo.fn_AP_BFWD_Inventory_On_Hand(@ProductID, @StartDate)

    SET @sql = ' SELECT '
    SET @sql = @sql + '     gd.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     gd.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    --GRVs always done to and from default bin
    SET @sql = @sql + '''' + @DefaultBin + '''' + ' AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN gh.Sys_AW_Transaction_Types_ID = 19 '
    SET @sql = @sql + '          THEN ''GRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 20 '
    SET @sql = @sql + '          THEN ''RETURN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '          THEN ''GRVFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 30 '
    SET @sql = @sql + '          THEN ''GRNFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 31 '
    SET @sql = @sql + '          THEN ''CRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 32 '
    SET @sql = @sql + '          THEN ''CRN'' '        
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 34 '
    SET @sql = @sql + '          THEN ''CON S'' '        
    SET @sql = @sql + '          ELSE ''NOGRV'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     gh.Date_Received AS [Date], '

    SET @sql = @sql + '     ISNULL(gh.Delivery_Note_Number, '''') '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), gh.AO_GRV_ID) + '')'' AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     ISNULL(gd.Qty, 0) AS [Qty], '

    SET @sql = @sql + '     ISNULL(gd.Unit_Price, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ISNULL(gd.Net_Amount, 0) AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AO_GRV_Details gd '
    SET @sql = @sql + '         ON p.AP_Products_ID = gd.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_GRV gh '
    SET @sql = @sql + '         ON gd.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON gh.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON gh.[User_ID] = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE gd.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND gd.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (gh.Sys_AW_Transaction_Types_ID = 19 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 20 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 29 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 30 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 31 ' + ' '        
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 32 ' + ' '            
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 34) ' + ' '   


    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- ADJUSTMENTS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ISNULL(a.Note, '''') AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN a.Sys_AP_Adjustment_Types_ID = 1 '
    SET @sql = @sql + '          THEN ''ADJUST'' '
    SET @sql = @sql + '          WHEN a.Sys_AP_Adjustment_Types_ID = 6 '
    SET @sql = @sql + '          THEN ''TAKEON'' '
    SET @sql = @sql + '          ELSE ''NOADJ'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '

    SET @sql = @sql + '     CONVERT(varchar(10), a.AP_Inventory_Adjustments_ID) AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '        
    SET @sql = @sql + '     ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) AS [Qty], '

    SET @sql = @sql + '     ISNULL(a.New_Last_Cost, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ROUND((ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0)) * ISNULL(a.New_Last_Cost, 0), 2) AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Inventory_Adjustments a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE a.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (a.Sys_AP_Adjustment_Types_ID = 1 ' + ' '
    SET @sql = @sql + '     OR a.Sys_AP_Adjustment_Types_ID = 6) ' + ' '
    SET @sql = @sql + '   AND ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) <> 0 ' + ' '


    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- SALES
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     d.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     d.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('', '' + c.Firstnames, ''''))) AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''SALE'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''REFUND'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) < 0) '
    SET @sql = @sql + '          THEN ''TRF IN'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) >= 0) '
    SET @sql = @sql + '          THEN ''TRF OUT'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 33  '
    SET @sql = @sql + '          THEN ''CON N'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 34  '
    SET @sql = @sql + '          THEN ''CON S'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 35  '    
    SET @sql = @sql + '          THEN ''CON R'' '    
    SET @sql = @sql + '          ELSE ''NOSALE'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     h.Transaction_Date AS [Date], '
    SET @sql = @sql + '     h.Transaction_Number AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     (ISNULL(d.Quantity, 0) * -1) AS [Qty], '

    SET @sql = @sql + '     CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '          THEN ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) / ISNULL(d.Quantity, 0), 2) '
    SET @sql = @sql + '          ELSE 0 '
    SET @sql = @sql + '     END AS [UnitPrice], '
    SET @sql = @sql + '     ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)), 2) AS [Total], '

    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + '         ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN dbo.AC_Customers c '
    SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON d.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE d.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND d.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 23 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 33 OR '    
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 34 OR '            
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 35) '   

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations From Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '        
    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     a.Date_Captured AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     ISNULL(a.From_Bin_New_On_Hand, 0) - ISNULL(a.From_Bin_Previous_On_Hand, 0) AS [Qty], '

    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.From_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations To Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '        
    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     a.Date_Captured AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     ISNULL(a.To_Bin_New_On_Hand, 0) - ISNULL(a.To_Bin_Previous_On_Hand, 0) AS [Qty], '

    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.To_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' ORDER BY [CompanyID], [Date Captured] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :[sp_RPT_AP_Consignment_Valuation]
--Purpose       :Selects ALL Consignment Products
--Date          :2015/07/20
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Consignment_Valuation]
    (
        @Option varchar(20),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT p.Product_Code As [Code], '
    SET @sql = @sql + ' p.AP_Products_ID AS [Products_ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    --SET @sql = @sql + ' p.Last_Cost AS [LastUnitCost], '
    --SET @sql = @sql + ' p.Average_Cost AS [AvgUnitCost], '
    --SET @sql = @sql + ' p.Standard_Cost AS [StdUnitCost], '    

    --SET @sql = @sql + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) AS [Qty], '
    --SET @sql = @sql + ' CONVERT(money, (p.Last_Cost * t.Qty) ) AS [Last Cost], '
    --SET @sql = @sql + ' CONVERT(money, (p.Average_Cost * t.Qty) ) AS [Avg Cost], '
    --SET @sql = @sql + ' CONVERT(money, (p.Standard_Cost * t.Qty) ) AS [Std Cost], '
    
    SET @sql = @sql + ' SUM(d.Qty_Left) AS [Qty], '
    SET @sql = @sql + ' CONVERT(Money, (SUM(dbo.fn_AP_Get_Products_Out_On_Consignment(d.AP_Products_ID)) )) AS [ConsQtyOut], '    
    SET @sql = @sql + ' CONVERT(Money, (SUM(d.Qty_Left) - SUM(dbo.fn_AP_Get_Products_Out_On_Consignment(d.AP_Products_ID)) )) As [QtyInStore], '
    SET @sql = @sql + ' SUM(d.Qty_Left * d.Unit_Price) AS [Total Cost], '    
    SET @sql = @sql + ' p.Price1_Price1 AS [Price1], '
    SET @sql = @sql + ' SUM(d.Qty_Left * p.Price1_Price1) AS [Total Selling], '
    SET @sql = @sql + ' CASE WHEN SUM(d.Qty_Left * p.Price1_Price1) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (SUM(d.Qty_Left * p.Price1_Price1) - SUM(d.Qty_Left * d.Unit_Price)) / (SUM(d.Qty_Left * p.Price1_Price1) ) * 100  ) '    
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg GP%], '

    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] '

    SET @sql = @sql + ' FROM AO_GRV m '
    SET @sql = @sql + '		INNER JOIN AO_GRV_Details d '
    SET @sql = @sql + '			ON m.AO_GRV_ID = d.AO_GRV_ID '
    SET @sql = @sql + '		INNER JOIN AP_Products p '    
    SET @sql = @sql + '			ON p.AP_Products_ID = d.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 m.AO_Suppliers_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 '

    SET @sql = @sql +
        ' WHERE m.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        ' m.Sys_AW_Transaction_Types_ID = 31 AND ' +
        ' d.Qty_Left <> 0 '

    SET @sql = @sql + ' GROUP BY p.Product_Code, p.AP_Products_ID, p.[Description], p.Price1_Price1, '
    
    
    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID, ' +
            ' o.[Description] '
    ELSE
    IF @Option = 'Group'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID, ' +
            ' o.[Description] '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID, ' +
            ' o.[Description] '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID, ' +
            ' o.[Supplier_Name] '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID, ' +
            ' o.[Description] '

    
    SET @sql = @sql + ' ORDER BY [HeaderID] '

EXEC (@sql)

--Select @sql

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Disabled_Products
--Purpose       :Retrieves products that have been disabled
--Date          :2004/02/03
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AP_Disabled_Products

    (
        @Filter varchar(30),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '
    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL], '
    SET @sql = @sql + ' ISNULL(p.Min_Order_Qty, 0) AS [Min], '
    SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) AS [Max], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' CONVERT(CHAR(10), p.Last_Sale_Date , 121) AS [LastSale], '

    SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [LastCost], '
    SET @sql = @sql + ' act.[Description] AS [Active] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active act ' +
                      '         ON p.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

--ORIG VERSION
-----------------------------------------------------
    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID <> 1 '
    SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '

    SET @sql = @sql + ' ORDER BY [Filter], [Description] '

--PRINT @sql

EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Slow_Moving_Stock
--Purpose       :Fetch Enterprise Slow Moving Stock
--Date          :2006/10/05
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AP_Enterprise_Slow_Moving_Stock
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Slow_Moving_Stock '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Stock
--Purpose       :Fetch Enterprise Stock
--Date          :2006/05/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AP_Enterprise_Stock
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Stock '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Stock_Filter
--Purpose       :Fetch Enterprise Stock Filter data
--Date          :2006/09/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AP_Enterprise_Stock_Filter
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Stock_Filter '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Stock_MSL
--Purpose       :Fetch Enterprise Stock
--Date          :2008/12/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AP_Enterprise_Stock_MSL
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Stock_MSL '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Stock_Replenish
--Purpose       :Fetch Enterprise Stock Replenishment
--Date          :2008/12/29
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AP_Enterprise_Stock_Replenish
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Stock_Replenish '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Stock_Replenish_Max
--Purpose       :Fetch Enterprise Stock Replenishment Max Order Qty
--Date          :2009/07/23
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AP_Enterprise_Stock_Replenish_Max
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Stock_Replenish_Max '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Enterprise_Stock_Valuation
--Purpose       :Fetch Enterprise Stock Valuation
--Date          :2006/09/18
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AP_Enterprise_Stock_Valuation
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AP_Enterprise_Stock_Valuation '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Gross_Profit_Analysis
--Purpose       :Product Margin Analysis
--Date          :2004/07/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AP_Gross_Profit_Analysis

    (
        @Filter varchar(30),
        @SortOrder tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    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 + ' CONVERT(CHAR(10), dbo.GetEffectiveDate(p.Price1_Effective_Date, p.Price2_Effective_Date, getdate()) , 121) AS [Effective], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) as [Unit Price], '
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg Cost], '

    SET @sql = @sql + ' CONVERT(money, (dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) - p.Last_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) - p.Last_Cost) / dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%] '

    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
                      '       AND p.Slu_AW_Active_ID = 1 '


    IF @SortOrder = 0
        SET @sql = @sql + ' ORDER BY [Filter], [Description] '
    ELSE
    IF @SortOrder = 1
        SET @sql = @sql + ' ORDER BY [Filter], [Code] '


--PRINT @sql

EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Adjustments
--Purpose       :Retrieves filtered list of Inventory Adjustments
--Date          :2004/01/08
--Authors       :TB
--MODS          :24/02/06 - New Dynamic definition with COMMON code section
--2004.4.1      :29/09/08 - Modified Product Filter behaviour to show adjustments 
--              :           listed by ALL filters applicable to selected filter
--2004.4.2      :16/11/08 - Added @AdjustType AGAIN !!!!
--2004.4.3      :21/02/09 - Modified ORDER BY from [ORDER BY a.Date_Captured] to
--              :           [ORDER BY [Product], [Date]] to match NEW Stock Take 
--V6.0	RL	2014-09-01	:Goods Returned as an option
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Adjustments]
    (
        @CompanyID int, 
        @AdjustType tinyint,
        @SearchFilter int,
        @SearchDescription varchar(50),
        @chkDateRange tinyint,
        @StartDate datetime,
        @EndDate datetime,
        @NonStock tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @SearchDescription = RTRIM(LTRIM(@SearchDescription))


    SET @sql = ' SELECT '

    IF @SearchFilter = 3
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 4
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 5
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 1
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @SearchFilter = 2
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 6
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' a.AP_Inventory_Adjustments_ID AS [ID], '
    SET @sql = @sql + ' dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period], '
    SET @sql = @sql + ' a.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' p.[Description] AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' t.[Description] AS [Type], '
    SET @sql = @sql + ' a.Note AS [Note], '
    SET @sql = @sql + ' a.Previous_On_Hand AS [Prev O/H], '
    SET @sql = @sql + ' a.New_On_Hand AS [New O/H], '
    SET @sql = @sql + ' a.Previous_Last_Cost AS [Prev Last Cost], '
    SET @sql = @sql + ' a.New_Last_Cost AS [New Last Cost], '
    SET @sql = @sql + ' a.Previous_Average_Cost AS [Prev Ave. Cost], '
    SET @sql = @sql + ' a.New_Average_Cost AS [New Ave. Cost], '
    SET @sql = @sql + ' (ISNULL(a.New_Last_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Last_Cost, 0) * ISNULL(a.Previous_On_Hand, 0)) AS [Last Cost Val], '
    SET @sql = @sql + ' (ISNULL(a.New_Average_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Average_Cost, 0) * ISNULL(a.Previous_On_Hand, 0)) AS [Ave. Cost Val], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' u.UserName AS [User] '

    SET @sql = @sql + ' FROM AP_Inventory_Adjustments a '
    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + '         ON a.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AP_Adjustment_Types t '
    SET @sql = @sql + '         ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '


    IF @SearchFilter = 3
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @SearchFilter = 4
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @SearchFilter = 5
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @SearchFilter = 1
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @SearchFilter = 2
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @SearchFilter = 6
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)


    IF @AdjustType = 1
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 1 '
        END
    ELSE
    IF @AdjustType = 2
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 2 '
        END
    ELSE
    IF @AdjustType = 3
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 3 '
        END
    ELSE
    IF @AdjustType = 4
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 4 '
        END
    ELSE
    IF @AdjustType = 5
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 5 '
        END
    ELSE
    IF @AdjustType = 6
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 6 '
        END
    ELSE
    IF @AdjustType = 7
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 7 '
        END

    IF @SearchFilter = 7        --> PRODUCT DESCRIPTION SEARCH
        BEGIN
            SET @sql = @sql + ' AND (p.[Description] LIKE ''%' + @SearchDescription + '%'' OR '
            SET @sql = @sql + '      p.Product_Code LIKE ''%' + @SearchDescription + '%'' ) '
        END


    IF @chkDateRange = 1   --Use Date Range
        BEGIN
            SET @sql = @sql + ' AND (a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + ' AND  a.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ') '
        END


    IF @NonStock = 1       --Exclude Non-Stock Items
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


--    SET @sql = @sql + ' ORDER BY a.Date_Captured '
    SET @sql = @sql + ' ORDER BY [Product], [Date] '


    EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Analysis
--Purpose       :Retrieves Product Sales Usage Analysis for last 12 months
--Functionality :Uses TABLE datatype
--              :    Conditional upon:
--              :        Has_Sales OR
--              :        Has On_Hand <> 0 OR
--              :        Has Min_Stock_Level <> 0 OR
--              :        Has Min_Order_Qty <> 0 OR
--              :        Has Max_Order_Qty <> 0 OR
--              :        Has_Orders AND
--              :        IS Active
--Date          :2003/04/11
--Authors       :TB
--Version       :1.0.0
--MODS:         :01/05/03 - Modified WHERE clause bracket ALL the OR conditions
--              :           including SALES
--              :20/10/03 - Modified to improve execution speed by 25x by using
--              :           TempTable instead of correlated subquery
--              :23/10/03 - Modified to use TABLE datatype instead of a #TempTable
--              :           and now selects ORDERS from SALES instead of SALES
--              :           from ORDERS which improves execution speed a further 2x
--              :26/12/04 - Added AW_User_Companies_ID = @CompanyID - Was = 1
--2004.2.7      :20/02/05 - Added a WHERE filter to EXCLUDE INACTIVE products
--2004.3.4      :19/11/06 - Added SortOrder input parameter
--2004.3.5      :09/06/07 - Added NonStock input parameter
--2004.5.9 RL	:2013-07-15 Added Average_Cost, Price1_Price1, Price1_Price2 
--							For new report Invetory Analysis Condesed Report For Autoweil
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Analysis]
    (
        @Filter varchar(30),
        @EndDate datetime,
        @SortOrder tinyint,
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6),
        @chkNonStock tinyint = 1
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartDate datetime

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @EndDate = '2003/90/30 23:59:59'
-- SET @Jan = '012003'
-- SET @Feb = '022003'
-- SET @Mar = '032003'
-- SET @Apr = '042003'
-- SET @May = '052003'
-- SET @Jun = '062003'
-- SET @Jul = '072003'
-- SET @Aug = '082003'
-- SET @Sep = '092003'
-- SET @Oct = '102002'
-- SET @Nov = '112002'
-- SET @Dec = '122002'

    SET @StartDate = DATEADD(yy, -1, @EndDate)


    ---------------------------------------------
    --> NEW 23/10/03 using TABLE datatype
    ---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AP_Products_Temp]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AP_Products_Temp]

    DECLARE @ActiveProducts table
                (
                    [AP_Products_ID] int
                )

    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AS_Transaction_Details
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AO_Order_Details od
        INNER JOIN AO_Orders oh
            ON od.AO_Orders_ID = oh.AO_Orders_ID
    WHERE oh.AW_User_Companies_ID = @CompanyID AND
          oh.Slu_AW_Active_ID = 1 AND
          oh.Date_Ordered IS NOT NULL AND
          oh.Complete <> 1 AND
         (ISNULL(od.Order_Qty, 0) + ISNULL(od.Back_Order_Qty, 0) - ISNULL(od.Received_Qty, 0)) > 0
--      AND dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AP_Products
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          (
              On_Hand <> 0 OR
              Min_Stock_Level <> 0 OR
              Min_Order_Qty <> 0 OR
              Max_Order_Qty <> 0
          )


    SELECT DISTINCT AP_Products_ID
    INTO AP_Products_Temp
    FROM @ActiveProducts
    ORDER BY AP_Products_ID

---------------------------------------------


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Description], '
    SET @sql = @sql + ' ISNULL(p.Product_Code, '''') AS [Code], '
    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '
    SET @sql = @sql + ' p.Min_Stock_Level AS [MSL], '
    SET @sql = @sql + ' p.Min_Order_Qty AS [Min], '
    SET @sql = @sql + ' p.Max_Order_Qty AS [Max], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '

	--RL 2013-07-15 Added Average_Cost, Price1_Price1, Price1_Price2 
	--For new report Invetory Analysis Condesed Report For Autoweil
    SET @sql = @sql + ' p.Average_Cost As [AverageCost], '
    SET @sql = @sql + ' p.Price1_Price1 As [Price1Price1], '
    SET @sql = @sql + ' p.Price1_Price2 As [Price1Price2], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jan + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jan], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Feb + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Feb], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Mar + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Mar], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Apr + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Apr], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @May + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [May], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jun + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jun], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jul + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jul], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Aug + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Aug], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Sep + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Sep], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Oct + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Oct], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Nov + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Nov], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Dec + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Dec] '

    SET @sql = @sql + ' FROM AP_Products p '

---------------------------------------------
--> NEW 20/10/03
---------------------------------------------
    SET @sql = @sql +
        ' INNER JOIN AP_Products_Temp temp ' +
        '     ON p.AP_Products_ID = temp.AP_Products_ID '
---------------------------------------------

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    SET @sql = @sql + ' WHERE p.Slu_AW_Active_ID = 1 '


    IF @chkNonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    IF @SortOrder = 0    --by Product Description
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END


    --PRINT @sql

    EXEC (@sql)


---------------------------------------------
--> NEW 20/10/03
---------------------------------------------
    DROP TABLE AP_Products_Temp
---------------------------------------------
SET NOCOUNT OFF



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Audit_Trail
--Purpose       :Retrieves Inventory physical movement
--Functionality :    uses UNION ALL
--Date          :2003/12/17
--Authors       :TB
--MODS:         :16/01/04 - Added Unit Price and Cost Fields
--              :04/03/04 - Added Sys_AP_Adjustment_Types_ID = 1 in WHERE of
--              :           Stock Adjustments to fetch ONLY normal Stock Adjustments
--              :08/09/04 - Added limiting transaction types to Invoices and Refunds
--              :           in the SALE section
--              :09/09/04 - Show ALL Adjustments with New_On_Hand - Previous_On_Hand
--              :           if Sys_AP_Adjustment_Types_ID = 1 or 6 (Stock Take-On)
--              :10/09/04 - Replaced ORDER BY [Date] with [Date Captured]
--              :11/09/04 - Added CASE to distinguish Transaction Types
--              :09/10/04 - Added fn_AP_BFWD_Inventory_On_Hand to get BFWD On-Hand
--              :12/05/05 - Appended (AO_GRV_ID) to Supplier_Reference
--2004.3.4      :08/03/07 - Replaced gh.Supplier_Reference with
--              :           gh.Delivery_Note_Number to show Supplier Invoice Number
--2004.3.9      :13/06/08 - Changed [Supplier/Customer] field in ADJUSTMENTS section
--              :           and inserted [Note] from AP_Inventory_Adjustments table
--2004.4.6      :19/08/09 - Changed [Date] field to CONVERT(CHAR(10), 121) in all three sections
--2004.4.7      :12/09/09 - Added STOCK TRANSFER type in SALES section
--2004.5.1      :02/06/11 - Added h.Sys_AW_Transaction_Types_ID = 29 as 'GRVFAC'
--              :           in GOODS RECEIVED for Casing Tracking Factory GRV's
--              :15/06/11 - Added h.Sys_AW_Transaction_Types_ID = 23 as 'TRF IN/OUT'
--              :           in SALES section CASE statement for [TYPE] field
-------------------------------------------------------------------------------

CREATE                            PROCEDURE sp_RPT_AP_Inventory_Audit_Trail

    (
        @StartDate as datetime,
        @Filter varchar(30),
        @SortOrder tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @StartDate = '2002/01/01 00:00:01'
-- SET @Filter = 'Department'
-- SET @SortOrder = 1
-- SET @CompanyID = 1


-------------------------------------------------------------------------------
-- GOODS RECEIVED
-------------------------------------------------------------------------------

    SET @sql = ' SELECT '
    SET @sql = @sql + '     gd.AW_User_Companies_ID AS [CompanyID], '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     gd.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '

    SET @sql = @sql + '     CASE WHEN gh.Sys_AW_Transaction_Types_ID = 19 '
    SET @sql = @sql + '          THEN ''GRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 20 '
    SET @sql = @sql + '          THEN ''RETURN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '          THEN ''GRVFAC'' '
    SET @sql = @sql + '          ELSE ''NOGRV'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), gh.Date_Received, 121)) AS [Date], '
    SET @sql = @sql + '     ISNULL(gh.Delivery_Note_Number, '''') '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), gh.AO_GRV_ID) + '')'' AS [Ref No], '
    SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '     ISNULL(gd.Qty, 0) AS [Qty], '
    SET @sql = @sql + '     ISNULL(gd.Unit_Price, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ISNULL(gd.Net_Amount, 0) AS [Cost], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AO_GRV_Details gd '
    SET @sql = @sql + '         ON p.AP_Products_ID = gd.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_GRV gh '
    SET @sql = @sql + '         ON gd.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON gh.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON gh.[User_ID] = u.AW_Users_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql + ' WHERE gd.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND gd.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (gh.Sys_AW_Transaction_Types_ID = 19 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 20 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 29) ' + ' '


    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- ADJUSTMENTS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ISNULL(a.Note, '''') AS [Supplier/Customer], '

    SET @sql = @sql + '     CASE WHEN a.Sys_AP_Adjustment_Types_ID = 1 '
    SET @sql = @sql + '          THEN ''ADJUST'' '
    SET @sql = @sql + '          WHEN a.Sys_AP_Adjustment_Types_ID = 6 '
    SET @sql = @sql + '          THEN ''TAKEON'' '
    SET @sql = @sql + '          ELSE ''NOADJ'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.AP_Inventory_Adjustments_ID) AS [Ref No], '
    SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '     ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ISNULL(a.New_Last_Cost, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ROUND((ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0)) * ISNULL(a.New_Last_Cost, 0), 2) AS [Cost], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Inventory_Adjustments a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (a.Sys_AP_Adjustment_Types_ID = 1 ' + ' '
    SET @sql = @sql + '     OR a.Sys_AP_Adjustment_Types_ID = 6) ' + ' '
    SET @sql = @sql + '   AND ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) <> 0 ' + ' '


    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- SALES
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     d.AW_User_Companies_ID AS [CompanyID], '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     d.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('', '' + c.Firstnames, ''''))) AS [Supplier/Customer], '

    SET @sql = @sql + '     CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''SALE'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''REFUND'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) < 0) '
    SET @sql = @sql + '          THEN ''TRF IN'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) >= 0) '
    SET @sql = @sql + '          THEN ''TRF OUT'' '
    SET @sql = @sql + '          ELSE ''NOSALE'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), h.Transaction_Date, 121)) AS [Date], '
    SET @sql = @sql + '     h.Transaction_Number AS [Ref No], '
    SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '     (ISNULL(d.Quantity, 0) * -1) AS [Qty], '
    SET @sql = @sql + '     ISNULL(d.Unit_Cost, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ROUND((ISNULL(d.Quantity, 0) * -1) * ISNULL(d.Unit_Cost, 0), 2) AS [Cost], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + '         ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN dbo.AC_Customers c '
    SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON d.[User_ID] = u.AW_Users_ID '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND d.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '

-------------------------------------------------------------
-- ONLY Invoices and Refunds (08/09/04)
-------------------------------------------------------------
    SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 23) '


    IF @SortOrder = 0    --by Product Description
        SET @sql = @sql + ' ORDER BY [CompanyID], [Filter], [Description], [Date Captured] '
    ELSE
    IF @SortOrder = 1    --by Product Code
        SET @sql = @sql + ' ORDER BY [CompanyID], [Filter], [Code], [Date Captured] '


--PRINT @sql

EXEC (@sql)



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Replenish
--Purpose       :Retrieves Inventory to be ordered
--Functionality :    Conditional upon:
--              :        Stock < (Min_Stock_Level + On Order)
--              :        Is Active product
--Date          :2003/04/11
--Authors       :TB
--MODS:         :12/09/03 - Added ISNULL validation to ALL NUMERIC fields and
--              :           fixed incorrect operator precedence in Qty To Order
--              :13/11/03 - Added Min_Stock_Level to On-Hand to fix incorrectly
--              :           calculated SURPLUS amount
--              :13/10/03 - Split off SURPLUS inventory into seperate report
--              :04/01/05 - Added Non-Stock ignore parameter
--              :17/03/06 - Added Sort by Description or Product Code
--2004.4.0      :03/09/08 - Added @Reserved to REMOVE Reserved Stock from Stock On Hand
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AP_Inventory_Replenish

    (
        @Filter varchar(30),
        @SortOrder tinyint,
        @NonStock int,
        @Reserved int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '


--> QTY to ORDER
    IF @Reserved = 1
        BEGIN
            SET @sql = @sql + ' CASE WHEN  '
            SET @sql = @sql + ' (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0))) > 0 '
            SET @sql = @sql + ' THEN  '
            SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0) ) '
            SET @sql = @sql + ' ELSE NULL '
            SET @sql = @sql + ' END '
            SET @sql = @sql + ' AS [ToOrder], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' CASE WHEN  '
            SET @sql = @sql + ' (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (ISNULL(p.On_Hand, 0) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0))) > 0 '
            SET @sql = @sql + ' THEN  '
            SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '     (ISNULL(p.On_Hand, 0) + '
            SET @sql = @sql + '      ISNULL(( '
            SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '         FROM AO_Order_Details od '
            SET @sql = @sql + '             INNER JOIN AO_Orders o '
            SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
            SET @sql = @sql + '               o.Complete <> 1 AND '
            SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '            ), 0) ) '
            SET @sql = @sql + ' ELSE NULL '
            SET @sql = @sql + ' END '
            SET @sql = @sql + ' AS [ToOrder], '
        END


    IF @Reserved = 1
        BEGIN
            SET @sql = @sql + ' CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) AS [OnHand], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '
        END


    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL], '
    SET @sql = @sql + ' ISNULL(p.Min_Order_Qty, 0) AS [Min], '
    SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) AS [Max], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [LastCost] '

    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


--------------------------------------------------------
--> (MSL - (On-Hand + On-Order)) > 0 (Qty to Order)
--------------------------------------------------------
    IF @Reserved = 1
        BEGIN
            SET @sql = @sql + '   AND (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '        (CONVERT(decimal(12, 3),(ISNULL(p.On_Hand, 0) - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) + '
            SET @sql = @sql + '         ISNULL(( '
            SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '             FROM AO_Order_Details od '
            SET @sql = @sql + '                 INNER JOIN AO_Orders o '
            SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '             WHERE o.Date_Ordered IS NOT NULL AND '
            SET @sql = @sql + '                   o.Complete <> 1 AND '
            SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '         ), 0))) > 0 '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '   AND (ISNULL(p.Min_Stock_Level, 0) - '
            SET @sql = @sql + '        (ISNULL(p.On_Hand, 0) + '
            SET @sql = @sql + '         ISNULL(( '
            SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
            SET @sql = @sql + '             FROM AO_Order_Details od '
            SET @sql = @sql + '                 INNER JOIN AO_Orders o '
            SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
            SET @sql = @sql + '             WHERE o.Date_Ordered IS NOT NULL AND '
            SET @sql = @sql + '                   o.Complete <> 1 AND '
            SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '         ), 0))) > 0 '
        END
-----------------------------------------------------


    IF @SortOrder = 0
        SET @sql = @sql + ' ORDER BY [Filter], [Description] '
    ELSE
    IF @SortOrder = 1
        SET @sql = @sql + ' ORDER BY [Filter], [Code] '


    EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Replenish_Analysis
--Purpose       :Inventory Replenishment Analysis with Last 6 months Sales Analysis
--Date          :2010/01/28
--Authors       :TB
--MODS:         :
--2004.5.4      :20/09/11 - Added @StartMonth and [Current] field as Current Month sales
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis]
    (
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @ExclInterCo tinyint,
        @CompanyID int,
        @M1 varchar(6),
        @M2 varchar(6),
        @M3 varchar(6),
        @M4 varchar(6),
        @M5 varchar(6),
        @M6 varchar(6),
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@PurchCatID int = -1
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(4000),
            @StartMonth datetime


	SET @Filter = ''
    SET @sql = ''


    -- FIRST day of the @EndDate month
    SET @StartMonth = CONVERT(datetime, CONVERT(varchar(4), YEAR(@EndDate)) + '/' + CONVERT(varchar(2), MONTH(@EndDate)) + '/' + '01 00:00:01' )


    SET @Filter = ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @Filter = @Filter + '  AND (h.Date_Captured >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @Filter = @Filter + '  AND  h.Date_Captured <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @Filter = @Filter + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @Filter = @Filter + '       h.Sys_AW_Transaction_Types_ID = 4)'


    --> Supplier
	IF @SupplierID > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                        convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                        convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0
		BEGIN
    		SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                        convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0
		BEGIN
			SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                        convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                        convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                        convert(varchar(20), @LocationID)
    	END
    --> PurchCat
	IF @PurchCatID  > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Purchase_Categories_ID = ' +
                                        convert(varchar(20), @PurchCatID)
    	END


    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' p.AP_Products_ID as [ID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [UnitPrice], '
    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '
    SET @sql = @sql + ' p.Average_Cost AS [AvgCost], '
    SET @sql = @sql + ' CASE WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
    SET @sql = @sql + '      THEN ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - p.Last_Cost) / dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [LastDisc%], '
    SET @sql = @sql + ' CONVERT(CHAR(10), p.Last_Sale_Date, 121) AS [LastSale], '
    SET @sql = @sql + ' p.On_Hand AS [On Hand], '

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN	
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN		
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN			
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN				
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN					
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN							
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END
	
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '


    SET @sql = @sql + @Filter


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '  AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    IF @ActiveOnly = 1      --Active Products only
        BEGIN
            SET @sql = @sql + '  AND p.Slu_AW_Active_ID = 1 '
        END


    IF @ExclInterCo = 1      --Exclude Inter-Company sales
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product] '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product] '
        END

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Replenish_Analysis2
--Purpose       :Inventory Replenishment Analysis with Last 6 months Sales Analysis
--              :    by Product Filter
--Date          :2010/06/08
--Authors       :TB
--MODS:         :
--2004.5.4      :20/09/11 - Added @StartMonth and [Current] field as Current Month sales
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis2]
	(
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @ExclInterCo tinyint,
        @CompanyID int,
        @M1 varchar(6),
        @M2 varchar(6),
        @M3 varchar(6),
        @M4 varchar(6),
        @M5 varchar(6),
        @M6 varchar(6),
        @Filter varchar(100)
	)

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000),
            @Where varchar(4000),
            @StartMonth datetime


	SET @Where = ''
    SET @sql = ''


    -- FIRST day of the @EndDate month
    SET @StartMonth = CONVERT(datetime, CONVERT(varchar(4), YEAR(@EndDate)) + '/' + CONVERT(varchar(2), MONTH(@EndDate)) + '/' + '01 00:00:01' )


    SET @Where = ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @Where = @Where + '  AND (h.Date_Captured >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @Where = @Where + '  AND  h.Date_Captured <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @Where = @Where + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @Where = @Where + '       h.Sys_AW_Transaction_Types_ID = 4)'
    
    
    SET @sql = ' SELECT DISTINCT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'PurchCat'
        SET @sql = @sql +
            ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' p.AP_Products_ID as [ID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [UnitPrice], '
    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '
    SET @sql = @sql + ' p.Average_Cost AS [AvgCost], '
    SET @sql = @sql + ' CASE WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
    SET @sql = @sql + '      THEN ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - p.Last_Cost) / dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [LastDisc%], '
    SET @sql = @sql + ' CONVERT(CHAR(10), p.Last_Sale_Date, 121) AS [LastSale],  '
    SET @sql = @sql + ' p.On_Hand AS [On Hand], '

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN	
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'PurchCat'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Purchase_Categories o ' +
            '     ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '


    SET @sql = @sql + @Where


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '  AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    IF @ActiveOnly = 1      --Active Products only
        BEGIN
            SET @sql = @sql + '  AND p.Slu_AW_Active_ID = 1 '
        END


    IF @ExclInterCo = 1      --Exclude Inter-Company sales
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--sp_RPT_AP_Inventory_Stock_Take 1, -1, 8, -1, -1, -1, -1, 0, 0, 0
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Stock_Take
--Purpose       :Retrieves Inventory Stock Take sheet
--Date          :2004/06/08
--Authors       :TB
--MODS:         :29/01/05 - Added [JobRes] field and narrowed Count fields by 3 spaces
--2004.4.1      :24/09/08 - Added dynamic [Reserved]
--2004.4.2      :23/01/09 - Reduced the spaces by 2 each in the [Count1] mask
--2004.4.6      :14/08/09 - Added Purchase Categories
--2016.6.2	RL  :2016-08-19 - Added Product Bins and Consignment
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Inventory_Stock_Take]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@PurchCatID int = -1,
      	@BinID int = -1,
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @SQL varchar(2000)

	SET @Filter = ''
    SET @SQL = ''


    	IF @SupplierID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    		END
    --> Manufacturer
    	IF @ManufacturerID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    		END
    --> Type
    	IF @TypeID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    		END
    --> Group
    	IF @GroupID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    		END
    --> Department
    	IF @DepartmentID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    		END
    --> Location
    	IF @LocationID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
        	END
    --> PurchCat
    	IF @PurchCatID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
        	END
    --> Bin
    	IF @BinID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' b.Lup_AP_Product_Bins_ID = ' +
                                    convert(varchar(20), @BinID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' b.Lup_AP_Product_Bins_ID = ' +
                                    convert(varchar(20), @BinID)
        	END


		IF @Filter = ''
            BEGIN
				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
				SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END

        IF @OnHandOnly = 1
            BEGIN
    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                    convert(varchar(20), @CompanyID) +
                                  ' AND ' + ' (p.On_Hand <> 0 ' +
                                  ' OR CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) <> 0) '
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' (p.On_Hand <> 0 ' +
                                            ' OR CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) <> 0) '
            END


        IF @NonStock = 1
            BEGIN
                SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Product], '
        SET @SQL = @SQL + ' p.Product_Code AS [Code], '
        SET @SQL = @SQL + ' p.Pack_Size AS [Size], '
        SET @SQL = @SQL + ' p.On_Hand AS [Qty], '
        SET @SQL = @SQL + ' b.On_Hand AS [BinQty], '
        SET @SQL = @SQL + ' d.[Description] AS [Bin], '
        SET @SQL = @SQL + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) AS [ConsQty], '        
        SET @SQL = @SQL + ' CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved], '
        SET @SQL = @SQL + '''[               ][               ][                ]'' AS [Count1] '

        SET @SQL = @SQL + ' FROM AP_Products p '
        
        SET @sql = @sql + ' LEFT JOIN AP_Products_Bins b '
        SET @sql = @sql +   '     ON p.AP_Products_ID = b.AP_Products_ID '

        SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Bins d '
        SET @sql = @sql +   '     ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '
        
        SET @SQL = @SQL + @Filter


        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY p.[Description] '
            END


    EXEC (@SQL)
--Select @SQL


SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Stock_Take_Filtered
--Purpose       :Retrieves Inventory Stock Take sheet
--Date          :2004/09/05
--Authors       :TB
--Version       :1.0.0
--MODS:         :29/01/05 - Added [JobRes] field and narrowed Count fields by 3 spaces
--2004.4.1      :24/09/08 - Added dynamic [Reserved]
--2004.4.2      :23/01/09 - Reduced the spaces by 2 each in the [Count1] mask
--2004.4.6      :14/08/09 - Added Purchase Categories
--2016.6.2	RL  :2016-08-19 - Added Product Bins and Consignment
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Inventory_Stock_Take_Filtered]
	(
        @CompanyID int,
        @Filter varchar(100),
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ''
    
    
        SET @sql = ' SELECT '
    
        IF @Filter = 'Type'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Groups'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Department'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Supplier'
            SET @sql = @sql +
                ' o.AO_Suppliers_ID AS [HeaderID], ' +
                ' o.[Supplier_Name] AS [Filter], '
        ELSE
        IF @Filter = 'Manufacturer'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Location'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'PurchCat'
            SET @sql = @sql +
                ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Bin'
            SET @sql = @sql +
                ' d.Lup_AP_Product_Bins_ID AS [HeaderID], ' +
                ' d.[Description] AS [Filter], '

        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Product], '
        SET @SQL = @SQL + ' p.Product_Code AS [Code], '
        SET @SQL = @SQL + ' p.Pack_Size AS [Size], '
        SET @SQL = @SQL + ' p.On_Hand AS [Qty], '
        SET @SQL = @SQL + ' b.On_Hand AS [BinQty], '
        SET @SQL = @SQL + ' d.[Description] AS [Bin], '
        SET @SQL = @SQL + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) AS [ConsQty], '
        SET @SQL = @SQL + ' CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved], '
        SET @SQL = @SQL + '''[               ][               ][                ]'' AS [Count1] '
        SET @SQL = @SQL + ' FROM AP_Products p '

        SET @sql = @sql + ' LEFT JOIN AP_Products_Bins b '
        SET @sql = @sql +   '     ON p.AP_Products_ID = b.AP_Products_ID '

        SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Bins d '
        SET @sql = @sql +   '     ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '

    
        IF @Filter = 'Type'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Product_Types o ' +
                '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
        ELSE
        IF @Filter = 'Groups'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Product_Groups o ' +
                '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
        ELSE
        IF @Filter = 'Department'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Product_Departments o ' +
                '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
        ELSE
        IF @Filter = 'Supplier'
            SET @sql = @sql +
                ' LEFT JOIN AO_Suppliers o ' +
                '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
        ELSE
        IF @Filter = 'Manufacturer'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
                '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
        ELSE
        IF @Filter = 'Location'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Product_Locations o ' +
                '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
        ELSE
        IF @Filter = 'PurchCat'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Purchase_Categories o ' +
                '     ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '

    
        SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


        IF @OnHandOnly = 1
            BEGIN
                --> This code causes Query Timeout !!!!!!!
--                 SET @sql = @sql + ' AND ' + ' (p.On_Hand <> 0 ' +
--                                             ' OR CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) <> 0) '
                SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
            END


        IF @NonStock = 1
            BEGIN
                SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


        IF @Sort = 1
            BEGIN
                SET @sql = @sql + ' ORDER BY [Filter], [Code] '
            END
        ELSE
            BEGIN
                SET @sql = @sql + ' ORDER BY [Filter], [Product] '
            END


    EXEC (@SQL)



SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_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 sp_RPT_AP_Inventory_Valuation
    (
        @ValuationID int,
        @Option varchar(20),
        @OnHandOnly tinyint,
        @NonStock tinyint,
        @AssignStd tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ZeroCostOverride smallint


    --> Get Secondary Costing method (Zero Primary Cost override)
    SELECT @ZeroCostOverride = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optZeroCostOverride' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


    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 + ' p.Pack_Size AS [Size], '

    SET @sql = @sql + ' h.Qty AS [Qty], '

    SET @sql = @sql + ' h.Cost AS [LastUnitCost], '
    SET @sql = @sql + ' h.Average_Cost AS [AvgUnitCost], '
    SET @sql = @sql + ' h.Standard_Cost AS [StdUnitCost], '

    SET @sql = @sql + ' CONVERT(money, (h.Cost * h.Qty)) AS [Last Cost], '
    SET @sql = @sql + ' CONVERT(money, (h.Average_Cost * h.Qty)) AS [Avg Cost], '

--     IF @AssignStd = 1      --Assign Last Cost if Std. Cost zero
--         BEGIN
--             SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
--             SET @sql = @sql + '      THEN CONVERT(money, (h.Cost * h.Qty)) '
--             SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
--             SET @sql = @sql + '      END AS [Std Cost], '
--         END
--     ELSE
--         BEGIN
--             SET @sql = @sql + ' CONVERT(money, (h.Standard_Cost * h.Qty)) AS [Std Cost], '
--         END

    IF @AssignStd = 1      --Assign SECONDARY Cost IF Standard_Cost = 0
        BEGIN
            IF @ZeroCostOverride = 0
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Average_Cost * h.Qty)) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
            ELSE
            IF @ZeroCostOverride = 1
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Cost * h.Qty)) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
            ELSE
            IF @ZeroCostOverride = 2
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' CONVERT(money, (h.Standard_Cost * h.Qty)) AS [Std Cost], '
        END

    SET @sql = @sql + ' CONVERT(money, (p.Price1_Price1 * h.Qty)) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, ((p.Price1_Price1 - h.Average_Cost) * h.Qty)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(p.Price1_Price1, h.Qty) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, dbo.fn_AS_Calc_Std_GP(p.Price1_Price1, h.Average_Cost, h.Qty) / dbo.fn_AS_Calc_Std_Sales_Value(p.Price1_Price1, h.Qty) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg GP%], '
    
    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Cost * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Last Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Average_Cost * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Avg Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Standard_Cost * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Std Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((p.Price1_Price1 * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Selling] '
    
    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 +
        ' 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


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    SET @sql = @sql + ' ORDER BY [HeaderID] '


EXEC (@sql)

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Valuation
--Purpose       :Select Inventory Valuation Movement BETWEEN two Valuations
--Date          :2007/09/26
--Authors       :TB
--MODS:         :
--2004.4.2      :09/11/08 - Added Assign Secondary Costing method if Standard Cost zero
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AP_Inventory_Valuation_Movement
    (
        @ValuationID_0 int,
        @ValuationID_1 int,
        @Option varchar(20),
        @OnHandOnly tinyint,
        @NonStock tinyint,
        @AssignStd tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ZeroCostOverride smallint


    --> Get Secondary Costing method (Zero Primary Cost override)
    SELECT @ZeroCostOverride = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optZeroCostOverride' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


    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.Product_Code AS [Code], '

    SET @sql = @sql + ' CONVERT(CHAR(10), m.Month_End_Date, 121) AS [Date], '

    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '
    SET @sql = @sql + ' (h.Qty * -1) AS [Qty], '

    SET @sql = @sql + ' h.Cost AS [LastUnitCost], '
    SET @sql = @sql + ' h.Average_Cost AS [AvgUnitCost], '
    SET @sql = @sql + ' h.Standard_Cost AS [StdUnitCost], '

    SET @sql = @sql + ' CONVERT(money, (h.Cost * (h.Qty * -1))) AS [Last Cost], '
    SET @sql = @sql + ' CONVERT(money, (h.Average_Cost * (h.Qty * -1))) AS [Avg Cost], '

--     IF @AssignStd = 1      --Assign Last Cost if Std. Cost zero
--         BEGIN
--             SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) = 0 '
--             SET @sql = @sql + '      THEN CONVERT(money, (h.Cost * (h.Qty * -1))) '
--             SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) '
--             SET @sql = @sql + '      END AS [Std Cost], '
--         END
--     ELSE
--         BEGIN
--             SET @sql = @sql + ' CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) AS [Std Cost], '
--         END

    IF @AssignStd = 1      --Assign SECONDARY Cost IF Standard_Cost = 0
        BEGIN
            IF @ZeroCostOverride = 0
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Average_Cost * (h.Qty * -1))) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
            ELSE
            IF @ZeroCostOverride = 1
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Cost * (h.Qty * -1))) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
            ELSE
            IF @ZeroCostOverride = 2
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' CONVERT(money, (h.Standard_Cost * (h.Qty * -1))) AS [Std Cost], '
        END

    SET @sql = @sql + ' CONVERT(money, (p.Price1_Price1 * (h.Qty * -1))) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, ((p.Price1_Price1 - h.Average_Cost) * (h.Qty * -1))) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(p.Price1_Price1, (h.Qty * -1)) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, dbo.fn_AS_Calc_Std_GP(p.Price1_Price1, h.Average_Cost, (h.Qty * -1)) / dbo.fn_AS_Calc_Std_Sales_Value(p.Price1_Price1, (h.Qty * -1)) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg GP%], '
    
    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Cost * (h.Qty * -1)) / (h.Qty * -1))) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Last Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Average_Cost * (h.Qty * -1)) / (h.Qty * -1))) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Avg Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Standard_Cost * (h.Qty * -1)) / (h.Qty * -1))) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Std Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((p.Price1_Price1 * (h.Qty * -1)) / (h.Qty * -1))) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Selling] '
    
    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 '
    SET @sql = @sql + '      INNER JOIN AW_Period_Procedures m '
    SET @sql = @sql + '          ON h.AW_Period_Procedures_ID = m.AW_Period_Procedures_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 +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
        '   AND h.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @ValuationID_0) + ' '


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + '   AND h.Qty <> 0 '
        END


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


-----------------------------------
    SET @sql = @sql + ' UNION ALL '
-----------------------------------


    SET @sql = @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.Product_Code AS [Code], '
--    SET @sql = @sql + ' m.Month_End_Date AS [Date], '
    SET @sql = @sql + ' CONVERT(CHAR(10), m.Month_End_Date, 121) AS [Date], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '
    SET @sql = @sql + ' h.Qty AS [Qty], '

    SET @sql = @sql + ' h.Cost AS [LastUnitCost], '
    SET @sql = @sql + ' h.Average_Cost AS [AvgUnitCost], '
    SET @sql = @sql + ' h.Standard_Cost AS [StdUnitCost], '

    SET @sql = @sql + ' CONVERT(money, (h.Cost * h.Qty)) AS [Last Cost], '
    SET @sql = @sql + ' CONVERT(money, (h.Average_Cost * h.Qty)) AS [Avg Cost], '

--     IF @AssignStd = 1      --Assign Last Cost if Std. Cost zero
--         BEGIN
--             SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
--             SET @sql = @sql + '      THEN CONVERT(money, (h.Cost * h.Qty)) '
--             SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
--             SET @sql = @sql + '      END AS [Std Cost], '
--         END
--     ELSE
--         BEGIN
--             SET @sql = @sql + ' CONVERT(money, (h.Standard_Cost * h.Qty)) AS [Std Cost], '
--         END

    IF @AssignStd = 1      --Assign SECONDARY Cost IF Standard_Cost = 0
        BEGIN
            IF @ZeroCostOverride = 0
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Average_Cost * h.Qty)) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
            ELSE
            IF @ZeroCostOverride = 1
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Cost * h.Qty)) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
            ELSE
            IF @ZeroCostOverride = 2
                BEGIN
                    SET @sql = @sql + ' CASE WHEN CONVERT(money, (h.Standard_Cost * h.Qty)) = 0 '
                    SET @sql = @sql + '      THEN CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      ELSE CONVERT(money, (h.Standard_Cost * h.Qty)) '
                    SET @sql = @sql + '      END AS [Std Cost], '
                END
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' CONVERT(money, (h.Standard_Cost * h.Qty)) AS [Std Cost], '
        END

    SET @sql = @sql + ' CONVERT(money, (p.Price1_Price1 * h.Qty)) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, ((p.Price1_Price1 - h.Average_Cost) * h.Qty)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(p.Price1_Price1, h.Qty) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, dbo.fn_AS_Calc_Std_GP(p.Price1_Price1, h.Average_Cost, h.Qty) / dbo.fn_AS_Calc_Std_Sales_Value(p.Price1_Price1, h.Qty) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg GP%], '
    
    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Cost * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Last Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Average_Cost * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Avg Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((h.Standard_Cost * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Std Cost], '

    SET @sql = @sql + ' CASE WHEN h.Qty <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, ((p.Price1_Price1 * h.Qty) / h.Qty)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Avg. Selling] '




    SET @sql = @sql + ' FROM AP_Products_History h '
    SET @sql = @sql + '      LEFT JOIN AP_Products p '
    SET @sql = @sql + '          ON h.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Period_Procedures m '
    SET @sql = @sql + '          ON h.AW_Period_Procedures_ID = m.AW_Period_Procedures_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 +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
        '   AND h.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @ValuationID_1) + ' '


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + '   AND h.Qty <> 0 '
        END


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END



    SET @sql = @sql + ' ORDER BY [HeaderID], [Code], [Date] '


EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














--sp_RPT_AP_Nursery_Labels 1, -1, 8, -1, -1, -1, -1, 0, 0, 0
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Nursery_Labels
--Purpose       :Nursery Tie-On Inventory Barcode Labels
--Date          :2006/02/06
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE           PROCEDURE sp_RPT_AP_Nursery_Labels
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(4000),
            @SQL varchar(4000)

	SET @Filter = ''
    SET @SQL = ''


    	IF @SupplierID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    		END
    --> Manufacturer
    	IF @ManufacturerID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    		END
    --> Type
    	IF @TypeID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    		END
    --> Group
    	IF @GroupID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    		END
    --> Department
    	IF @DepartmentID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    		END
    --> Location
    	IF @LocationID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
        	END

		IF @Filter = ''
            BEGIN
				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
				SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END

        IF @OnHandOnly = 1
            BEGIN
    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                    convert(varchar(20), @CompanyID) +
                                  ' AND ' + ' p.On_Hand <> 0 '
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.On_Hand <> 0 '
            END


        IF @NonStock = 1
            BEGIN
                SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Description], '
        SET @SQL = @SQL + ' p.[Print_Description] AS [PrintDesc], '
        SET @SQL = @SQL + ' p.Product_Code AS [ProductCode], '
        SET @SQL = @SQL + ' p.On_Hand AS [OnHand], '
        SET @sql = @sql + ' ISNULL(p.Product_Code, '''') '
        SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')'' AS [CompositeCode] '
        SET @SQL = @SQL + ' FROM AP_Products p '
        SET @SQL = @SQL + @Filter

        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY p.[Description] '
            END


    EXEC (@SQL)



SET NOCOUNT OFF	



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Order_Analysis
--Purpose       :Retrieves Product Sales Usage Analysis for last 12 months
--Functionality :    Conditional upon:
--              :        Has_Sales OR
--              :        Has On_Hand <> 0 OR
--              :        Has Min_Stock_Level <> 0 OR
--              :        Has Min_Order_Qty <> 0 OR
--              :        Has Max_Order_Qty <> 0 OR
--              :        Has_Orders AND
--              :        IS Active
--Date          :2003/04/11
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AP_Order_Analysis
    (
        @Filter varchar(30),
        @EndDate datetime,
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6),
        @Option0 tinyint,
        @Option1 tinyint,
        @Option2 tinyint,
        @Option3 tinyint,
        @Option4 tinyint,
        @Option5 tinyint,
        @Option6 tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartDate datetime

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @EndDate = '2003/04/12 23:59:59'
-- SET @StartDate = DATEADD(yy, -1, @EndDate)
-- SET @Jan = '012003'
-- SET @Feb = '022003'
-- SET @Mar = '032003'
-- SET @Apr = '042003'
-- SET @May = '052002'
-- SET @Jun = '062002'
-- SET @Jul = '072002'
-- SET @Aug = '082002'
-- SET @Sep = '092002'
-- SET @Oct = '102002'
-- SET @Nov = '112002'
-- SET @Dec = '122002'
-- SET @Option0 = 0    --Has sales
-- SET @Option1 = 0    --Has On_Hand
-- SET @Option2 = 0    --Has Min_Stock_Level
-- SET @Option3 = 0    --Has Min_Order_Qty
-- SET @Option4 = 0    --Has Max_Order_Qty
-- SET @Option5 = 0    --Has_Orders
-- SET @Option6 = 0    --IS Active


    SET @StartDate = DATEADD(yy, -1, @EndDate)


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.On_Hand AS [OnHand], '
    SET @sql = @sql + ' p.Min_Stock_Level AS [MSL], '
    SET @sql = @sql + ' p.Min_Order_Qty AS [Min], '
    SET @sql = @sql + ' p.Max_Order_Qty AS [Max], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jan + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jan], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Feb + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Feb], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Mar + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Mar], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Apr + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Apr], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @May + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [May], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jun + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jun], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jul + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jul], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Aug + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Aug], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Sep + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Sep], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Oct + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Oct], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Nov + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Nov], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         INNER JOIN AS_Transactions h '
    SET @sql = @sql + '             ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Dec + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Dec] '

    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

--ORIG VERSION
-----------------------------------------------------
    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND AP_Products_ID in '
    SET @sql = @sql + '     ( SELECT DISTINCT AP_Products_ID '
    SET @sql = @sql + '       FROM AS_Transaction_Details '
    SET @sql = @sql + '       WHERE dbo.fn_AS_Product_Has_Sales(' + CONVERT(varchar(10), @CompanyID) + ', ''' + CONVERT(varchar(30), @StartDate) + ''', ''' + CONVERT(varchar(30), @EndDate) + ''') = 1 ) '
    SET @sql = @sql + '    OR p.On_Hand <> 0 '
    SET @sql = @sql + '    OR p.Min_Stock_Level <> 0 '
    SET @sql = @sql + '    OR p.Min_Order_Qty <> 0 '
    SET @sql = @sql + '    OR p.Max_Order_Qty <> 0 '
    SET @sql = @sql + '    OR dbo.fn_AO_Product_Has_Orders(p.AP_Products_ID) = 1 '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '
-----------------------------------------------------

--     SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
-- 
--     IF @Option0 = 1    --Has Sales
--         BEGIN
--             SET @sql = @sql + '   AND AP_Products_ID in '
--             SET @sql = @sql + '     ( SELECT DISTINCT AP_Products_ID '
--             SET @sql = @sql + '       FROM AS_Transaction_Details '
--             SET @sql = @sql + '       WHERE dbo.fn_AS_Product_Has_Sales(' + CONVERT(varchar(10), @CompanyID) + ', ''' + CONVERT(varchar(30), @StartDate) + ''', ''' + CONVERT(varchar(30), @EndDate) + ''') = 1 ) '
--         END
-- 
--     IF @Option1 = 1    --Has On_Hand
--         SET @sql = @sql + '    OR p.On_Hand <> 0 '
-- 
--     IF @Option2 = 1    --Has Min_Stock_Level <> 0
--         SET @sql = @sql + '    OR p.Min_Stock_Level <> 0 '
-- 
--     IF @Option3 = 1    --Has Min_Order_Qty <> 0
--         SET @sql = @sql + '    OR p.Min_Order_Qty <> 0 '
-- 
--     IF @Option4 = 1    --Has Max_Order_Qty <> 0
--         SET @sql = @sql + '    OR p.Max_Order_Qty <> 0 '
-- 
--     IF @Option5 = 1    --Has_Orders
--         SET @sql = @sql + '    OR dbo.fn_AO_Product_Has_Orders(p.AP_Products_ID) = 1 '
-- 
--     IF @Option6 = 1    --IS Active
--         SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '

    SET @sql = @sql + ' ORDER BY [Filter], [Description] '

--PRINT @sql

EXEC (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Product_Consignment_Customer
--Purpose       :Consignment Products out at Customers
--Date          :2015/08/12
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_RPT_AP_Product_Consignment_Customer]
(
        @Products_ID	int,
		@CompanyID int
)        
AS

		SELECT c.AC_Customers_ID, 
				ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
 				SUM(d.Quantity   
					- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID)) AS [Qty]
		FROM AS_Transactions t
			INNER JOIN AS_Transaction_Details d
				ON t.AS_Transactions_ID = d.AS_Transactions_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			INNER JOIN AP_Products p
				ON d.AP_Products_ID = p.AP_Products_ID	
		WHERE t.Sys_AW_Transaction_Types_ID = 33  --Consignment Stock Note
		AND d.Quantity   
				- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
				- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
		AND p.AP_Products_ID = @Products_ID
		AND c.AW_User_Companies_ID = @CompanyID
		Group By c.AC_Customers_ID, ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')'
		ORDER BY ISNULL(c.Surname, '') + ' ' + ISNULL(c.Firstnames, '')  + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Product_Price_List
--Purpose       :Product Price List
--Date          :2003/11/27
--Authors       :TB
--Version       :1.0.0
--MODS:         :08/01/04 - Removed Active field and SELECT ONLY active Products
--              :24/05/04 - Renamed alias for the two sets of prices
--              :05/04/06 - Added input parameter @chkOnHand
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AP_Product_Price_List

    (
        @Filter varchar(30),
        @SortOrder tinyint,
        @chkOnHand tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    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 + ' CONVERT(CHAR(10), p.Price1_Effective_Date , 121) AS [Price1 Date], '
    SET @sql = @sql + ' p.Price1_Price1 AS [Price11], '
    SET @sql = @sql + ' p.Price1_Price2 AS [Price12], '

    SET @sql = @sql + ' CONVERT(CHAR(10), p.Price2_Effective_Date , 121) AS [Price2 Date], '
    SET @sql = @sql + ' p.Price2_Price1 AS [Price21], '
    SET @sql = @sql + ' p.Price2_Price2 AS [Price22] '

    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '

    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
                      '       AND p.Slu_AW_Active_ID = 1 '


    IF @chkOnHand = 1
        SET @sql = @sql + '      AND p.On_Hand <> 0 '


    IF @SortOrder = 0
        SET @sql = @sql + ' ORDER BY [Filter], [Description] '
    ELSE
    IF @SortOrder = 1
        SET @sql = @sql + ' ORDER BY [Filter], [Code] '

--PRINT @sql

EXEC (@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Product_Price_List_VAT
--Purpose       :Product Price List - V.A.T. INCLUSIVE
--Date          :2005/12/12
--Authors       :TB
--MODS:         :05/04/06 - Added input parameter @chkOnHand
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AP_Product_Price_List_VAT

    (
        @Filter varchar(30),
        @SortOrder tinyint,
        @chkOnHand tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' p.On_Hand as [Qty on Hand], '
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg Cost], '
    SET @sql = @sql + ' CONVERT(CHAR(10), dbo.GetEffectiveDate(p.Price1_Effective_Date, p.Price2_Effective_Date, getdate()) , 121) AS [Effective], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price1], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price2], '
    SET @sql = @sql + ' p.Sys_AW_Tax_Codes_ID as [TaxCodeID] '

    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '

    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' ' +
                      '       AND p.Slu_AW_Active_ID = 1 '


    IF @chkOnHand = 1
        SET @sql = @sql + '      AND p.On_Hand <> 0 '


    IF @SortOrder = 0
        SET @sql = @sql + ' ORDER BY [Filter], [Description] '
    ELSE
    IF @SortOrder = 1
        SET @sql = @sql + ' ORDER BY [Filter], [Code] '

--PRINT @sql

EXEC (@sql)





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Sales_Promotions
--Purpose       :Select Sales Promotion Product
--Functionality :
--Date          :2004/03/11
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE          PROCEDURE sp_RPT_AP_Sales_Promotions
    (
        @PromotionID int
    )

AS

SET NOCOUNT ON

    SELECT
        pp.AP_Promotion_Products_ID AS [PromoProductID],
        p.[Description] AS [Product],
        p.Product_Code AS [Code],
        pp.Start_Date AS [Starts],
        pp.End_Date AS [Ends],
        ct.[Description] AS [Terms],
        pp.Selling_Price AS [Selling],
        pp.Qty_Projected_Sales AS [Projected],
        pp.Qty_Cutoff AS [Cutoff],
        pp.Qty_Sold AS [Sold],
        a.[Description] AS [Status]
    FROM AP_Promotion_Products pp
        LEFT JOIN AP_Products p
            ON pp.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON pp.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_Active a
            ON pp.Slu_AW_Active_ID = a.Slu_AW_Active_ID
    WHERE pp.AP_Promotions_ID = @PromotionID



SET NOCOUNT OFF














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Slow_Moving_Inventory
--Purpose       :Retrieves Surplus Inventory
--Functionality :    Conditional upon:
--              :        Stock > 0 and
--              :            No Sales since Last_Sale_Date
--              :            No Purchases since Last_Purchase_Date
--              :    Excludes Non-Stock Items
--Date          :2003/11/13
--Authors       :TB
--MODS:         :
--2004.3.5      :22/05/07 - Added Last Purchase Date to fetch date from Function
--              :               fn_AP_Get_Last_Purchase_Date
--              :22/05/07 - Modified [LastSale] to fetch date from Function
--              :               fn_AP_Get_Last_Sale_Date
--2004.3.8      :08/04/08 - Added @GRVDate input parameter to add validation if no
--              :           purchases AND Sales before @SaleDate and @GRVDate - PB
--              :08/04/08 - Modified WHERE validation by converting dates to FLOAT
--              :           to prevent inconsistent filtering when datetime values
--              :           are converted to varchar(30)
--              :08/04/08 - Added [PurchQty] using new fn_AP_Get_Last_Purchase_Qty
--2004.4.2      :22/12/08 - Added ISNULL(LastSaleDate) and ISNULL(LastPurchDate) validation 
--              :           to also include products if NEVER SOLD or PURCHASED
--              :23/12/08 - Added @chkNoSales and @chkNoPurchases as options to widen capability
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AP_Slow_Moving_Inventory
    (
        @chkNoSales tinyint,
        @chkNoPurchases tinyint,
        @SaleDate datetime,
        @GRVDate datetime,
        @Filter varchar(30),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '
    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL], '
    SET @sql = @sql + ' ISNULL(p.Min_Order_Qty, 0) AS [Min], '
    SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) AS [Max], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' CONVERT(CHAR(10), dbo.fn_AP_Get_Last_Sale_Date(p.AP_Products_ID), 121) as [LastSale], '
    SET @sql = @sql + ' CONVERT(CHAR(10), dbo.fn_AP_Get_Last_Purchase_Date(p.AP_Products_ID), 121) as [LastPurch], '
    SET @sql = @sql + ' dbo.fn_AP_Get_Last_Purchase_Qty(p.AP_Products_ID) as [PurchQty], '

    SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [LastCost], '
    SET @sql = @sql + ' act.[Description] AS [Active] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active act ' +
                      '         ON p.Slu_AW_Active_ID = act.Slu_AW_Active_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.On_Hand > 0 '
    SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '

    IF @chkNoSales = 1
        BEGIN
            SET @sql = @sql + '   AND (p.Last_Sale_Date IS NULL OR CONVERT(varchar(30), CONVERT(float, p.Last_Sale_Date)) < ' +
                               '''' + CONVERT(varchar(30), CONVERT(float, @SaleDate)) + '''' + ') '
        END

    IF @chkNoPurchases = 1
        BEGIN
            SET @sql = @sql + '   AND (dbo.fn_AP_Get_Last_Purchase_Date(p.AP_Products_ID) IS NULL OR CONVERT(varchar(30), CONVERT(float, dbo.fn_AP_Get_Last_Purchase_Date(p.AP_Products_ID))) < ' +
                               '''' + CONVERT(varchar(30), CONVERT(float, @GRVDate))  + '''' + ') '
        END

    SET @sql = @sql + ' ORDER BY [Filter], [Description] '




--PRINT @sql

EXEC (@sql)














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Stock_Bins
--Purpose       :Retrieves Inventory Stock per Bin
--Date          :2015-12-02
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Stock_Bins]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@PurchCatID int = -1,
        @BinID int = -1,
        @Sort int,
        @NonStock int,
        @Option varchar(30)
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @SQL varchar(2000),
            @ValuationMethod smallint

	SET @Filter = ''
    SET @SQL = ''

    --> Get Primary Costing method
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


		---------------------------------------------------------
		--Filter Begin
		---------------------------------------------------------
    	IF @SupplierID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    		END
    --> Manufacturer
    	IF @ManufacturerID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    		END
    --> Type
    	IF @TypeID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    		END
    --> Group
    	IF @GroupID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    		END
    --> Department
    	IF @DepartmentID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    		END
    --> Location
    	IF @LocationID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
        	END
    --> PurchCat
    	IF @PurchCatID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
        	END
	    --> Product Bin
		IF @BinID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END

		IF @Filter = ''
            BEGIN
				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
				SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END

        IF @NonStock = 1
            BEGIN
                SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END

		SET @Filter = @Filter + ' AND ' + ' b.On_Hand <> 0 '
		---------------------------------------------------------
		--Filter End
		---------------------------------------------------------


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '

		IF @Option = 'Type'
			SET @sql = @sql +
				' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Groups'
			SET @sql = @sql +
				' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Department'
			SET @sql = @sql +
				' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Supplier'
			SET @sql = @sql +
				' o.AO_Suppliers_ID AS [HeaderID], ' +
				' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
		ELSE
		IF @Option = 'Manufacturer'
			SET @sql = @sql +
				' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Location'
			SET @sql = @sql +
				' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Purchase Category'
			SET @sql = @sql +
				' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
				' o.[Description] AS [Filter], '

        SET @SQL = @SQL + ' p.[Description] AS [Product], '
        SET @SQL = @SQL + ' p.Product_Code AS [Code], '
        SET @SQL = @SQL + ' l.[Description] AS [Bin], '        
        SET @SQL = @SQL + ' b.On_Hand AS [Qty], '
        
        If @ValuationMethod = 0 --Average_Cost
        Begin
			SET @SQL = @SQL + ' p.Average_Cost AS [Cost], '
			SET @SQL = @SQL + ' b.On_Hand  * p.Average_Cost AS [TotalCost], '
		End	
        If @ValuationMethod = 1 --Last_Cost
        Begin
			SET @SQL = @SQL + ' p.Last_Cost AS [Cost], '
			SET @SQL = @SQL + ' b.On_Hand * p.Last_Cost AS [TotalCost], '
		End
        If @ValuationMethod = 2 --Standard_Cost
        Begin
			SET @SQL = @SQL + ' p.Standard_Cost AS [Cost], '
			SET @SQL = @SQL + ' b.On_Hand * p.Standard_Cost AS [TotalCost], '
		End
        
        SET @SQL = @SQL + ' p.Price1_Price1 AS [Price1_Price1], '        
        SET @SQL = @SQL + ' b.On_Hand * p.Price1_Price1 AS [TotalPrice1_Price1] '        

        SET @SQL = @SQL + ' FROM AP_Products p '
	    SET @SQL = @SQL + '		LEFT OUTER JOIN AP_Products_Bins b '
		SET @SQL = @SQL + '			ON p.AP_Products_ID = b.AP_Products_ID'        
	    SET @SQL = @SQL + '		INNER JOIN Lup_AP_Product_Bins l '
		SET @SQL = @SQL + '			ON b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID'
		
		
		IF @Option = 'Type'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Product_Types o ' +
				'        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
		ELSE
		IF @Option = 'Groups'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Product_Groups o ' +
				'        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
		ELSE
		IF @Option = 'Department'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Product_Departments o ' +
				'        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
		ELSE
		IF @Option = 'Supplier'
			SET @sql = @sql +
				'    LEFT JOIN AO_Suppliers o ' +
				'        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
		ELSE
		IF @Option = 'Manufacturer'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
				'        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
		ELSE
		IF @Option = 'Location'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Product_Locations o ' +
				'        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
		ELSE
		IF @Option = 'Purchase Category'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Purchase_Categories o ' +
				'        ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '
		
        SET @SQL = @SQL + @Filter


        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY l.[Description], [Filter], p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY l.[Description], [Filter], p.[Description] '
            END


    EXEC (@SQL)
--Select @SQL


SET NOCOUNT OFF	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Stock_Reconcilliation
--Purpose       :
--Date          :2004/10/15
--Authors       :TB
--Version       :1.0.0
--MODS          :
------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AP_Stock_Reconcilliation
    (
        @Filter varchar(30),
        @CompanyID tinyint,
    	@StartDate datetime,
        @EndDate datetime
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @StartDate = '2004/10/01 00:00:01'
-- SET @EndDate = '2004/10/16 08:00:01'

    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')''AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' ISNULL(dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) AS [BFWD], '
    SET @sql = @sql + ' ISNULL(dbo.fn_AP_SUM_Product_Qty_GRV(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) AS [GRV], '
    SET @sql = @sql + ' ISNULL(dbo.fn_AP_SUM_Product_Qty_ADJ(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) AS [ADJ], '
    SET @sql = @sql + ' ISNULL(dbo.fn_AP_SUM_Product_Qty_SALE(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) AS [SALE], '
    SET @sql = @sql + ' ISNULL(dbo.fn_AP_CFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @EndDate)  + '''' + '), 0) AS [CFWD], '
    SET @sql = @sql + ' ISNULL(On_Hand, 0) AS [OnHand], '
    SET @sql = @sql + ' ISNULL(dbo.fn_AP_CFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @EndDate)  + '''' + '), 0) - ISNULL(On_Hand, 0) AS [DIFF], '

    SET @sql = @sql + ' CONVERT(CHAR(10), p.Last_Sale_Date , 121) AS [LastSale], '
    SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [LastCost] '

    SET @sql = @sql + ' FROM AP_Products p '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


-- THIS only returns products with movement from @StartDate !!
--     SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
--     SET @sql = @sql + '   AND ISNULL(dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) <> 0 '
--     SET @sql = @sql + '   AND ISNULL(dbo.fn_AP_SUM_Product_Qty_GRV(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) <> 0 '
--     SET @sql = @sql + '   AND ISNULL(dbo.fn_AP_SUM_Product_Qty_ADJ(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) <> 0 '
--     SET @sql = @sql + '   AND ISNULL(dbo.fn_AP_SUM_Product_Qty_SALE(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + '), 0) <> 0 '
--     SET @sql = @sql + '   AND ISNULL(dbo.fn_AP_CFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @EndDate)  + '''' + '), 0) <> 0 '


    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND dbo.fn_AP_Product_Has_Movement(p.AP_Products_ID) = 1 '


    SET @sql = @sql + ' ORDER BY [Filter], [Product] '

--PRINT @sql

EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Surplus_Inventory
--Purpose       :Retrieves Surplus Inventory
--Functionality :    Conditional upon:
--              :        Stock > Min_Stock_Level
--              :        Is Active product
--Date          :2003/04/11
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AP_Surplus_Inventory

    (
        @Filter varchar(30),
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '
    SET @sql = @sql + ' ISNULL(p.Min_Stock_Level, 0) AS [MSL], '
    SET @sql = @sql + ' ISNULL(p.Min_Order_Qty, 0) AS [Min], '
    SET @sql = @sql + ' ISNULL(p.Max_Order_Qty, 0) AS [Max], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

--> SURPLUS STOCK
    SET @sql = @sql + ' CASE WHEN  '
    SET @sql = @sql + ' (ISNULL(p.On_Hand, 0) - ISNULL(p.Min_Stock_Level, 0)) + '
    SET @sql = @sql + '     ISNULL(( '
    SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '         FROM AO_Order_Details od '
    SET @sql = @sql + '             INNER JOIN AO_Orders o '
    SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '               o.Complete <> 1 AND '
    SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     ), 0) > ISNULL(p.Max_Order_Qty, 0) '
    SET @sql = @sql + ' THEN  '
    SET @sql = @sql + ' (ISNULL(p.On_Hand, 0) - ISNULL(p.Min_Stock_Level, 0)) + '
    SET @sql = @sql + '     ISNULL(( '
    SET @sql = @sql + '         SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '         FROM AO_Order_Details od '
    SET @sql = @sql + '             INNER JOIN AO_Orders o '
    SET @sql = @sql + '                 ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '         WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '               o.Complete <> 1 AND '
    SET @sql = @sql + '               od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     ), 0) '
    SET @sql = @sql + ' ELSE NULL '
    SET @sql = @sql + ' END '
    SET @sql = @sql + ' AS [Surplus], '

    SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [LastCost] '

    SET @sql = @sql + ' FROM AP_Products p '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

--ORIG VERSION
-----------------------------------------------------
    SET @sql = @sql + ' WHERE p.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '

--------------------------------------------------------
--> (On-Hand + On-Order) > Max_Order_Qty (Surplus Stock)
--------------------------------------------------------
    SET @sql = @sql + '   AND ((ISNULL(p.On_Hand, 0) - ISNULL(p.Min_Stock_Level, 0)) + '
    SET @sql = @sql + '         ISNULL(( '
    SET @sql = @sql + '             SELECT (SUM(od.Order_Qty) + SUM(od.Back_Order_Qty) - SUM(od.Received_Qty)) '
    SET @sql = @sql + '             FROM AO_Order_Details od '
    SET @sql = @sql + '                 INNER JOIN AO_Orders o '
    SET @sql = @sql + '                     ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '             WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '                   o.Complete <> 1 AND '
    SET @sql = @sql + '                   od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '         ), 0)) > ISNULL(p.Max_Order_Qty, 0) '

    SET @sql = @sql + ' ORDER BY [Filter], [Description] '

--PRINT @sql

EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












--EXEC sp_RPT_AP_Topseller_Analysis '2004/06/01 12:00:01 AM', '2004/09/07 11:59:59 PM', 'Groups', 0, 0, 0, 1

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Topseller_Analysis
--Purpose       :Selects ALL Products with Sales in selected SORT ORDER DESC
--Date          :2004/08/04
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AP_Topseller_Analysis
    (
        @StartDate as datetime,
        @EndDate as datetime,
        @Filter varchar(30),
        @SortOrder tinyint,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @ExclInterCo tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


--     IF @Option = 0    -- Top 20% Products
--         BEGIN
--             SET @sql = ' SELECT TOP 20 PERCENT WITH TIES '
--         END
--     ELSE
--     IF @Option = 1    -- ALL Products
--         BEGIN
            SET @sql = ' SELECT  '
--         END

    IF @Filter = 'Type'
        SET @sql = @sql + ' MAX(o.Lup_AP_Product_Types_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql + ' MAX(o.Lup_AP_Product_Groups_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql + ' MAX(o.Lup_AP_Product_Departments_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql + ' MAX(o.AO_Suppliers_ID) AS [HeaderID], MAX(o.[Supplier_Name]) AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql + ' MAX(o.Lup_AP_Product_Manufacturers_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql + ' MAX(o.Lup_AP_Product_Locations_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql + ' MAX(o.Lup_AC_Sales_Areas_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql + ' MAX(o.Lup_AS_Reps_ID) AS [HeaderID], MAX(o.[Description]) AS [Filter], '


    SET @sql = @sql + ' p.AP_Products_ID as [ID], '
    SET @sql = @sql + ' MAX(p.Description) AS [Product], '
    SET @sql = @sql + ' MAX(p.Product_Code) AS [Code], '
    SET @sql = @sql + ' MAX(s.Supplier_Name) AS [Supplier], '
    SET @sql = @sql + ' MAX(CONVERT(CHAR(10), p.Last_Sale_Date, 121)) AS [Last Sale],  '
    SET @sql = @sql + ' SUM(d.Quantity) AS [Qty], '
    SET @sql = @sql + ' MAX(p.On_Hand) AS [On Hand], '

    SET @sql = @sql + ' SUM(d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' SUM(d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '

    SET @sql = @sql + ' CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100 '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '

    SET @sql = @sql + ' MAX(dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), p.Last_Cost)) as [Std GP %], '

    SET @sql = @sql + ' MAX(CONVERT(CHAR(10), dbo.GetEffectiveDate(p.Price1_Effective_Date, p.Price2_Effective_Date, getdate()) , 121)) AS [Effective], '
    SET @sql = @sql + ' MAX(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())) as [Unit Price], '

    SET @sql = @sql + ' MAX(p.Last_Cost) AS [Last Cost], '
    SET @sql = @sql + ' MAX(p.Average_Cost) AS [Avg Cost], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' MAX(p.Min_Stock_Level) AS [MSL], '
    SET @sql = @sql + ' MAX(p.Min_Order_Qty) AS [MIN], '
    SET @sql = @sql + ' MAX(p.Max_Order_Qty) AS [MAX], '
    SET @sql = @sql + ' MAX(p.Service_Level) AS [SL], '
    SET @sql = @sql + ' MAX(p.Pack_Size) AS [Pack] '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON p.Default_Supplier_ID = s.AO_Suppliers_ID '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            '     ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Transaction_Date >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @sql = @sql + '  AND  h.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       h.Sys_AW_Transaction_Types_ID = 4)'


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END

    IF @ActiveOnly = 1      --Active Products only
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '
        END

    IF @ExclInterCo = 1      --Exclude Inter-Company Customers
        BEGIN
            SET @sql = @sql + '   AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    SET @sql = @sql + ' GROUP BY p.AP_Products_ID '


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Qty] DESC '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [NetSales] DESC '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Cost] DESC '
        END
    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [GP] DESC '
        END
    ELSE
    IF @SortOrder = 4
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END
    ELSE
    IF @SortOrder = 5
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER [Filter], [Product] '
        END


--PRINT @sql

EXEC (@sql)




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














--EXEC sp_RPT_AP_Topseller_Pareto '2004/05/01 12:00:01 AM', '2004/08/04 11:59:59 PM', 0, 0, 0, 1

-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Topseller_Pareto
--Purpose       :
--Date          :2004/08/05
--Authors       :TB
--MODS:         :
--2004.3.8      :19/05/08 - Added @ActiveOnly parameter
--2004.4.5      :28/07/09 - Added @ExclInterCo Exclude Inter-Company Customers parameter
--2004.5.0      :10/03/11 - Remoced MAX from p.AP_Products_ID. This is the GROUP BY field !!!
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AP_Topseller_Pareto
    (
        @StartDate as datetime,
        @EndDate as datetime,
        @SortOrder tinyint,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @ExclInterCo tinyint,
        @Option tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    IF @Option = 0    -- Top 20% Products
        BEGIN
            SET @sql = ' SELECT TOP 20 PERCENT WITH TIES '
        END
    ELSE
    IF @Option = 1    -- ALL Products
        BEGIN
            SET @sql = ' SELECT  '
        END

    SET @sql = @sql + ' p.AP_Products_ID as [ID], '
    SET @sql = @sql + ' MAX(p.Description) AS [Product], '
    SET @sql = @sql + ' MAX(p.Product_Code) AS [Code], '
    SET @sql = @sql + ' MAX(s.Supplier_Name) AS [Supplier], '
    SET @sql = @sql + ' MAX(CONVERT(CHAR(10), p.Last_Sale_Date, 121)) AS [Last Sale],  '
    SET @sql = @sql + ' SUM(d.Quantity) AS [Qty], '
    SET @sql = @sql + ' MAX(p.On_Hand) AS [On Hand], '

    SET @sql = @sql + ' SUM(d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' SUM(d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '

    SET @sql = @sql + ' CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100 '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '

    SET @sql = @sql + ' MAX(dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), p.Last_Cost)) as [Std GP %], '

    SET @sql = @sql + ' MAX(CONVERT(CHAR(10), dbo.GetEffectiveDate(p.Price1_Effective_Date, p.Price2_Effective_Date, getdate()) , 121)) AS [Effective], '
    SET @sql = @sql + ' MAX(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())) as [Unit Price], '

    SET @sql = @sql + ' MAX(p.Last_Cost) AS [Last Cost], '
    SET @sql = @sql + ' MAX(p.Average_Cost) AS [Avg Cost], '

--> QTY on ORDER
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' MAX(p.Min_Stock_Level) AS [MSL], '
    SET @sql = @sql + ' MAX(p.Min_Order_Qty) AS [MIN], '
    SET @sql = @sql + ' MAX(p.Max_Order_Qty) AS [MAX], '
    SET @sql = @sql + ' MAX(p.Service_Level) AS [SL], '
    SET @sql = @sql + ' MAX(p.Pack_Size) AS [Pack] '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON p.Default_Supplier_ID = s.AO_Suppliers_ID '

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Transaction_Date >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @sql = @sql + '  AND  h.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       h.Sys_AW_Transaction_Types_ID = 4)'


    IF @NonStock = 1      --IGNORE Non-Stock Items
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    IF @ActiveOnly = 1      --Active Products only
        BEGIN
            SET @sql = @sql + '   AND p.Slu_AW_Active_ID = 1 '
        END


    IF @ExclInterCo = 1      --Exclude Inter-Company Customers
        BEGIN
            SET @sql = @sql + '   AND c.Sys_AC_Account_Types_ID <> 3 '
        END

    SET @sql = @sql + ' GROUP BY p.AP_Products_ID '


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Qty] DESC '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [NetSales] DESC '
        END
    ELSE
    IF @SortOrder = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Cost] DESC '
        END
    ELSE
    IF @SortOrder = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [GP] DESC '
        END
    ELSE
    IF @SortOrder = 4
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product] '
        END
    ELSE
    IF @SortOrder = 5
        BEGIN
            SET @sql = @sql + ' ORDER BY [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER [Product] '
        END

--PRINT @sql

EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_100Perc_GP_Audit_Trail
--Purpose       :Zero Cost Sales (100% GP) Audit Trail
--Date          :2004/07/09
--Authors       :TB
--MODS:         :22/12/04 - Added @NonStock input parameter
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AS_100Perc_GP_Audit_Trail
    (
        @CompanyID int,
        @TranTypes tinyint,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @chkDayEnd tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @NonStock int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


    SET @sql = ' SELECT '

    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  h.Day_End  AS [Date], '
        END
    ELSE                 --Day range
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + ' CONVERT(CHAR(10), h.Transaction_Date, 121) AS [Date], '
            END
    ELSE                 --Day range
        BEGIN
            SET @sql = @sql + ' CONVERT(CHAR(10), h.Transaction_Date, 121) AS [Date], '
        END


    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' h.Day_End AS [Day End], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [Unit Price], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) +
        '  AND d.Unit_Cost = 0 ' +
        '  AND (h.Sys_AW_Transaction_Types_ID = 3 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 4 '


    IF @TranTypes = 1          --ALL Transaction Types
        BEGIN
            SET @sql = @sql + 
                '    OR h.Sys_AW_Transaction_Types_ID = 1 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 2 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 13 '
        END


    -- We ALWAYS need this bracket
    SET @sql = @sql + ') '



    IF @ChkDates = 1     --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END


    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  AND h.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ' '
        END
    ELSE                 --Fetch Current (Not yet Day-Ended)
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + '  AND h.Day_End IS NULL '
            END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    SET @sql = @sql + ' ORDER BY [Date], [TranID] ASC '

    EXEC (@sql)


SET NOCOUNT OFF















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_CBilling_Audit_Trail
--Purpose       :Centralised Billing Transactions Audit Trail Report
--Date          :2006/03/07
--Authors       :TB
--Version       :1.0.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AS_CBilling_Audit_Trail
    (
            @CompanyID int,
            @ChkAllCustomers int,
            @CustomerID int,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 1627
-- SET @TranTypes = 0
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' cbt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' cbt.AS_Transactions_CBilling_ID AS [ClaimID], '
    SET @sql = @sql + ' cbt.AS_Transactions_ID AS [TranID], '

    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '
    SET @sql = @sql + ' CONVERT(CHAR(10), cbt.Transaction_Date, 121) AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' cbt.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '

--     SET @sql = @sql + ' h.Total_Cost AS [Cost], '
--     SET @sql = @sql + ' h.Amount AS [Amount], '
--     SET @sql = @sql + ' h.Total_Tax_Amount AS [Tax], '
--     SET @sql = @sql + ' h.Total_Discount_Amount AS [Discount], '
--     SET @sql = @sql + ' h.Total_Amount AS [Total], '
--     SET @sql = @sql + ' h.Payment_Amount AS [Payment], '
--     SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) AS [Balance], '

--    SET @sql = @sql + ' til.[Description] AS [Till], '
    SET @sql = @sql + ' ISNULL(cas.FirstName, '''') + '' '' + '
    SET @sql = @sql + '     ISNULL(cas.Surname, '''') AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '

--    SET @sql = @sql + ' h.Cashed_Up AS [Cashed Up], '
--    SET @sql = @sql + ' h.Day_End AS [Day End], '
    SET @sql = @sql + ' h.Date_Captured AS [Captured], '

    SET @sql = @sql + ' cbt.Xmit_Date AS [XmitDate], '
    SET @sql = @sql + ' cbt.Xmit_File AS [XmitFile], '
--    SET @sql = @sql + ' LEFT(ISNULL(g.Description, ''''), 20) AS [GL Account], '

    SET @sql = @sql + ' u.UserName AS [User], '

    SET @sql = @sql + ' x.[Description] AS [Provider], '
    SET @sql = @sql + ' cbt.Customer_Number AS [AcctNo], '
    SET @sql = @sql + ' cbt.Network_Identity_Number AS [FranchiseNo], '
    SET @sql = @sql + ' cbt.Original_Number AS [OrigNo], '
    SET @sql = @sql + ' cbt.Manufacturer_Code AS [ProductCode], '
    SET @sql = @sql + ' cbt.Quantity AS [Qty], '
    SET @sql = @sql + ' cbt.Extended_Amount AS [ClaimAmount], '
    SET @sql = @sql + ' cbt.Tax_Amount AS [ClaimTax], '
    SET @sql = @sql + ' cbt.Discount_Amount AS [ClaimDiscount], '
    SET @sql = @sql + ' y.[Description] AS [FailReason], '
    SET @sql = @sql + ' cbt.Item_No AS [Item], '
    SET @sql = @sql + ' cbt.Authorization_No AS [AuthNo], '
    SET @sql = @sql + ' cbt.Registration_No AS [RegNo], '
    SET @sql = @sql + ' cbt.Odometer_Reading AS [Odo], '
    SET @sql = @sql + ' cbt.Make AS [Make], '
    SET @sql = @sql + ' cbt.Model AS [Model], '
    SET @sql = @sql + ' cbt.Model_Year AS [Year], '
    SET @sql = @sql + ' cbt.Client_ID_No AS [CustID], '
    SET @sql = @sql + ' cbt.Engine_No AS [EngineNo], '
    SET @sql = @sql + ' cbt.Chassis_No AS [ChassisNo], '
    SET @sql = @sql + ' z.[Description] AS [ClaimCode] '

--    SET @sql = @sql + ' act.[Description] AS [Active] '


    SET @sql = @sql + ' FROM AS_Transactions_CBilling cbt '
    SET @sql = @sql + '      LEFT JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = cbt.AS_Transactions_ID '
    SET @sql = @sql + '      LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users cas '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = cas.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_CBilling_Providers x '
    SET @sql = @sql + '          ON cbt.Lup_AS_CBilling_Providers_ID = x.Lup_AS_CBilling_Providers_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AP_Fail_Reasons y '
    SET @sql = @sql + '          ON cbt.Lup_AP_Fail_Reasons_ID = y.Lup_AP_Fail_Reasons_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AP_Claim_Codes z '
    SET @sql = @sql + '          ON cbt.Lup_AP_Claim_Codes_ID = z.Lup_AP_Claim_Codes_ID '


    SET @sql = @sql +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '       c.Sys_AC_Account_Types_ID = 4 AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 4) '

    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY cbt.Xmit_Date, h.Transaction_Date ASC '


    EXEC (@sql)


SET NOCOUNT OFF




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_CashUp_Audit_Trail
--Purpose       :Sales CashUp and Payment Transactions Audit Trail Report
--Date          :2003/11/11
--Authors       :TB
--Version       :1.0.0
--MODS:         :06/05/04 - Added Day-End filtering with NO Day-End resultset
--              :09/05/04 - Added Ignore TranType 18 - Settlement Discount
--              :09/05/04 - Change Date field value dependant upon Checkbox
--              :           selected in UI (None, Transaction Date, or Day-End)\
--              :28/06/04 - Replaced Cashier Fullname with Username to save space
--              :28/06/04 - Added [TranDate] to the ORDER BY statement
--              :05/08/04 - Replaced Lup_AS_Cashiers_ID with User_ID in JOIN
--              :13/11/04 - Added [CompanyID] to produce COMPANY total in report
--              :07/06/05 - Added [TranTypeID] to SEPERATE Payment (POS) sources
--2004.2.7      :31/03/06 - Changed PRIMARY table to AS_Transactions to include
--              :           PAYMENT REVERSALS
--              :31/03/06 - Added ISNULL validation to handle Payment Reversals
--              :           that are not written to AS_Transaction_Payments
--              :31/03/06 - Changed trantype filter to only select Payment types
--RL	2015-10-14	:Split display of POS and BOF EFT payments
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AS_CashUp_Audit_Trail]
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @chkDayEnd tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime
    )
AS


SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '

    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  t.Day_End  AS [Date], '
        END
    ELSE                 --Day range
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + ' CONVERT(CHAR(10), t.Transaction_Date, 121) AS [Date], '
            END
    ELSE                 --Day range
        BEGIN
            SET @sql = @sql + ' CONVERT(CHAR(10), t.Transaction_Date, 121) AS [Date], '
        END

    SET @sql = @sql + ' tp.AS_Transaction_Payments_ID AS [TranPayID], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '

    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' csh.UserName AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' ISNULL(tp.Payor_Name, '''') AS [Payor],  '
    
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) AS [Total], '
    SET @sql = @sql + ' ISNULL(t.Payment_Amount, 0) AS [Allocated], '

	--Changed V6.2 Split display of POS and BOF EFT payments
    --SET @sql = @sql + ' ISNULL(pm.[Description], ''Payment Reversals'')  AS [Method], '
	SET @sql = @sql + ' CASE t.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' WHEN 7 THEN  ''POS'' + '' - '' + ISNULL(pm.[Description], ''Payment Reversals'')'
	SET @sql = @sql + ' WHEN 21 THEN  ''BOF'' + '' - '' + ISNULL(pm.[Description], ''Payment Reversals'')'
	SET @sql = @sql + ' WHEN 22 THEN  ''BOF'' + '' - '' + ISNULL(pm.[Description], ''Payment Reversals'')'	
	SET @sql = @sql + ' ELSE ISNULL(pm.[Description], ''Payment Reversals'') '			
	SET @sql = @sql + ' END AS [Method], '    

    SET @sql = @sql + ' ISNULL(tp.Amount, 0) AS [Paid], '
    
    SET @sql = @sql + ' ISNULL(ci.[Description], ''<None>'') AS [Institution], ' 
    SET @sql = @sql + ' ISNULL(tp.Card_Expiry_Date, '''') AS [Expiry], ' 
    SET @sql = @sql + ' ISNULL(tp.Card_Number, '''') AS [Card No], '
    SET @sql = @sql + ' ISNULL(tp.Authorisation_Number, '''') AS [Auth], ' 
    SET @sql = @sql + ' t.Cashed_Up '

-- Change PRIMARY table to include PAYMENT REVERSALS not written to AS_Transaction_Payments
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AS_Transaction_Payments tp '
    SET @sql = @sql + '         ON tp.AS_Transactions_ID = t.AS_Transactions_ID '


    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = t.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users csh '
    SET @sql = @sql + '          ON t.User_ID = csh.AW_Users_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 Sys_AW_Payment_Methods pm '
    SET @sql = @sql + '         ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID ' 
    SET @sql = @sql + '     LEFT JOIN Slu_AS_Card_Institutions ci '
    SET @sql = @sql + '         ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID '
    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND (t.Sys_AW_Transaction_Types_ID = 7 '        --POS Payment
    SET @sql = @sql + '     OR t.Sys_AW_Transaction_Types_ID = 21 '         --BOF Payment
    SET @sql = @sql + '     OR t.Sys_AW_Transaction_Types_ID = 22) '        --EFT Payment


    IF @ChkDates = 1     --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END


    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  AND t.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ' '
        END
    ELSE                 --Fetch Current (Not yet Day-Ended)
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + '  AND t.Day_End IS NULL '
            END


    SET @sql = @sql + ' ORDER BY [TranTypeID], [Date], [Method], [TranDate]  ASC '


    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_CashUp_Cashiers_Audit_Trail
--Purpose       :Sales CashUp and Payment Transactions Audit Trail by Cashier
--Date          :2004/11/02
--Authors       :TB
--Version       :1.0.0
--MODS:         :07/06/05 - Added [TranTypeID] to SEPERATE Payment (POS) sources
--2004.2.7      :31/03/06 - Added ISNULL validation to handle Payment Reversals
--              :           that are not written to AS_Transaction_Payments
--              :31/03/06 - Changed trantype filter to only select Payment types
--RL	2015-10-14	:Split display of POS and BOF EFT payments
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AS_CashUp_Cashiers_Audit_Trail]
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @chkDayEnd tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime
    )
AS


SET NOCOUNT ON

    DECLARE @sql varchar(6000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.User_ID AS [CashierID], '

    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  t.Day_End  AS [Date], '
        END
    ELSE                 --Day range
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + ' CONVERT(CHAR(10), t.Transaction_Date, 121) AS [Date], '
            END
    ELSE                 --Day range
        BEGIN
            SET @sql = @sql + ' CONVERT(CHAR(10), t.Transaction_Date, 121) AS [Date], '
        END

    SET @sql = @sql + ' CONVERT(CHAR(10), t.Transaction_Date, 121) AS [TranDay], '
    SET @sql = @sql + ' tp.AS_Transaction_Payments_ID AS [TranPayID], '
    SET @sql = @sql + ' tp.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '

    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' csh.UserName AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' ISNULL(tp.Payor_Name, '''') AS [Payor],  '
    
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) AS [Total], '
    SET @sql = @sql + ' ISNULL(t.Payment_Amount, 0) AS [Allocated], '

    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) AS [Total], '
    SET @sql = @sql + ' ISNULL(t.Payment_Amount, 0) AS [Allocated], '
    
	--Changed V6.2 Split display of POS and BOF EFT payments
    --SET @sql = @sql + ' ISNULL(pm.[Description], ''Payment Reversals'')  AS [Method], '
	SET @sql = @sql + ' CASE t.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' WHEN 7 THEN  ''POS'' + '' - '' + ISNULL(pm.[Description], ''Payment Reversals'')'
	SET @sql = @sql + ' WHEN 21 THEN  ''BOF'' + '' - '' + ISNULL(pm.[Description], ''Payment Reversals'')'
	SET @sql = @sql + ' WHEN 22 THEN  ''BOF'' + '' - '' + ISNULL(pm.[Description], ''Payment Reversals'')'	
	SET @sql = @sql + ' ELSE ISNULL(pm.[Description], ''Payment Reversals'') '			
	SET @sql = @sql + ' END AS [Method], '    
    
    SET @sql = @sql + ' ISNULL(tp.Amount, 0) AS [Paid], '
    
    
    SET @sql = @sql + ' ci.[Description] AS [Institution], ' 
    SET @sql = @sql + ' ISNULL(tp.Card_Expiry_Date, '''') AS [Expiry], ' 
    SET @sql = @sql + ' ISNULL(tp.Card_Number, '''') AS [Card No], '
    SET @sql = @sql + ' ISNULL(tp.Authorisation_Number, '''') AS [Auth], ' 
    SET @sql = @sql + ' t.Cashed_Up '

-- Change PRIMARY table to include PAYMENT REVERSALS not written to AS_Transaction_Payments
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AS_Transaction_Payments tp '
    SET @sql = @sql + '         ON tp.AS_Transactions_ID = t.AS_Transactions_ID '

    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = t.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users csh '
    SET @sql = @sql + '          ON t.User_ID = csh.AW_Users_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 Sys_AW_Payment_Methods pm '
    SET @sql = @sql + '         ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID ' 
    SET @sql = @sql + '     LEFT JOIN Slu_AS_Card_Institutions ci '
    SET @sql = @sql + '         ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID '
    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND (t.Sys_AW_Transaction_Types_ID = 7 '        --POS Payment
    SET @sql = @sql + '     OR t.Sys_AW_Transaction_Types_ID = 21 '         --BOF Payment
    SET @sql = @sql + '     OR t.Sys_AW_Transaction_Types_ID = 22) '        --EFT Payment

    IF @ChkDates = 1     --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END


    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  AND t.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ' '
        END
    ELSE                 --Fetch Current (Not yet Day-Ended)
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + '  AND t.Day_End IS NULL '
            END


    SET @sql = @sql + ' ORDER BY [CompanyID], [CashierID], [TranTypeID], [Date], [Method], [TranDate] ASC '



    EXEC (@sql)


SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Customer_Sales_Filter
--Purpose       :Simplified Customer Sales from/to DayEnd date
--Functionality :
--Date          :2009/09/02
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                       PROCEDURE sp_RPT_AS_Customer_Sales_Filter
    (
        @FilterP tinyint,
        @FilterC tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @ChkAllCustomers int,
        @Level tinyint,
        @CustomerID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @FilterP = 2
-- SET @FilterC = 1
-- SET @DayEndFromDate = '2009/06/01 16:47:00'
-- SET @DayEndToDate = '2009/06/10 17:01:00'
-- SET @ChkAllCustomers = 1
-- SET @CustomerID = 0
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @FilterP = 0
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 1
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 2
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 3
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [PHeaderID], ' +
            ' o.[Supplier_Name] AS [PFilter], '
    ELSE
    IF @FilterP = 4
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 5
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 6
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 7
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '


    IF @FilterC = 0
        SET @sql = @sql +
            ' x.Lup_AC_Customer_Types_ID AS [CHeaderID], ' +
            ' x.[Description] AS [CFilter], '
    ELSE
    IF @FilterC = 1
        SET @sql = @sql +
            ' x.Lup_AC_Customer_Groups_ID AS [CHeaderID], ' +
            ' x.[Description] AS [CFilter], '
    ELSE
    IF @FilterC = 2
        SET @sql = @sql +
            ' x.Sys_AC_Account_Types_ID AS [CHeaderID], ' +
            ' x.[Description] AS [CFilter], '
    ELSE
    IF @FilterC = 3
        SET @sql = @sql +
            ' x.Sys_AC_Account_Status_ID AS [CHeaderID], ' +
            ' x.[Description] AS [CFilter], '


    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '      THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '      THEN ''C/N'' '
    SET @sql = @sql + '      ELSE ''INV'' '
    SET @sql = @sql + ' END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + ' END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, ISNULL(p.Standard_Cost, 0) * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * ISNULL(p.Standard_Cost, 0))) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, ISNULL(p.Standard_Cost, 0))) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + ' END AS [Std GP%], '
    SET @sql = @sql + ' u.UserName AS [User] '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + ' INNER JOIN AS_Transactions h '
    SET @sql = @sql + ' ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + ' INNER JOIN AP_Products p '
    SET @sql = @sql + ' ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + ' ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + ' ON h.User_ID = u.AW_Users_ID '


    IF @FilterP = 0
        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 @FilterP = 1
        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 @FilterP = 2
        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 @FilterP = 3
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            ' ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @FilterP = 4
        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 @FilterP = 5
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            ' ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @FilterP = 6
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            ' ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @FilterP = 7
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            ' ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    IF @FilterC = 0
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Customer_Types x ' +
            ' ON c.Lup_AC_Customer_Types_ID = x.Lup_AC_Customer_Types_ID '
    ELSE
    IF @FilterC = 1
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Customer_Groups x ' +
            ' ON c.Lup_AC_Customer_Groups_ID = x.Lup_AC_Customer_Groups_ID '
    ELSE
    IF @FilterC = 2
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Account_Types x ' +
            ' ON c.Sys_AC_Account_Types_ID = x.Sys_AC_Account_Types_ID '
    ELSE
    IF @FilterC = 3
        SET @sql = @sql +
            ' LEFT JOIN Sys_AC_Account_Status x ' +
            ' ON c.Sys_AC_Account_Status_ID = x.Sys_AC_Account_Status_ID '


    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' '
    SET @sql = @sql + '  AND  h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '   OR  h.Sys_AW_Transaction_Types_ID = 4) '


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @Level = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Customer] '
        END
    ELSE
    IF @Level = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [CFilter], [PFilter], [Customer] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [CFilter], [PFilter], [Customer], [Product], [DocNo], [TranDate] '
        END

--PRINT @sql

EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Cashier_Jobcards
--Purpose       :Jobcards from Starting DayEnd date to Ending DayEnd date
--              :by Cashier (User) by Filter
--Date          :2008/03/02
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AS_DayEnd_Cashier_Jobcards
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

-- SET @Option = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '
    SET @sql = @sql + ' h.User_ID AS [CashierID], '
    SET @sql = @sql + ' ISNULL(u.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(u.Surname, '''') AS [Cashier], '

    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [RepName], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '       h.Sys_AW_Transaction_Types_ID = 2 '

    SET @sql = @sql +
        ' ORDER BY [CashierID], [Filter], [Customer], [TranDate] '

--PRINT @sql

EXEC (@sql)














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Cashier_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--              :by Cashier (User) by Filter
--Date          :2004/07/22
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AS_DayEnd_Cashier_Sales
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

-- SET @Option = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '
    SET @sql = @sql + ' h.User_ID AS [CashierID], '
    SET @sql = @sql + ' ISNULL(u.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(u.Surname, '''') AS [Cashier], '

    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [RepName], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    SET @sql = @sql +
        ' ORDER BY [CashierID], [Filter], [Customer], [TranDate] '

--PRINT @sql

EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Customer_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by CUSTOMER by Sales Person by Filter
--Date          :2003/08/27
--Authors       :TB
--MODS:         :15/04/04 - Added 'Cashier' filter
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
--V6.3	RL	2017/09/10	:Added Sys_AW_Transaction_Types_ID Option
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Customer_Sales]
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
		@Sys_AW_Transaction_Types_ID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(5000)

-- SET @Option = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '


    SET @sql = @sql + ' r.Lup_AS_Reps_ID AS [RepID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [RepName], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '

--     SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
--     SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
--     SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


--------------------------------------------------------------------------------------------
--> Floor_Rep_Sales extracts Rep from AS_Transactions rather than AC_Customers
--------------------------------------------------------------------------------------------
--     SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
--     SET @sql = @sql + '          ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
--------------------------------------------------------------------------------------------


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '       h.Slu_AW_Active_ID = 1'



		If @Sys_AW_Transaction_Types_ID <> 0
		BEGIN
			SET @sql = @sql + '     AND (h.Sys_AW_Transaction_Types_ID = ' + CONVERT(varchar(10), @Sys_AW_Transaction_Types_ID) + ')  ' 
        END

    SET @sql = @sql +
        ' ORDER BY [Customer], [RepID], [Filter], [TranDate] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Customer_Type_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by CUSTOMER TYPE by Filter
--Date          :2004/01/14
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AS_DayEnd_Customer_Type_Sales
    (
        @Option varchar(30),
        @CustType tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

-- SET @Option = 'Department'
-- SET @CustType = 0
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'
-- SET @CompanyID = 1


    IF @CustType = 0
        BEGIN

            SET @sql = ' SELECT '
        
            SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '
            SET @sql = @sql + ' ct.Description AS [CustType], '
        
            SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
            SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
            SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
            SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
        
        
            SET @sql = @sql + ' r.Lup_AS_Reps_ID AS [RepID], '
            SET @sql = @sql + ' r.[Description] AS [RepName], '
        
            IF @Option = 'Type'
                SET @sql = @sql +
                    ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
                    ' o.[Description] AS [Filter], '
            ELSE
            IF @Option = 'Groups'
                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], '
            ELSE
            IF @Option = 'Sales Area'
                SET @sql = @sql +
                    ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
                    ' o.[Description] AS [Filter], '
        
        --     SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
        --     SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
        --     SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
        
            SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
            SET @sql = @sql + ' tt.[Description] AS [TranType], '
            SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
            SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
            SET @sql = @sql + ' h.Comment AS [ShortComment], '
            SET @sql = @sql + ' p.[Description] AS [Product], '
        
            SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--            SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
            SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
            SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
            SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
            SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
            SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '
        
            SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
            SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
            SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Act GP%], '
            SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Std GP%], '
        
            SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
            SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '
        
            SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Ave Cost], '
        
            SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Ave Sell], '
            
            SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Ave Disc], '
        
            SET @sql = @sql + ' u.UserName AS [User] '
            
            SET @sql = @sql + ' FROM AS_Transaction_Details d '
            SET @sql = @sql + '      INNER JOIN AS_Transactions h '
            SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
            SET @sql = @sql + '      INNER JOIN AP_Products p '
            SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '      INNER JOIN AC_Customers c '
            SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
            SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Types ct '
            SET @sql = @sql + '          ON c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
            SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
            SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
            SET @sql = @sql + '      LEFT JOIN AW_Users u '
            SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
        
        
        --------------------------------------------------------------------------------------------
        --> Floor_Rep_Sales extracts Rep from AS_Transactions rather than AC_Customers
        --------------------------------------------------------------------------------------------
        --     SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
        --     SET @sql = @sql + '          ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
        
            SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
            SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
        --------------------------------------------------------------------------------------------
        
        
            IF @Option = 'Type'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Types o ' +
                    '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
            ELSE
            IF @Option = 'Groups'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Groups o ' +
                    '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
            ELSE
            IF @Option = 'Department'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Departments o ' +
                    '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
            ELSE
            IF @Option = 'Supplier'
                SET @sql = @sql +
                    '    LEFT JOIN AO_Suppliers o ' +
                    '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
            ELSE
            IF @Option = 'Manufacturer'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
                    '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
            ELSE
            IF @Option = 'Location'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Locations o ' +
                    '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
            ELSE
            IF @Option = 'Sales Area'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AC_Sales_Areas o ' +
                    '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
        
            SET @sql = @sql +
                ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
                '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
                '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
                '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
                '       h.Sys_AW_Transaction_Types_ID = 4)'
        
            SET @sql = @sql +        
        --        ' ORDER BY [Customer], [RepID], [Filter], [TranDate] '
                ' ORDER BY [CustType], [Filter], [Product], [TranDate] '

        END

    ELSE
        BEGIN

            SET @sql = ' SELECT '
        
            SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '
            SET @sql = @sql + ' ct.Description AS [CustType], '
        
            SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
            SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
            SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
            SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
        
        
            SET @sql = @sql + ' r.Lup_AS_Reps_ID AS [RepID], '
            SET @sql = @sql + ' r.[Description] AS [RepName], '
        
            IF @Option = 'Type'
                SET @sql = @sql +
                    ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
                    ' o.[Description] AS [Filter], '
            ELSE
            IF @Option = 'Groups'
                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], '
            ELSE
            IF @Option = 'Sales Area'
                SET @sql = @sql +
                    ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
                    ' o.[Description] AS [Filter], '
        
        --     SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
        --     SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
        --     SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
        
            SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
            SET @sql = @sql + ' tt.[Description] AS [TranType], '
            SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
            SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
            SET @sql = @sql + ' h.Comment AS [ShortComment], '
            SET @sql = @sql + ' p.[Description] AS [Product], '
        
            SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--            SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
            SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
            SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
            SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
            SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
            SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '
        
            SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
            SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
            SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Act GP%], '
            SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Std GP%], '
        
            SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
            SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '
        
            SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Ave Cost], '
        
            SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Ave Sell], '
            
            SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
            SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
            SET @sql = @sql + '      ELSE 0.00 '
            SET @sql = @sql + '      END AS [Ave Disc], '
        
            SET @sql = @sql + ' u.UserName AS [User] '
            
            SET @sql = @sql + ' FROM AS_Transaction_Details d '
            SET @sql = @sql + '      INNER JOIN AS_Transactions h '
            SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
            SET @sql = @sql + '      INNER JOIN AP_Products p '
            SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
            SET @sql = @sql + '      INNER JOIN AC_Customers c '
            SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
            SET @sql = @sql + '      LEFT JOIN Lup_AC_Customer_Types ct '
            SET @sql = @sql + '          ON c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
            SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
            SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
            SET @sql = @sql + '      LEFT JOIN AW_Users u '
            SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
        
        
        --------------------------------------------------------------------------------------------
        --> Floor_Rep_Sales extracts Rep from AS_Transactions rather than AC_Customers
        --------------------------------------------------------------------------------------------
        --     SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
        --     SET @sql = @sql + '          ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
        
            SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
            SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
        --------------------------------------------------------------------------------------------
        
        
            IF @Option = 'Type'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Types o ' +
                    '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
            ELSE
            IF @Option = 'Groups'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Groups o ' +
                    '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
            ELSE
            IF @Option = 'Department'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Departments o ' +
                    '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
            ELSE
            IF @Option = 'Supplier'
                SET @sql = @sql +
                    '    LEFT JOIN AO_Suppliers o ' +
                    '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
            ELSE
            IF @Option = 'Manufacturer'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
                    '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
            ELSE
            IF @Option = 'Location'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AP_Product_Locations o ' +
                    '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
            ELSE
            IF @Option = 'Sales Area'
                SET @sql = @sql +
                    '    LEFT JOIN Lup_AC_Sales_Areas o ' +
                    '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
        
            SET @sql = @sql +
                ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
                '       c.Lup_AC_Customer_Types_ID = ' + CONVERT(varchar(30), @CustType) + ' AND ' +
                '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
                '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
                '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
                '       h.Sys_AW_Transaction_Types_ID = 4)'
        
            SET @sql = @sql +        
        --        ' ORDER BY [Customer], [RepID], [Filter], [TranDate] '
                ' ORDER BY [CustType], [Filter], [Product], [TranDate] '

        END

--PRINT @sql

EXEC (@sql)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Export_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by EXPORT CUSTOMER by Filter
--Date          :2011/03/08
--Authors       :TB
--MODS:         :
--RL	V6.1	2015-02-19	:Removed Customer Account Type Check. Does not make sense???
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Export_Sales]
    (
        @Filter varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Tax_Rate decimal(5,2),
            @TaxRate varchar(30)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


------------------------------------------------------------------------------
    --> Get the STANDARD VAT rate
------------------------------------------------------------------------------
    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

--    SET @Tax_Rate = @Tax_Rate / 100

    SET @TaxRate = CONVERT(varchar(30), @Tax_Rate)
------------------------------------------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '


    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '
    SET @sql = @sql + ' tc.[Description] AS [TaxCode], '
    SET @sql = @sql + ' tc.Tax_Rate AS [TaxRate], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '          ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)  ' 
      --  '       c.Sys_AC_Account_Types_ID = 7 ' Export WTF????

    SET @sql = @sql + ' ORDER BY [Customer], [Filter], [TranDate] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Floor_Rep_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by FLOOR Sales Person (POS selected Rep) by Filter
--Date          :2003/08/22
--Authors       :TB
--MODS:         :15/04/04 - Added 'Cashier' filter
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AS_DayEnd_Floor_Rep_Sales
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

-- SET @Option = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '
    SET @sql = @sql + ' r.Lup_AS_Reps_ID AS [RepID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [RepName], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    SET @sql = @sql +
        ' ORDER BY [RepID], [Filter], [Customer], [TranDate] '

--PRINT @sql

EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Performance
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--              :netted by Inter-Company by Filter
--Functionality :NB SP used by BOTH Sales Performae and Sales Performance with QTY
--Date          :2004/01/28
--Authors       :TB
--MODS:         :03/07/04 - Moved Lup_AC_Customer_Types_ID to Sys_AC_Account_Types_ID 
--              :           and replaced @CustType input parameter with @AccountType
--              :22/11/04 - Added ISNULL validation on all Numeric DB fields 
--              :03/05/05 - Added [Qty] and removed [TranDate] and [TranNo] (Protea)

--              :03/05/05 - Added 'Sales Person' filter (Protea)
--RL	V6.2	2016-06-24	:Add ISNULL check to Extended_Amount, Tax_Amount, Quantity And Unit_Cost
--RL	V6.2	2016-06-24	:Added Product Purchase Category group option
--RL	V6.2	2016-06-24	:Added Product Bin group option
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Performance]
    (
        @Option_1 varchar(30),
        @Option_2 varchar(30),        
        @AccountType tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

-- SET @Option = 'Bin'
-- SET @AccountType = 0
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '

	--@Option_1
    IF @Option_1 = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Group'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Option_1 = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Purchase Category'
        SET @sql = @sql +
            ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Bin'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Bins_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

	--@Option_2
    IF @Option_2 = 'Type'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Types_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Group'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Groups_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Department'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Departments_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Supplier'
        SET @sql = @sql +
            ' x.AO_Suppliers_ID AS [HeaderID_2], ' +
            ' x.[Supplier_Name] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Manufacturer'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Manufacturers_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Location'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Locations_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Purchase Category'
        SET @sql = @sql +
            ' x.Lup_AP_Purchase_Categories_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Bin'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Bins_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Sales Area'
        SET @sql = @sql +
            ' x.Lup_AC_Sales_Areas_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Sales Person'
        SET @sql = @sql +
            ' x.Lup_AS_Reps_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = '<None>'
        SET @sql = @sql +
--            ' o.Lup_AS_Reps_ID AS [HeaderID_2], ' +
--            ' o.[Description] AS [Filter_2], '

            ' 0 AS [HeaderID_2], ' +
            ''' <None>''' + ' AS [Filter_2], '



    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) AS [TotalSales], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN ISNULL(ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), 0) '
    SET @sql = @sql + '      ELSE 0 '
    SET @sql = @sql + '      END AS [InterCo], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN 0 '
    SET @sql = @sql + '      ELSE ISNULL(ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), 0) '
    SET @sql = @sql + '      END AS [NetSales], '

    SET @sql = @sql + ' CONVERT(money, (ISNULL(d.Extended_Amount,0) - ISNULL(d.Tax_Amount,0)) - (ISNULL(d.Quantity,0) * ISNULL(d.Unit_Cost,0))) AS [TotalGP], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN CONVERT(money, (ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) - (ISNULL(d.Quantity, 0) * ISNULL(d.Unit_Cost, 0))) '
    SET @sql = @sql + '      ELSE 0 '
    SET @sql = @sql + '      END AS [InterCoGP], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN 0 '
    SET @sql = @sql + '      ELSE CONVERT(money, (ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) - (ISNULL(d.Quantity, 0) * ISNULL(d.Unit_Cost, 0))) '
    SET @sql = @sql + '      END AS [NetGP], '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0), ISNULL(d.Quantity,0), ISNULL(d.Unit_Cost,0))) / dbo.fn_AS_Calc_Act_Sales_Value(ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [TotGP%], '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(ISNULL(d.Original_Price,0), ISNULL(d.Unit_Cost,0), ISNULL(d.Quantity,0))) / dbo.fn_AS_Calc_Std_Sales_Value(ISNULL(d.Original_Price,0), ISNULL(d.Quantity,0)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [StdGP%], '

    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Unit_Cost, 0) * ISNULL(d.Quantity, 0)) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Original_Price, 0) * ISNULL(d.Quantity, 0)) AS [Selling], '

    SET @sql = @sql + ' ISNULL(d.Quantity, 0) AS [Qty], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '

	--@Option_1
    IF @Option_1 = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option_1 = 'Group'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option_1 = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option_1 = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option_1 = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option_1 = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option_1 = 'Purchase Category'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Purchase_Categories o ' +
            '        ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '
    ELSE
    IF @Option_1 = 'Bin'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Bins o ' +
            '        ON d.Lup_AP_Product_Bins_ID = o.Lup_AP_Product_Bins_ID '
    ELSE
    IF @Option_1 = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option_1 = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

	--@Option_2
    IF @Option_2 = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types x ' +
            '        ON p.Lup_AP_Product_Types_ID = x.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option_2 = 'Group'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups x ' +
            '        ON p.Lup_AP_Product_Groups_ID = x.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option_2 = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments x ' +
            '        ON p.Lup_AP_Product_Departments_ID = x.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option_2 = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers x ' +
            '        ON p.Default_Supplier_ID = x.AO_Suppliers_ID '
    ELSE
    IF @Option_2 = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers x ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = x.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option_2 = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations x ' +
            '        ON p.Lup_AP_Product_Locations_ID = x.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option_2 = 'Purchase Category'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Purchase_Categories x ' +
            '        ON p.Lup_AP_Purchase_Categories_ID = x.Lup_AP_Purchase_Categories_ID '
    ELSE
    IF @Option_2 = 'Bin'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Bins x ' +
            '        ON d.Lup_AP_Product_Bins_ID = x.Lup_AP_Product_Bins_ID '
    ELSE
    IF @Option_2 = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas x ' +
            '        ON c.Lup_AC_Sales_Areas_ID = x.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option_2 = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps x ' +
            '        ON c.Lup_AS_Reps_ID = x.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'


    IF @AccountType <> 0        --0 = ALL Account Types
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID = ' + CONVERT(varchar(10), @AccountType) + ' '
        END

	--IF @Option_2 = '<All>'
	--    SET @sql = @sql + ' ORDER BY [Filter], [Product], [TranDate] '
	--Else
		SET @sql = @sql + ' ORDER BY [Filter_2], [Filter], [Product], [TranDate] '    

--Select @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Product_Sales_Analysis
--Purpose       :Day-End Sales by Filter with Product Sales detail ONLY
--Functionality :
--Date          :2003/09/11
--Authors       :TB
--MODS:         :15/04/04 - Added 'Cashier' filter
--              :08/08/04 - Truncated [TranDate] field
--              :06/03/05 - Added Product_Code [Code] field
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
--2004.5.3      :04/08/11 - Modified [Ave Sell] field to reflect Net Sales Average
--              :04/08/11 - Added [UnitSelling] field to SUM Unit Price value for Average calc
--2004.5.8 RGL  :2013-02-20 - Added product group to order by clause
--RL	V6.2	2016-06-24	:Added Product Purchase Category group option
--RL	V6.2	2016-06-24	:Added Product Bin group option
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AS_DayEnd_Product_Sales_Analysis]
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @Option = 'Groups'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '

    SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '
    ELSE
    IF @Option = 'Purchase Category'
        SET @sql = @sql +
            ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Bins'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Bins_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product], '
    SET @sql = @sql + ' ISNULL(p.Product_Code, '''') AS [Code], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' CONVERT(CHAR(10), h.Transaction_Date, 121) AS [TranDate],  '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '


    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [UnitSelling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
--    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Extended_Amount - d.Tax_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '
    ELSE
    IF @Option = 'Purchase Category'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Purchase_Categories o ' +
            '        ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '
    ELSE
    IF @Option = 'Bins'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Bins o ' +
            '        ON d.Lup_AP_Product_Bins_ID = o.Lup_AP_Product_Bins_ID '


    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    SET @sql = @sql +
--        ' ORDER BY [Filter], [Customer], [TranDate] '
        ' ORDER BY [Filter], [Product], [Code], [TranDate] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Rep_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by Sales Person by Filter
--Date          :2003/02/05
--Authors       :TB
--MODS:         :15/04/04 - Added 'Cashier' filter
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AS_DayEnd_Rep_Sales
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(5000)

-- SET @Option = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '
    SET @sql = @sql + ' r.Lup_AS_Reps_ID AS [RepID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [RepName], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '          ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    SET @sql = @sql +
        ' ORDER BY [RepID], [Filter], [Customer], [TranDate] '

--PRINT @sql

EXEC (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :
--Date          :2003/01/11
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AS_DayEnd_Sales
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @Option = 'Groups'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    SET @sql = @sql +
        ' ORDER BY [Filter], [Customer], [TranDate] '

--PRINT @sql

EXEC (@sql)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Zero_VAT_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by CUSTOMER with ZERO VAT Sales by Filter
--Date          :2005/11/25
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
--              :08/03/11 - Added [TaxCode] and [TaxRate] fields
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AS_DayEnd_Zero_VAT_Sales
    (
        @Filter varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int,
        @Option tinyint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Tax_Rate decimal(5,2),
            @TaxRate varchar(30)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


------------------------------------------------------------------------------
    --> Get the STANDARD VAT rate
------------------------------------------------------------------------------
    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

--    SET @Tax_Rate = @Tax_Rate / 100

    SET @TaxRate = CONVERT(varchar(30), @Tax_Rate)
------------------------------------------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '


    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '
    SET @sql = @sql + ' tc.[Description] AS [TaxCode], '
    SET @sql = @sql + ' tc.Tax_Rate AS [TaxRate], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '          ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4) '


    IF @Option = 0
        BEGIN
            SET @sql = @sql + '       AND (h.Total_Tax_Amount = 0 AND h.Total_Amount <> 0) '
        END


    ELSE
    IF @Option = 1
        BEGIN
            SET @sql = @sql + '       AND (h.Total_Tax_Amount = 0 AND h.Total_Amount = 0) '
        END


    ELSE
    IF @Option = 2
        BEGIN
--            SET @sql = @sql + '       AND (ROUND((h.Total_Amount * (@TaxRate / (100 + @TaxRate))) ,2) <> h.Total_Tax_Amount AND h.Total_Amount <> 0) '
            SET @sql = @sql + '       AND (ROUND((h.Total_Amount * (' + @TaxRate + ' / (100 + ' + @TaxRate + '))) ,2) <> h.Total_Tax_Amount AND h.Total_Amount <> 0) '
        END


    SET @sql = @sql +
        ' ORDER BY [Customer], [Filter], [TranDate] '

--PRINT @sql

EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Day_End
--Purpose       :Day End sales totals extract from AS_Transactions
--Functionality :Uses LEFT OUTER JOIN on Tran Details and Products
--Date          :2004/01/10
--Authors       :TB
--MODS:         :16/06/04 - Added ISNULL validation for most fields
--              :17/06/04 - Removed the Transaction Detail field now displayed
--              :           in the Detail SubReport
--2004.3.5      :28/04/07 - Modified SORT ORDER to add [TranDate] to precede [TranNo]
--2004.4.7      :13/09/09 - Added @chkTranType14 for Stock Transfers
-------------------------------------------------------------------------------

CREATE                 PROCEDURE sp_RPT_AS_Day_End
    (
        @ttCount tinyint,
        @chkTranType1 tinyint,
        @chkTranType2 tinyint,
        @chkTranType3 tinyint,
        @chkTranType4 tinyint,
        @chkTranType5 tinyint,
        @chkTranType6 tinyint,
        @chkTranType7 tinyint,
        @chkTranType8 tinyint,
        @chkTranType9 tinyint,
        @chkTranType10 tinyint,
        @chkTranType11 tinyint,
        @chkTranType12 tinyint,
        @chkTranType13 tinyint,
        @chkTranType14 tinyint,
        @chkDayEnd tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(7000),
            @filter varchar(2000),
            @cnt tinyint


-- SET @ttCount = 8
-- SET @chkTranType1 = 0
-- SET @chkTranType2 = 0
-- SET @chkTranType3 = 1
-- SET @chkTranType4 = 1
-- SET @chkTranType5 = 1
-- SET @chkTranType6 = 1
-- SET @chkTranType7 = 0
-- SET @chkTranType8 = 1
-- SET @chkTranType9 = 0
-- SET @chkTranType10 = 0
-- SET @chkTranType11 = 1
-- SET @chkTranType12 = 1
-- SET @chkTranType13 = 1
-- SET @chkTranType14 = 1
-- SET @chkDayEnd = 0
-- SET @DayEndFromDate = '2003-10-02 07:37:00'
-- SET @DayEndToDate = '2003-10-31 17:42:00'
-- SET @CompanyID = 1



    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '

    SET @sql = @sql + ' ISNULL(h.Lup_AS_Cashiers_ID, 1) AS [CashierID], '
    SET @sql = @sql + ' ISNULL(h.Lup_AS_Tills_ID, 1) AS [TillID], '
    SET @sql = @sql + ' ISNULL(h.Lup_AS_Reps_ID, 1) AS [RepID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustomerID], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [CustRef], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '
    SET @sql = @sql + ' tt.[Description] + ''s''' + ' AS [TranType], '

    SET @sql = @sql + ' ISNULL(h.Total_Cost, 0) AS [HCost], '
--    SET @sql = @sql + ' ISNULL(h.Amount, 0) AS [HAmount], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount - h.Total_Tax_Amount, 0) AS [HAmount], '
    SET @sql = @sql + ' ISNULL(h.Total_Tax_Amount, 0) AS [HTax], '
    SET @sql = @sql + ' ISNULL(h.Total_Discount_Amount, 0) AS [HDiscount], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) AS [HTotal], ' 
    SET @sql = @sql + ' ISNULL(h.Payment_Amount, 0) AS [HPayment], '

    SET @sql = @sql + ' ISNULL(u.UserName, '''') AS [Cashier], '
--    SET @sql = @sql + ' csh.[Description] AS [Cashier], '
    SET @sql = @sql + ' ISNULL(til.[Description], '''') AS [Till], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [Active] '

    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      INNER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      INNER JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      INNER JOIN AW_Users u '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    IF @chkDayEnd = 1    --Fetch Previous Day-End
        SET @sql = @sql +
            ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
            '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
            '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') '
    ELSE                 --Fetch Current (Not yet Day-Ended)    
        SET @sql = @sql +
            ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
            '       h.Day_End IS NULL '

    SET @filter = ' '

    IF @ttCount > 0
        BEGIN
            SET @filter = ' AND ( '
            SET @cnt = 0

            IF @chkTranType1 = 1
                BEGIN
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 1 '    --Quote
                    SET @cnt = @cnt + 1
                END
        
            IF @chkTranType2 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 2 '    --Job
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType3 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 3 '    --Invoice
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType4 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 4 '    --Refund
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType5 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 5 '    --Journal
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType6 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 7 '    --POS Payment
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType7 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 13 '    --Pro Forma
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType8 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 15 '    --Interest
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType9 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 16 '    --Sales Order
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType10 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 17 '    --Sales Order Reversal
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType11 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 18 '    --Settlement
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType12 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 21 '    --Back Office Receipt
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType13 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 22 '    --EFT Receipt
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType14 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 23 '    --Stock Transfer
                    SET @cnt = @cnt + 1
                END

            IF @ttCount > 0
                SET @filter = @filter + ' ) '

        END

    SET @sql = @sql + @filter

    SET @sql = @sql + ' ORDER BY [CompanyID], [TranTypeID], [TranDate], [TranNo] '


--PRINT @sql

EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Day_End_Detail
--Purpose       :Day End Transaction Detail extracted from AS_Transaction_Details
--Functionality :
--Date          :2004/06/17
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AS_Day_End_Detail
    (
        @TranID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' d.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Quantity), 0) AS [Qty], '
--    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price * d.Quantity), 0) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Discount_Amount), 0) AS [Discount], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Tax_Amount), 0) AS [Tax], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Extended_Amount), 0) AS [Total], '

    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Cost * d.Quantity), 0) AS [Cost], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' ISNULL(CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [Price Adj], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Discount_Amount - d.Original_Discount), 0) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '

    SET @sql = @sql + ' WHERE d.AS_Transactions_ID = ' + CONVERT(varchar(10), @TranID)


--PRINT @sql

EXEC (@sql)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Day_End_Till_Payouts
--Purpose       :Day End Till Payouts Transaction Detail
--Functionality :
--Date          :2009/08/08
--Authors       :TB
--MODS:         :
--2004.4.8      :30/01/10 - Added Expense Payout - (Tax Invoice) (Expense Tax Payout)
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AS_Day_End_Till_Payouts
    (
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @chkDayEnd tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AS_Till_Payouts_ID AS [TranID], '
    SET @sql = @sql + ' t.Payout_Date AS [TranDate], '
    SET @sql = @sql + ' t.Payout_Number AS [TranNo], '
    SET @sql = @sql + ' t.Sys_AB_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' ISNULL(tt.Transaction_Code, '''') AS [TranType], '

    SET @sql = @sql + ' CASE WHEN t.Payout_Type_ID = 0 '
    SET @sql = @sql + '      THEN ''Expense with Tax'' '
    SET @sql = @sql + '      WHEN t.Payout_Type_ID = 1 '
    SET @sql = @sql + '      THEN ''Expense no Tax'' '
    SET @sql = @sql + '      WHEN t.Payout_Type_ID = 2 '
    SET @sql = @sql + '      THEN ''Supplier'' '
    SET @sql = @sql + ' END AS [PayType], '

    SET @sql = @sql + ' ISNULL(t.[Description], '''') AS [Description], '
    SET @sql = @sql + ' ISNULL(t.Narration, '''') AS [Narration], '
    SET @sql = @sql + ' ISNULL(t.Amount, 0) AS [Amount], '
    SET @sql = @sql + ' dr.Description AS [AccountDR], '
    SET @sql = @sql + ' cr.Description AS [AccountCR], '
    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [SupplierName], '
    SET @sql = @sql + ' m.[Description] AS [Month], '
    SET @sql = @sql + ' y.[Description] AS [Year], '
    SET @sql = @sql + ' u.UserName AS [Cashier] '

    SET @sql = @sql + ' FROM AS_Till_Payouts t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts dr '
    SET @sql = @sql + '         ON t.AB_Account_DR_ID = dr.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts cr '
    SET @sql = @sql + '         ON t.AB_Account_CR_ID = cr.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkDates = 1     --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Payout_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Payout_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END

    IF @chkDayEnd = 1    --Day-End range
        BEGIN
            SET @sql = @sql + '  AND t.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ' '
        END
    ELSE                 --Fetch Current (Not yet Day-Ended)
        IF @ChkDates <> 1     --Only if From/To Dates NOT SET
            BEGIN
                SET @sql = @sql + '  AND t.Day_End IS NULL '
            END

    SET @sql = @sql + ' ORDER BY [TranDate] ASC '


    EXEC (@sql)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Enterprise_Customer_Sales
--Purpose       :Fetch Enterprise Customer Sales
--Date          :2007/03/16
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AS_Enterprise_Customer_Sales
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AS_Enterprise_Customer_Sales '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [CustNo] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Customer] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Enterprise_GP
--Purpose       :Fetch Enterprise GP
--Date          :2009/09/04
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                  PROCEDURE sp_RPT_AS_Enterprise_GP
    (
        @FetchType tinyint
    )
AS

SET NOCOUNT ON


	DECLARE @sql varchar(1000)


    IF @FetchType = 1        --If GP% recalculate GP% because Insert AGGREGATED ALL percentages
        BEGIN
            UPDATE AS_Enterprise_GP
            SET Total = CASE WHEN TotalSales <> 0
                             THEN ROUND((((TotalSales - TotalCost) / TotalSales) * 100), 2)
                             ELSE 0
                        END
        END


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AS_Enterprise_GP '
    SET @sql = @sql + ' ORDER BY [Filter], [Description] '


    EXEC (@sql)



SET NOCOUNT OFF	


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Enterprise_Sales
--Purpose       :Fetch Enterprise Sales
--Date          :2007/03/12
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AS_Enterprise_Sales
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AS_Enterprise_Sales '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Enterprise_Sales_All
--Purpose       :Fetch Enterprise Sales All
--Date          :2009/09/30
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AS_Enterprise_Sales_All
    (
        @Sort int
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(2000)


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AS_Enterprise_Sales_All '


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product_Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













--EXEC sp_RPT_AS_GP_Audit_Trail 1, 1, 1022, 1, 0, '2003/02/28 12:00:01 AM', '2004/04/14 11:59:59 PM'

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_GP_Audit_Trail
--Purpose       :Sales Transactions Gross Profit Audit Trail
--Date          :2003/11/22
--Authors       :TB
--Version       :1.0.0
--MODS:         :14/04/04 - Fixed that we ALWAYS need this bracket when ANY
--                          Transaction Types selection
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AS_GP_Audit_Trail
    (
            @CompanyID int,
            @ChkAllCustomers int,
            @CustomerID int,
            @TranTypes tinyint,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('' '' + c.Firstnames, ''''))) AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [OrderNo], '
    SET @sql = @sql + ' h.Comment AS [Asset], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' til.[Description] AS [Till], '
    SET @sql = @sql + ' ISNULL(cas.FirstName, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(cas.Surname, '''') AS [Cashier], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' h.Day_End AS [Day End], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [Unit Price], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users cas '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = cas.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) +
        '  AND (h.Sys_AW_Transaction_Types_ID = 3 ' +
        '    OR h.Sys_AW_Transaction_Types_ID = 4 '

    IF @TranTypes = 1          --ALL Transaction Types
        BEGIN
            SET @sql = @sql + 
                '    OR h.Sys_AW_Transaction_Types_ID = 1 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 2 ' +
                '    OR h.Sys_AW_Transaction_Types_ID = 13 '
        END
--     ELSE
--         BEGIN
--             SET @sql = @sql + ') '
--         END

    -- We ALWAYS need this bracket
    SET @sql = @sql + ') '


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND h.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND h.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    SET @sql = @sql + ' ORDER BY h.Transaction_Date ASC '


    EXEC (@sql)


SET NOCOUNT OFF













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
















-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Low_Profit_Sales
--Purpose       :DayEnd Sales lower than @GPThreshold by Filter by Product
--Functionality :
--Date          :2008/11/07
--Authors       :TB
--MODS:         :
--2004.4.7      :16/09/09 - Replaced 'Location' filter with 'Cashier' - TW
-------------------------------------------------------------------------------

CREATE                       PROCEDURE sp_RPT_AS_Low_Profit_Sales
    (
        @GPThreshold decimal(12,3),
        @AcctType tinyint,
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @GPThreshold = 5
-- SET @AcctType = 1
-- SET @Option = 'Department'
-- SET @DayEndFromDate = '2008/10/01 16:56:00'
-- SET @DayEndToDate = '2008/10/30 16:53:00'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    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 = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' o.UserName AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' c.Sys_AC_Account_Types_ID AS [AcctTypeID], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ProdID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '          ELSE ''INV'' '
    SET @sql = @sql + '      END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Original_Price) AS [DealerPrice], '
    SET @sql = @sql + ' CASE WHEN (d.Original_Price * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN ABS(CONVERT(money, (((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / (d.Original_Price * d.Quantity)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Disc%], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [UnitSelling], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost) AS [UnitCost], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost) AS [StdUnitCost], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * p.Standard_Cost)) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, p.Standard_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = '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 = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.User_ID = o.AW_Users_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4) AND '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END <= ' + CONVERT(varchar(30), @GPThreshold) + ' '


    IF @AcctType = 2
        BEGIN
            SET @sql = @sql + '    AND c.Sys_AC_Account_Types_ID = 3 '
        END

    ELSE
    IF @AcctType = 3
        BEGIN
            SET @sql = @sql + '    AND c.Sys_AC_Account_Types_ID <> 3 '
        END



    SET @sql = @sql +
        ' ORDER BY [Filter], [Product], [DocNo], [TranDate] '

--PRINT @sql

EXEC (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Open_Jobcard_Detail
--Purpose       :Open Jobcard Transaction Detail extracted from AS_Transaction_Details
--Functionality :
--Date          :2006/01/18
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AS_Open_Jobcard_Detail
    (
        @TranID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' d.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Quantity), 0) AS [Qty], '
--    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price * d.Quantity), 0) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Discount_Amount), 0) AS [Discount], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Extended_Amount - d.Tax_Amount), 0) AS [NetSales], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Tax_Amount), 0) AS [Tax], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Extended_Amount), 0) AS [Total], '

    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Cost * d.Quantity), 0) AS [Cost], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), 0) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' ISNULL(CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity), 0) AS [Price Adj], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Discount_Amount - d.Original_Discount), 0) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '

    SET @sql = @sql + ' WHERE d.AS_Transactions_ID = ' + CONVERT(varchar(10), @TranID)


--PRINT @sql

EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Open_Jobcards
--Purpose       :Day End extract of OPEN JOBCARDS etc.
--Functionality :
--Date          :2006/01/18
--Authors       :TB
--MODS:         :
--2004.3.5      :28/04/07 - Modified SORT ORDER from [TranNo] to [TranDate]
--2004.4.5      :10/06/09 - Added @chkTranType4 to fetch Sales Orders
-------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AS_Open_Jobcards
    (
        @ttCount tinyint,
        @chkTranType1 tinyint,
        @chkTranType2 tinyint,
        @chkTranType3 tinyint,
        @chkTranType4 tinyint,
        @chkDayEnd tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @filter varchar(4000),
            @cnt tinyint


    SET @sql = ' SELECT '

    SET @sql = @sql + ' h.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' h.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '

    SET @sql = @sql + ' ISNULL(h.Lup_AS_Cashiers_ID, 1) AS [CashierID], '
    SET @sql = @sql + ' ISNULL(h.Lup_AS_Tills_ID, 1) AS [TillID], '
    SET @sql = @sql + ' ISNULL(h.Lup_AS_Reps_ID, 1) AS [RepID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustomerID], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [CustRef], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Comment], '
    SET @sql = @sql + ' tt.[Description] + ''s''' + ' AS [TranType], '

    SET @sql = @sql + ' ISNULL(h.Total_Cost, 0) AS [HCost], '
--    SET @sql = @sql + ' ISNULL(h.Amount, 0) AS [HAmount], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount - h.Total_Tax_Amount, 0) AS [HAmount], '
    SET @sql = @sql + ' ISNULL(h.Total_Tax_Amount, 0) AS [HTax], '
    SET @sql = @sql + ' ISNULL(h.Total_Discount_Amount, 0) AS [HDiscount], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) AS [HTotal], ' 
    SET @sql = @sql + ' ISNULL(h.Payment_Amount, 0) AS [HPayment], '

    SET @sql = @sql + ' ISNULL(u.UserName, '''') AS [Cashier], '
--    SET @sql = @sql + ' csh.[Description] AS [Cashier], '
    SET @sql = @sql + ' ISNULL(til.[Description], '''') AS [Till], '
    SET @sql = @sql + ' ISNULL(rep.[Description], '''') AS [Rep], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [Active] '

    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      INNER JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      INNER JOIN Lup_AS_Tills til '
    SET @sql = @sql + '          ON h.Lup_AS_Tills_ID = til.Lup_AS_Tills_ID '
    SET @sql = @sql + '      INNER JOIN AW_Users u '
    SET @sql = @sql + '          ON h.Lup_AS_Cashiers_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '

    IF @chkDayEnd = 1    --Fetch Previous Day-End
        SET @sql = @sql +
            ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
            '       h.Slu_AW_Active_ID = 1 AND ' +
            '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
            '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') '
    ELSE                 --Fetch Current (Not yet Day-Ended)    
        SET @sql = @sql +
            ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
            '       h.Slu_AW_Active_ID = 1 AND ' +
            '       h.Day_End IS NULL '

    SET @filter = ' '

    IF @ttCount > 0
        BEGIN
            SET @filter = ' AND ( '
            SET @cnt = 0

            IF @chkTranType1 = 1
                BEGIN
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 1 '    --Quote
                    SET @cnt = @cnt + 1
                END
        
            IF @chkTranType2 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 2 '    --Job
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType3 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 13 '    --Pro Forma
                    SET @cnt = @cnt + 1
                END

            IF @chkTranType4 = 1
                BEGIN
                    IF @cnt > 0
                        BEGIN
                            SET @filter = @filter + ' OR '
                        END
                    SET @filter = @filter + '    h.Sys_AW_Transaction_Types_ID = 16 '    --Sales Orders
                    SET @cnt = @cnt + 1
                END

            IF @ttCount > 0
                SET @filter = @filter + ' ) '

        END

    SET @sql = @sql + @filter

    SET @sql = @sql + ' ORDER BY [CompanyID], [TranTypeID], [TranDate] '


--PRINT @sql

EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Rep_Sales_Filter
--Purpose       :Simplified Customer Sales from/to DayEnd date
--Functionality :
--Date          :2010/07/02
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                        PROCEDURE sp_RPT_AS_Rep_Sales_Filter
    (
        @FilterP tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @ChkAllCustomers int,
        @Level tinyint,
        @RepID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    IF @FilterP = 0
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 1
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 2
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 3
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [PHeaderID], ' +
            ' o.[Supplier_Name] AS [PFilter], '
    ELSE
    IF @FilterP = 4
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 5
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '
    ELSE
    IF @FilterP = 6
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [PHeaderID], ' +
            ' o.[Description] AS [PFilter], '


    SET @sql = @sql + ' r.Description AS [Rep], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '      THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '      THEN ''C/N'' '
    SET @sql = @sql + '      ELSE ''INV'' '
    SET @sql = @sql + ' END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + ' END AS [Act GP%], '
    SET @sql = @sql + ' u.UserName AS [User] '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + ' INNER JOIN AS_Transactions h '
    SET @sql = @sql + ' ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + ' INNER JOIN AP_Products p '
    SET @sql = @sql + ' ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + ' ON r.Lup_AS_Reps_ID = c.Lup_AS_Reps_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + ' ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + ' ON h.User_ID = u.AW_Users_ID '


    IF @FilterP = 0
        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 @FilterP = 1
        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 @FilterP = 2
        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 @FilterP = 3
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            ' ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @FilterP = 4
        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 @FilterP = 5
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            ' ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @FilterP = 6
        SET @sql = @sql +
            ' LEFT JOIN Lup_AC_Sales_Areas o ' +
            ' ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '


    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' '
    SET @sql = @sql + '  AND  h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '   OR  h.Sys_AW_Transaction_Types_ID = 4) '


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND r.Lup_AS_Reps_ID = ' + CONVERT(varchar(10), @RepID) + ' '
        END


    IF @Level = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Rep] '
        END
    ELSE
    IF @Level = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Rep], [Customer], [PFilter] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Rep], [Customer], [PFilter], [Product], [DocNo], [TranDate] '
        END

--PRINT @sql

EXEC (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

















-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Analysis
--Purpose       :Rolling 12 months Sales Analysis
--Funtionality  :    NB NB @sql string size near its limit of 8000 characters
--Date          :2004/12/22
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AS_Sales_Analysis
    (
        @Filter varchar(30),
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @InterCompany tinyint,
        @Target decimal(9,3),
        @Projected decimal(9,3),
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
    )

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000),
            @ElapsedDays tinyint,
            @YearStartDate datetime,
            @TargetPerc float
            



    SET @ElapsedDays = ISNULL(DAY(@ReportDate), 1)
    SET @YearStartDate = DATEADD(yy, -1, @EndDate)
    SET @TargetPerc = @Target / 100


    SET @sql = ' SELECT '
    
    SET @sql = @sql + ' MAX(d.AW_User_Companies_ID) AS [CompanyID], '
    
    IF @Filter = 'Type'
    SET @sql = @sql +
                ' MAX(o.Lup_AP_Product_Types_ID) AS [HeaderID], ' +
                ' MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
    SET @sql = @sql +
                ' MAX(o.Lup_AP_Product_Groups_ID) AS [HeaderID], ' +
                ' MAX(o.[Description]) AS [Filter], '
    ELSE
    IF @Filter = 'Department'
    SET @sql = @sql +
                ' MAX(o.Lup_AP_Product_Departments_ID) AS [HeaderID], ' +
                ' MAX(o.[Description]) AS [Filter], '
    
    
    SET @sql = @sql + ' d.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' MAX(ISNULL(p.[Description], '''')) AS [Description], '
    SET @sql = @sql + ' MAX(ISNULL(p.Product_Code, '''')) AS [Code], '
    
    
    SET @sql = @sql + ' SUM(d.Quantity) AS [Qty], '
    SET @sql = @sql + ' ROUND(SUM(d.Quantity) / ' + CONVERT(varchar(10), @ElapsedDays) + ', 2) AS [AvgQty], '
    SET @sql = @sql + ' ROUND((SUM(d.Quantity) / ' + CONVERT(varchar(10), @ElapsedDays) + ') * ' + CONVERT(varchar(10), @Projected) + ', 2) AS [ProjQty], '
    
    
    SET @sql = @sql + ' SUM(d.Extended_Amount - d.Tax_Amount) AS [Amount], '
    SET @sql = @sql + ' ROUND(SUM(d.Extended_Amount - d.Tax_Amount) / ' + CONVERT(varchar(10), @ElapsedDays) + ', 2) AS [AvgAmt], '
    SET @sql = @sql + ' ROUND((SUM(d.Extended_Amount - d.Tax_Amount) / ' + CONVERT(varchar(10), @ElapsedDays) + ') * ' + CONVERT(varchar(10), @Projected) + ', 2) AS [ProjAmt], '
    
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(x.Quantity / 12) + SUM(x.Quantity / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
    SET @sql = @sql + ' FROM AS_Transaction_Details x '
    SET @sql = @sql + ' INNER JOIN AS_Transactions y '
    SET @sql = @sql + ' ON y.AS_Transactions_ID = x.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
    SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
    SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   y.Sys_AW_Transaction_Types_ID = 4)'
    SET @sql = @sql + ' ), 0) AS [TargetQty], '
    
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM((x.Extended_Amount - x.Tax_Amount) / 12) + SUM((x.Extended_Amount - x.Tax_Amount) / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
    SET @sql = @sql + ' FROM AS_Transaction_Details x '
    SET @sql = @sql + ' INNER JOIN AS_Transactions y '
    SET @sql = @sql + ' ON y.AS_Transactions_ID = x.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
    SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
    SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   y.Sys_AW_Transaction_Types_ID = 4)'
    SET @sql = @sql + ' ), 0) AS [TargetAmt], '
    
    
    SET @sql = @sql + ' SUM(d.Extended_Amount) AS [Total], '
    SET @sql = @sql + ' SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0 '
    SET @sql = @sql + '  THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100 '
    SET @sql = @sql + '  ELSE 0.00 '
    SET @sql = @sql + '  END AS [GP%], '
    
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Jan + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jan], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Feb + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Feb], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Mar + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Mar], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Apr + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Apr], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @May + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [May], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Jun + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jun], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Jul + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jul], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Aug + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Aug], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Sep + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Sep], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Oct + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Oct], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Nov + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Nov], '
    
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + ' SELECT SUM(e.Quantity) '
    SET @sql = @sql + ' FROM AS_Transaction_Details e '
    SET @sql = @sql + ' INNER JOIN AS_Transactions f '
    SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE e.AP_Products_ID = d.AP_Products_ID AND '
    SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Dec + ''' AND '
    SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Dec] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + ' INNER JOIN AS_Transactions h '
    SET @sql = @sql + ' ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + ' INNER JOIN AP_Products p '
    SET @sql = @sql + ' ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON c.AC_Customers_ID = h.AC_Customers_ID '
    
    
    IF @Filter = 'Type'
    SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            ' ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
    SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            ' ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
    SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            ' ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '


    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + ' AND (h.Transaction_Date >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @sql = @sql + ' AND  h.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
    SET @sql = @sql + ' AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '      h.Sys_AW_Transaction_Types_ID = 4)'


    IF @ActiveOnly = 1     --Only Active Products
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_Active_ID = 1 '
        END
    
    
    IF @NonStock = 1       --Exclude Non-Stock Items
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    IF @InterCompany = 1      --Exclude Inter-Company Sales
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '
        END

    
    SET @sql = @sql + ' GROUP BY d.AP_Products_ID '
    
    
    SET @sql = @sql + ' ORDER BY [Filter], [Description] '
    
    --PRINT @sql
    
    EXEC (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Analysis_Month
--Purpose       :CURRENT MONTH Sales Analysis with Rolling 12 months UNIT SALES
--              :Shows SALES DATA for products sold in the CURRENT MONTH ONLY
--              :    caused by @StartDate and @EndDate REQUIRED in WHERE clause
--Funtionality  :NB NB @sql string size near its limit of 8000 (7531) characters
--Date          :2004/12/22
--Authors       :TB
--MODS:         :
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Analysis_Month]
    (
        @Filter varchar(30),
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @InterCompany tinyint,
        @Target decimal(9,3),
        @Projected decimal(9,3),
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ElapsedDays tinyint,
            @YearStartDate datetime,
            @TargetPerc float

    SET @ElapsedDays = ISNULL(DAY(@ReportDate), 1)
    SET @YearStartDate = DATEADD(yy, -1, @EndDate)
    SET @TargetPerc = @Target / 100

    SET @sql = 'SELECT '
    
    SET @sql = @sql + 'MAX(d.AW_User_Companies_ID)AS[CompanyID],'
    
    IF @Filter = 'Type'
    SET @sql = @sql +
                'MAX(o.Lup_AP_Product_Types_ID)AS[HeaderID],' +
                'MAX(o.[Description])AS[Filter],'
    ELSE
    IF @Filter = 'Groups'
    SET @sql = @sql +
                'MAX(o.Lup_AP_Product_Groups_ID)AS[HeaderID],' +
                'MAX(o.[Description])AS[Filter],'
    ELSE
    IF @Filter = 'Department'
    SET @sql = @sql +
                'MAX(o.Lup_AP_Product_Departments_ID)AS[HeaderID],' +
                'MAX(o.[Description])AS[Filter],'
    
    SET @sql = @sql + 'd.AP_Products_ID AS [ProductID],'
    SET @sql = @sql + 'MAX(ISNULL(p.[Description],''''))AS[Description],'
    SET @sql = @sql + 'MAX(ISNULL(p.Product_Code,''''))AS[Code],'
    
    SET @sql = @sql + 'SUM(d.Quantity)AS[Qty],'
    SET @sql = @sql + 'ROUND(SUM(d.Quantity)/' + CONVERT(varchar(10), @ElapsedDays) + ',2)AS[AvgQty],'
    SET @sql = @sql + 'ROUND((SUM(d.Quantity)/' + CONVERT(varchar(10), @ElapsedDays) + ')* ' + CONVERT(varchar(10), @Projected) + ',2)AS[ProjQty],'
    
    SET @sql = @sql + 'SUM(d.Extended_Amount-d.Tax_Amount)AS[Amount],'
    SET @sql = @sql + 'ROUND(SUM(d.Extended_Amount-d.Tax_Amount)/' + CONVERT(varchar(10), @ElapsedDays) + ',2)AS[AvgAmt],'
    SET @sql = @sql + 'ROUND((SUM(d.Extended_Amount-d.Tax_Amount)/' + CONVERT(varchar(10), @ElapsedDays) + ')* ' + CONVERT(varchar(10), @Projected) + ',2)AS[ProjAmt],'
    
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(x.Quantity/12)+SUM(x.Quantity/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=y.AC_Customers_ID	'							
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4)'
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '		
		SET @sql = @sql + '),0)AS[TargetQty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(x.Quantity/12)+SUM(x.Quantity/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4)'
		SET @sql = @sql + '),0)AS[TargetQty],'
	END
	    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(( '
		SET @sql = @sql + 'SELECT SUM((x.Extended_Amount-x.Tax_Amount)/12)+SUM((x.Extended_Amount-x.Tax_Amount)/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=y.AC_Customers_ID	'									
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3'				
		SET @sql = @sql + '),0)AS[TargetAmt],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(( '
		SET @sql = @sql + 'SELECT SUM((x.Extended_Amount-x.Tax_Amount)/12)+SUM((x.Extended_Amount-x.Tax_Amount)/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4)'
		SET @sql = @sql + '),0)AS[TargetAmt],'
	END    
    
    SET @sql = @sql + 'SUM(d.Extended_Amount) AS [Total], '
    SET @sql = @sql + 'SUM((d.Extended_Amount-d.Tax_Amount)-(d.Quantity*d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + 'CASE WHEN SUM(d.Extended_Amount-d.Tax_Amount)<>0 '
    SET @sql = @sql + 'THEN SUM((d.Extended_Amount-d.Tax_Amount)-(d.Quantity*d.Unit_Cost))/SUM(d.Extended_Amount-d.Tax_Amount)*100 '
    SET @sql = @sql + 'ELSE 0.00 '
    SET @sql = @sql + 'END AS [GPPerc],'
    
  	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jan + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jan_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jan + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jan_Qty],'
	END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Feb + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Feb_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Feb + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Feb_Qty], '
	END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Mar + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Mar_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Mar + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Mar_Qty],'
	END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Apr + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Apr_Qty], '
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Apr + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Apr_Qty],'
    END

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @May + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '				
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[May_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @May + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[May_Qty],'
    END
  
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jun + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jun_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jun + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jun_Qty],'
    END    
    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jul + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jul_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jul + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jul_Qty],'    
    END
    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Aug + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Aug_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Aug + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Aug_Qty],'
	END	
	
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Sep + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Sep_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Sep + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Sep_Qty],'
    END    
  
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)= ''' + @Oct + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '		
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Oct_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Oct + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Oct_Qty],'
    END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Nov + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Nov_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)= ''' + @Nov + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Nov_Qty],'
	END
	    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Dec + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '		
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Dec_Qty] '
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)= ''' + @Dec + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
		SET @sql = @sql + '),0)AS[Dec_Qty] '
	END	
    
    SET @sql = @sql + 'FROM vw_ASTD d '
    SET @sql = @sql + 'INNER JOIN vw_AST h '
    SET @sql = @sql + 'ON h.AS_Transactions_ID=d.AS_Transactions_ID '
    SET @sql = @sql + 'INNER JOIN AP_Products p '
    SET @sql = @sql + 'ON d.AP_Products_ID=p.AP_Products_ID '
    SET @sql = @sql + 'INNER JOIN AC_Customers c '
    SET @sql = @sql + 'ON c.AC_Customers_ID=h.AC_Customers_ID '
    
    IF @Filter = 'Type'
    SET @sql = @sql +
            'LEFT JOIN Lup_AP_Product_Types o ' +
            'ON p.Lup_AP_Product_Types_ID=o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
    SET @sql = @sql +
            'LEFT JOIN Lup_AP_Product_Groups o ' +
            'ON p.Lup_AP_Product_Groups_ID=o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
    SET @sql = @sql +
            'LEFT JOIN Lup_AP_Product_Departments o ' +
            'ON p.Lup_AP_Product_Departments_ID=o.Lup_AP_Product_Departments_ID '

    SET @sql = @sql + 'WHERE d.AW_User_Companies_ID=' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + 'AND (h.Transaction_Date>=''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @sql = @sql + 'AND  h.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
    SET @sql = @sql + 'AND (h.Sys_AW_Transaction_Types_ID=3 OR '
    SET @sql = @sql + 'h.Sys_AW_Transaction_Types_ID=4) '

    IF @ActiveOnly = 1     --Only Active Products
        BEGIN
            SET @sql = @sql + 'AND p.Slu_AW_Active_ID=1 '
        END
    
    IF @NonStock = 1       --Exclude Non-Stock Items
        BEGIN
            SET @sql = @sql + 'AND p.Slu_AW_YesNo_Non_Stock_Item=0 '
        END

    IF @InterCompany = 1      --Exclude Inter-Company Sales
        BEGIN
            SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
        END
    
    SET @sql = @sql + 'GROUP BY d.AP_Products_ID '
    
    SET @sql = @sql + 'ORDER BY [Filter],[Description] '
    
    --PRINT @sql
    
    EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Analysis_Year
--Purpose       :PRECEDING 12 MONTHS Sales Analysis with Rolling 12 months UNIT SALES
--              :Shows SALES DATA for products sold IN THE PRECEDING 12 MONTHS
--              :
--Funtionality  :
--Date          :2004/12/26
--Authors       :TB
--MODS:         :
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Analysis_Year]
    (
        @Filter varchar(50),
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @InterCompany tinyint,
        @Target decimal(9,3),
        @Projected decimal(9,3),
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ElapsedDays tinyint,
            @YearStartDate datetime,
            @TargetPerc float,
            @Jan_Qty decimal(9,3),
            @Feb_Qty decimal(9,3),
            @Mar_Qty decimal(9,3),
            @Apr_Qty decimal(9,3),
            @May_Qty decimal(9,3),
            @Jun_Qty decimal(9,3),
            @Jul_Qty decimal(9,3),
            @Aug_Qty decimal(9,3),
            @Sep_Qty decimal(9,3),
            @Oct_Qty decimal(9,3),
            @Nov_Qty decimal(9,3),
            @Dec_Qty decimal(9,3)


    SET @ElapsedDays = ISNULL(DAY(@ReportDate), 1)
    SET @YearStartDate = DATEADD(yy, -1, @EndDate)
    SET @TargetPerc = @Target / 100



--------------------------------------------------
--> DROP the WORK table AS_RPT_Sales_Analysis_Temp
--------------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AS_RPT_Sales_Analysis_Temp]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AS_RPT_Sales_Analysis_Temp]


--------------------------------------------------
--> SELECT DISTINCT rolling 12 months products with sales 
--------------------------------------------------
    DECLARE @Sales_12_Months table
                (
                    [CompanyID] int,
                    [HeaderID] int,
                    [Filter] varchar(100),
                    [ProductID] int,
                    [Description] varchar(100),
                    [Code] varchar(20),
                    [Qty] decimal(9,3),
                    [AvgQty] decimal(9,3),
                    [TargetQty] decimal(9,3),
                    [ProjQty] decimal(9,3),
                    [Amount] money,
                    [AvgAmt] money,
                    [TargetAmt] money,
                    [ProjAmt] money,
                    [Total] money,
                    [GP] money,
                    [GPPerc] decimal(9,3),
                    [Jan_Qty] decimal(9,3),
                    [Feb_Qty] decimal(9,3),
                    [Mar_Qty] decimal(9,3),
                    [Apr_Qty] decimal(9,3),
                    [May_Qty] decimal(9,3),
                    [Jun_Qty] decimal(9,3),
                    [Jul_Qty] decimal(9,3),
                    [Aug_Qty] decimal(9,3),
                    [Sep_Qty] decimal(9,3),
                    [Oct_Qty] decimal(9,3),
                    [Nov_Qty] decimal(9,3),
                    [Dec_Qty] decimal(9,3)
                )

    IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		IF @ActiveOnly = 1
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					INNER JOIN AC_Customers c
						ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					c.Sys_AC_Account_Types_ID <> 3 AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_Active_ID = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
					(
						CompanyID,
						ProductID
					)
					SELECT DISTINCT
						d.AW_User_Companies_ID,
						d.AP_Products_ID
					FROM AS_Transaction_Details d
						INNER JOIN AS_Transactions h
							ON d.AS_Transactions_ID = h.AS_Transactions_ID
						INNER JOIN AC_Customers c
							ON c.AC_Customers_ID = h.AC_Customers_ID
						INNER JOIN AP_Products p
							ON d.AP_Products_ID = p.AP_Products_ID
					WHERE d.AW_User_Companies_ID = @CompanyID AND
						c.Sys_AC_Account_Types_ID <> 3 AND
						d.Slu_AW_Active_ID = 1 AND
						(h.Sys_AW_Transaction_Types_ID = 3 OR 
						 h.Sys_AW_Transaction_Types_ID = 4) AND
						dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
						p.Slu_AW_Active_ID = 1
			END
		END --@ActiveOnly = 1
		ELSE
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					INNER JOIN AC_Customers c
						ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					c.Sys_AC_Account_Types_ID <> 3 AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					INNER JOIN AC_Customers c
						ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					c.Sys_AC_Account_Types_ID <> 3 AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1
			END
		END
    END      --Exclude Inter-Company Sales
    ELSE    
	BEGIN
		IF @ActiveOnly = 1
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					--INNER JOIN AC_Customers c
					--	ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_Active_ID = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
					(
						CompanyID,
						ProductID
					)
					SELECT DISTINCT
						d.AW_User_Companies_ID,
						d.AP_Products_ID
					FROM AS_Transaction_Details d
						INNER JOIN AS_Transactions h
							ON d.AS_Transactions_ID = h.AS_Transactions_ID
						--INNER JOIN AC_Customers c
						--	ON c.AC_Customers_ID = h.AC_Customers_ID
						INNER JOIN AP_Products p
							ON d.AP_Products_ID = p.AP_Products_ID
					WHERE d.AW_User_Companies_ID = @CompanyID AND
						d.Slu_AW_Active_ID = 1 AND
						(h.Sys_AW_Transaction_Types_ID = 3 OR 
						 h.Sys_AW_Transaction_Types_ID = 4) AND
						dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
						p.Slu_AW_Active_ID = 1
			END
		END
		ELSE
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					--INNER JOIN AC_Customers c
					--	ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					--INNER JOIN AC_Customers c
					--	ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1
			END
		END
    END



--------------------------------------------------
--> ADD static data to @Sales_12_Months table
--------------------------------------------------
    SET @sql = ' UPDATE sp '
    
    IF @Filter = 'Type'
        BEGIN
			UPDATE sp
			SET HeaderID = o.Lup_AP_Product_Types_ID,
				Filter = o.[Description],
				[Description] = p.[Description],
				Code = p.Product_Code
			FROM @Sales_12_Months sp
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = sp.ProductID
				LEFT JOIN Lup_AP_Product_Types o
					ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID
        END
    ELSE
    IF @Filter = 'Groups'
        BEGIN
            UPDATE sp
            SET HeaderID = o.Lup_AP_Product_Groups_ID,
                Filter = o.[Description],
                [Description] = p.[Description],
                Code = p.Product_Code
            FROM @Sales_12_Months sp
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = sp.ProductID
                LEFT JOIN Lup_AP_Product_Groups o
                    ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID
        END
    ELSE
    IF @Filter = 'Department'
        BEGIN
            UPDATE sp
            SET HeaderID = o.Lup_AP_Product_Departments_ID,
                Filter = o.[Description],
                [Description] = p.[Description],
                Code = p.Product_Code
            FROM @Sales_12_Months sp
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = sp.ProductID
                LEFT JOIN Lup_AP_Product_Departments o
                    ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID
        END



--------------------------------------------------
--> ADD MONTHLY Sales Qty for each Sales Product
--------------------------------------------------
	--JAN
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Jan_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jan AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Jan_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jan AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--FEB	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Feb_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Feb AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Feb_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Feb AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Mar	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Mar_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Mar AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Mar_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Mar AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END

	--Apr
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Apr_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Apr AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Apr_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Apr AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--May
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET May_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @May AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET May_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @May AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Jun
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Jun_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jun AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Jun_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jun AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Jul
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Jul_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jul AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Jul_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jul AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Aug	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Aug_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Aug AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Aug_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Aug AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Sep	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Sep_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Sep AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Sep_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Sep AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Oct	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Oct_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Oct AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Oct_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Oct AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Nov	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Nov_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Nov AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Nov_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Nov AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Dec
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Dec_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Dec AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Dec_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Dec AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
--------------------------------------------------
--> INSERT everyting into NEW AS_RPT_Sales_Analysis_Temp
--------------------------------------------------
    SELECT *
    INTO AS_RPT_Sales_Analysis_Temp
    FROM @Sales_12_Months
    ORDER BY [Filter], [HeaderID], [Description]


--------------------------------------------------
--> INSERT the CURRENT MONTH sales data
--------------------------------------------------
    SET @sql = ' DECLARE @Current_Month table ( ' +
                                                ' [ProductID] int, ' +
                                                ' [Qty] decimal(9,3), ' +
                                                ' [AvgQty] decimal(9,3), ' +
                                                ' [ProjQty] decimal(9,3), ' +
                                                ' [Amount] money, ' +
                                                ' [AvgAmt] money, ' +
                                                ' [ProjAmt] money, ' +
                                                ' [TargetQty] decimal(9,3), ' +
                                                ' [TargetAmt] money, ' +
                                                ' [Total] money, ' +
                                                ' [GP] money, ' +
                                                ' [GPPerc] decimal(9,3) ) '


    SET @sql = @sql + ' INSERT INTO @Current_Month '

    SET @sql = @sql + ' SELECT '
    
    SET @sql = @sql + ' d.AP_Products_ID, '
    SET @sql = @sql + ' SUM(d.Quantity), '
    SET @sql = @sql + ' ROUND(SUM(d.Quantity) / ' + CONVERT(varchar(10), @ElapsedDays) + ', 2), '
    SET @sql = @sql + ' ROUND((SUM(d.Quantity) / ' + CONVERT(varchar(10), @ElapsedDays) + ') * ' + CONVERT(varchar(10), @Projected) + ', 2), '
    
    
    SET @sql = @sql + ' SUM(d.Extended_Amount - d.Tax_Amount), '
    SET @sql = @sql + ' ROUND(SUM(d.Extended_Amount - d.Tax_Amount) / ' + CONVERT(varchar(10), @ElapsedDays) + ', 2), '
    SET @sql = @sql + ' ROUND((SUM(d.Extended_Amount - d.Tax_Amount) / ' + CONVERT(varchar(10), @ElapsedDays) + ') * ' + CONVERT(varchar(10), @Projected) + ', 2), '

	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(x.Quantity / 12) + SUM(x.Quantity / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + '     INNER JOIN AC_Customers c '
		SET @sql = @sql + '         ON c.AC_Customers_ID = y.AC_Customers_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
		SET @sql = @sql + ' ), 0), '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(x.Quantity / 12) + SUM(x.Quantity / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4)'
		SET @sql = @sql + ' ), 0), '	
	END    
    
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM((x.Extended_Amount - x.Tax_Amount) / 12) + SUM((x.Extended_Amount - x.Tax_Amount) / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + '     INNER JOIN AC_Customers c '
		SET @sql = @sql + '         ON c.AC_Customers_ID = y.AC_Customers_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '		
		SET @sql = @sql + ' ), 0), '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM((x.Extended_Amount - x.Tax_Amount) / 12) + SUM((x.Extended_Amount - x.Tax_Amount) / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4)'
		SET @sql = @sql + ' ), 0), '
	END


    SET @sql = @sql + ' SUM(d.Extended_Amount), '
    SET @sql = @sql + ' SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), '
    SET @sql = @sql + ' CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100 '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END '

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON h.AS_Transactions_ID = d.AS_Transactions_ID '

	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + '     INNER JOIN AC_Customers c '
		SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '
	END

    SET @sql = @sql + ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '     AND (h.Transaction_Date >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @sql = @sql + '     AND  h.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
    SET @sql = @sql + '     AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '          h.Sys_AW_Transaction_Types_ID = 4)'

	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '				
	END

    SET @sql = @sql + ' GROUP BY d.AP_Products_ID '


    SET @sql = @sql + ' UPDATE b '
    SET @sql = @sql + ' SET b.Qty = a.Qty, '
    SET @sql = @sql + '     b.AvgQty = a.AvgQty, '
    SET @sql = @sql + '     b.ProjQty = a.ProjQty, '
    SET @sql = @sql + '     b.Amount = a.Amount, '
    SET @sql = @sql + '     b.AvgAmt = a.AvgAmt, '
    SET @sql = @sql + '     b.ProjAmt = a.ProjAmt, '
    SET @sql = @sql + '     b.TargetQty = a.TargetQty, '
    SET @sql = @sql + '     b.TargetAmt = a.TargetAmt, '
    SET @sql = @sql + '     b.Total = a.Total, '
    SET @sql = @sql + '     b.GP = a.GP, '
    SET @sql = @sql + '     b.GPPerc = a.GPPerc '
    SET @sql = @sql + ' FROM @Current_Month a '
    SET @sql = @sql + '     INNER JOIN AS_RPT_Sales_Analysis_Temp b '
    SET @sql = @sql + '         ON a.ProductID = b.ProductID '
    SET @sql = @sql + ' WHERE a.ProductID = b.ProductID '


    EXEC (@sql)


--------------------------------------------------
--> FETCH the REPORT data
--------------------------------------------------
    SET @sql = ' SELECT st.* '
    SET @sql = @sql + ' FROM AS_RPT_Sales_Analysis_Temp st '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON p.AP_Products_ID = st.ProductID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = st.ProductID '

    IF @ActiveOnly = 1     --Only Active Products
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_Active_ID = 1 '
        END
    
    
    IF @NonStock = 1       --Exclude Non-Stock Items
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END

    
    SET @sql = @sql + ' ORDER BY st.[Filter], st.[Description] '
    
    
    EXEC (@sql)


---------------------------------------------
    DROP TABLE AS_RPT_Sales_Analysis_Temp
---------------------------------------------

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Products
--Purpose       :Sales by product filtered by Customer, cashier or sales rep
--Functionality :
--Date          :2014-05-13
--Authors       :RL
--Release		:V6.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Products]
    (
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @Option varchar(20), --Customer, Customer Type, Customer Group, Cashier, Sales Rep, Sales Area
        
        @CustomerChkAll int,
        @CustomerID int,
        @CustomerGroupChkAll int,
        @CustomerGroupID int,
        @CustomerTypeChkAll int,
        @CustomerTypeID int,
        @CashierChkAll int,
        @CashierID int,
        @SalesRepChkAll int,
        @SalesRepID int,
        @SalesAreaChkAll int,
        @SalesAreaID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    IF @Option = 'Customer'
    BEGIN
        SET @sql = @sql + ' c.AC_Customers_ID AS [HeaderID], '
		SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
		SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
		SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [PFilter], '
	END
    ELSE
    IF @Option = 'Customer Group'
        SET @sql = @sql + ' cg.Lup_AC_Customer_Groups_ID AS [HeaderID], ' +
						  ' cg.[Description] AS [PFilter], '
    ELSE
    IF @Option = 'Customer Type'
        SET @sql = @sql + ' ct.Lup_AC_Customer_Types_ID AS [HeaderID], ' +
						  ' ct.[Description] AS [PFilter], '
    ELSE
    IF @Option = 'Cashier'
    BEGIN
        SET @sql = @sql + ' u.AW_Users_ID AS [HeaderID], '            
		SET @sql = @sql + ' ISNULL(u.FirstName, '''') + '' '' + '
		SET @sql = @sql + ' ISNULL(u.Surname, '''') AS [PFilter], '            
	END
    ELSE
    IF @Option = 'Sales Rep'
        SET @sql = @sql +
            ' sr.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' sr.[Description] AS [PFilter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' sa.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' sa.[Description] AS [PFilter], '
  
    SET @sql = @sql + ' p.Product_Code AS [ProductCode], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code '
    SET @sql = @sql + ' + '' - '' + '
    SET @sql = @sql + ' ISNULL(p.Description,'''') AS [ProductFilter], '   
    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '          ELSE ''INV'' '
    SET @sql = @sql + '      END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Original_Price) AS [DealerPrice], '
    SET @sql = @sql + ' CASE WHEN (d.Original_Price * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN ABS(CONVERT(money, (((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / (d.Original_Price * d.Quantity)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Disc%], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [UnitSelling], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost) AS [UnitCost], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost) AS [StdUnitCost], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * p.Standard_Cost)) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, p.Standard_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
--    SET @sql = @sql + '      LEFT JOIN AW_Users u '
--    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Customer_Groups cg ' +
            '        ON c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID '
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Customer_Types ct' +
            '        ON c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
        SET @sql = @sql +
            '    LEFT JOIN AW_Users u ' +
            '        ON h.User_ID = u.AW_Users_ID '
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps sr ' +
            '        ON h.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID '
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas sa ' +
            '        ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    IF @CustomerChkAll = 0
        SET @sql = @sql +' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    
    IF @CustomerGroupChkAll = 0
		SET @sql = @sql +' AND cg.Lup_AC_Customer_Groups_ID = ' + CONVERT(varchar(10), @CustomerGroupID) + ' '
    
    IF @CustomerTypeChkAll = 0
		SET @sql = @sql +' AND ct.Lup_AC_Customer_Types_ID = ' + CONVERT(varchar(10), @CustomerTypeID) + ' '
    
    IF @CashierChkAll = 0
		SET @sql = @sql +' AND u.User_ID = ' + CONVERT(varchar(10), @CashierID) + ' '
    
    IF @SalesRepChkAll = 0
		SET @sql = @sql +' AND sr.Lup_AS_Reps_ID = ' + CONVERT(varchar(10), @SalesRepID) + ' '
    
    IF @SalesAreaChkAll = 0
		SET @sql = @sql +' AND sa.Lup_AC_Sales_Areas_ID = ' + CONVERT(varchar(10), @SalesAreaID) + ' '

    SET @sql = @sql +
        ' ORDER BY [PFilter], [ProductCode], [Product] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Profit
--Purpose       :Simplified Sales from/to DayEnd date
--Functionality :
--Date          :2008/04/28
--Authors       :TB
--MODS:         :
--2004.4.0      :13/07/08 - Added [Product] field
--              :26/07/08 - Changed 'Groups' to 'Group' to match OptionBox.Caption
--2004.4.3      :29/01/09 - Added selecting ONE or ALL Customers using @ChkAllCustomers
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Profit]
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @ChkAllCustomers int,
        @CustomerID int,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @Option = 'Group'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2007/09/03 07:34:00'
-- SET @DayEndToDate = '2007/09/15 12:06:00'



    SET @sql = ' SELECT '

    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], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '          ELSE ''INV'' '
    SET @sql = @sql + '      END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Original_Price,0)) AS [DealerPrice], '
    SET @sql = @sql + ' CASE WHEN (ISNULL(d.Original_Price,0) * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN ABS(CONVERT(money, (((ISNULL(d.Original_Price,0) * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / (ISNULL(d.Original_Price,0) * d.Quantity)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Disc%], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [UnitSelling], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Unit_Cost,0)) AS [UnitCost], '
    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Unit_Cost,0) * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * ISNULL(d.Unit_Cost,0))) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, ISNULL(d.Unit_Cost,0))) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost) AS [StdUnitCost], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * p.Standard_Cost)) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, p.Standard_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = '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 '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'


    IF @ChkAllCustomers = 0    --Single Customer Account
        BEGIN
            SET @sql = @sql + ' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END


    SET @sql = @sql +
        ' ORDER BY [Filter], [Product], [DocNo], [TranDate] '

--PRINT @sql

EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Profit_Products
--Purpose       :Simplified Sales from/to DayEnd date by Product
--Functionality :
--Date          :2008/11/01
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE                    PROCEDURE sp_RPT_AS_Sales_Profit_Products
    (
        @AcctType tinyint,
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @Option = 'Group'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2007/09/03 07:34:00'
-- SET @DayEndToDate = '2007/09/15 12:06:00'



    SET @sql = ' SELECT '

    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], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' c.Sys_AC_Account_Types_ID AS [AcctTypeID], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ProdID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '          ELSE ''INV'' '
    SET @sql = @sql + '      END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Original_Price) AS [DealerPrice], '
    SET @sql = @sql + ' CASE WHEN (d.Original_Price * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN ABS(CONVERT(money, (((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / (d.Original_Price * d.Quantity)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Disc%], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [UnitSelling], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost) AS [UnitCost], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost) AS [StdUnitCost], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * p.Standard_Cost)) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, p.Standard_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = '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 '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'


    IF @AcctType = 2
        BEGIN
            SET @sql = @sql + '    AND c.Sys_AC_Account_Types_ID = 3 '
        END

    ELSE
    IF @AcctType = 3
        BEGIN
            SET @sql = @sql + '    AND c.Sys_AC_Account_Types_ID <> 3 '
        END



    SET @sql = @sql +
        ' ORDER BY [Filter], [Product], [DocNo], [TranDate] '

--PRINT @sql

EXEC (@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO










-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Promotions
--Purpose       :
--Date          :2009/01/10
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE               PROCEDURE sp_RPT_AS_Sales_Promotions
    (
        @Filter tinyint,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' p.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AP_Promotions_ID AS [PromoID], '
    SET @sql = @sql + ' b.AP_Products_ID AS [ProductID], '

    SET @sql = @sql + ' a.Description AS [Promotion], '
    SET @sql = @sql + ' a.Start_Date AS [Promo Start], '
    SET @sql = @sql + ' a.End_Date AS [Promo End], '

    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' b.Start_Date AS [Starts], '
    SET @sql = @sql + ' b.End_Date AS [Ends], '
    SET @sql = @sql + ' b.Slu_AW_Credit_Terms_ID AS [Terms From], '
    SET @sql = @sql + ' b.Selling_Price AS [Price], '
    SET @sql = @sql + ' b.Qty_Projected_Sales AS [Projected], '
    SET @sql = @sql + ' b.Qty_Cutoff AS [Cutoff Qty], '
    SET @sql = @sql + ' b.Qty_Sold AS [Sold], '
    SET @sql = @sql + ' b.Max_Per_Customer AS [Cust Max], '
    SET @sql = @sql + ' p.On_Hand as [On Hand] '

    SET @sql = @sql + ' FROM AP_Promotions a '
    SET @sql = @sql + '     INNER JOIN AP_Promotion_Products b '
    SET @sql = @sql + '         ON a.AP_Promotions_ID = b.AP_Promotions_ID '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON p.AP_Products_ID = b.AP_Products_ID '


    IF @Filter = 1
        BEGIN
            SET @sql = @sql + ' WHERE a.End_Date > getdate() '
        END
    ELSE
    IF @Filter = 2
        BEGIN
            SET @sql = @sql + ' WHERE a.End_Date <= getdate() '
        END


    SET @sql = @sql + ' ORDER BY a.Start_Date DESC '


--PRINT @sql

EXEC (@sql)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Transaction_Listing
--Purpose       :Sales Transaction Listing
--Date          :2010/08/07
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Transaction_Listing]
    (
        @CompanyID int,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
	    @Option tinyint,
	    @Filter tinyint,
        @Sort tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    IF @Filter = 0
        SET @sql = @sql + ' o.AW_Users_ID AS [HeaderID], ' +
                          ' o.[Surname] + ISNULL('', '' + o.FirstName, '''') AS [Filter], '
    ELSE
    IF @Filter = 1
        SET @sql = @sql + ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
                          ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 2
        SET @sql = @sql + ' ISNULL(o.Lup_AS_Reps_ID,0) AS [HeaderID], ' +
                          ' ISNULL(o.[Description],''<None>'') AS [Filter], '
    ELSE
    IF @Filter = 3
        SET @sql = @sql + ' ISNULL(o.Lup_AS_Reps_ID,0) AS [HeaderID], ' +
                          ' ISNULL(o.[Description],''<None>'') AS [Filter], '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' t.Amount AS [Amount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + u.UserName, ''''))) AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = t.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '

    IF @Filter = 0
        SET @sql = @sql + '    LEFT JOIN AW_Users o ' +
                          '        ON t.User_ID = o.AW_Users_ID '
    ELSE
    IF @Filter = 1
        SET @sql = @sql + '    LEFT JOIN Lup_AC_Sales_Areas o ' +
                          '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 2
        SET @sql = @sql + '    LEFT JOIN Lup_AS_Reps o ' +
                          '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '
    ELSE
    IF @Filter = 3
        SET @sql = @sql + '    LEFT JOIN Lup_AS_Reps o ' +
                          '        ON t.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND t.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' '
    SET @sql = @sql + '  AND t.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ' '


    IF @Option = 0
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 1 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 2 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 3 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 4 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 5 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 7 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 15 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 16 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 18 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 21 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 22 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 23) '
        END

    ELSE
    IF @Option = 1
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 1 '
        END
    ELSE
    IF @Option = 2
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 2 '
        END
    ELSE
    IF @Option = 3
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 3 '
        END
    ELSE
    IF @Option = 4
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 4 '
        END
    ELSE
    IF @Option = 5
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 7 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 21 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 22) '
        END
    ELSE
    IF @Option = 6
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 5 '
        END
    ELSE
    IF @Option = 7
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 15 '
        END
    ELSE
    IF @Option = 8
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 18 '
        END
    ELSE
    IF @Option = 9
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 16 '
        END
    ELSE
    IF @Option = 10
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 23 '
        END


    IF @Sort = 0        --Date Captured
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Captured] ASC '
        END
    ELSE
    IF @Sort = 1        --Transaction Date
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [TranDate] ASC '
        END
    ELSE
    IF @Sort = 2        --Transaction Number
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [TranNo] ASC '
        END
    ELSE
    IF @Sort = 3        --Customer
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Customer] ASC '
        END


    EXEC (@sql)

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


















------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Transaction_Listing_Details
--Purpose       :Sales Transactions Details
--Date          :2010/08/08
--Authors       :TB
--MODS          :
------------------------------------------------------------------------------

CREATE             PROCEDURE sp_RPT_AS_Sales_Transaction_Listing_Details
    (
    	@TranID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    SET @sql = @sql + '     d.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     d.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + '     p.[Description] AS [Product], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     d.Quantity AS [Qty], '
    SET @sql = @sql + '     d.Unit_Cost AS [UnitCost], '
    SET @sql = @sql + '     d.Unit_Price AS [UnitPrice], '
    SET @sql = @sql + '    (d.Extended_Amount - d.Tax_Amount) AS [Amount], '
    SET @sql = @sql + '     d.Tax_Amount AS [Tax], '
    SET @sql = @sql + '     d.Extended_Amount AS [Total] '

    SET @sql = @sql + '     FROM AS_Transaction_Details d '
    SET @sql = @sql + '         LEFT JOIN AP_Products p '
    SET @sql = @sql + '             ON d.AP_Products_ID = p.AP_Products_ID '

    SET @sql = @sql + '     WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           d.AS_Transactions_ID = ' + CONVERT(varchar(10), @TranID) + ' '



    EXEC (@sql)


SET NOCOUNT OFF












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








-------------------------------------------------------------------------------
--Description	:sp_RPT_AS_Transaction_Details
--Purpose       :Day End Sales
--Date			:2002/02/04
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE        PROCEDURE  sp_RPT_AS_Transaction_Details
	(
		@TransactionID int
	)

AS

SET NOCOUNT ON

    SELECT     
        ISNULL(p.[Description],'') AS [Product], 
        ISNULL(p.Product_Code,'') AS [Code], 
        ISNULL(td.Quantity,0) AS [Qty], 
        ISNULL(td.Unit_Cost,0) AS [Cost], 
        ISNULL(td.Unit_Price,0) AS [Price], 
        ISNULL(td.Original_Price,0) AS [Original Price], 
        ISNULL(td.Original_Discount,0) AS [Original Discount], 
        ISNULL(td.Discount_Amount,0) AS [Discount], 
        ISNULL(td.Tax_Amount,0) AS [Tax], 
        ISNULL(td.Extended_Amount,0) AS [Amount], 
        ISNULL(td.Commission_Amount,0) AS [Commission], 
        td.AP_Products_ID AS [ProductID], 
        td.AS_Transactions_ID AS [TransactionID], 
        td.AS_Transaction_Details_ID AS [ID]
    FROM AS_Transaction_Details td 
        LEFT OUTER JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
    WHERE td.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO












----------------------------------------------------------------------------
--Description	:sp_RPT_AS_Transaction_Headers
--Purpose       :Day End Sales
--Date			:2002/02/04
--Authors		:TB
--Version		:1.0.0
--MODS          :13/07/02 - Removed superfluous colums
--              :04/08/02 - Replaced columns: Till, Cashier (Users), Cashed_Up
--              :01/10/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :                and commented JOIN to Lup_AS_Cashiers
----------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AS_Transaction_Headers
	(
		@CompanyID int,
		@Date DateTime
	)

AS

SET NOCOUNT ON

	SELECT     
        ISNULL(t.Transaction_Number, '') AS [No], 
        ISNULL(t.Total_Cost, 0) AS [Cost], 
        ISNULL(t.Amount, 0) AS [Amount], 
        ISNULL(t.Total_Tax_Amount, 0) AS [Tax], 
        ISNULL(t.Total_Discount_Amount, 0) AS [Discount], 
        ISNULL(t.Total_Amount, 0) AS [Total], 
        ISNULL(t.Payment_Amount, 0) AS [Payment], 
        t.Transaction_Date, 
        tt.[Description] AS [TransactionType], 
        tills.[Description] AS [Till], 
--        u.UserName AS [Cashier],
        ISNULL(u.Surname, '') + ISNULL(', ' + u.FirstName, '') as [Cashier],
--         cashiers.[Description] AS [Cashier], 
--         reps.[Description] AS [Rep], 
        ISNULL(c.Surname, '') + ISNULL(', ' + c.Firstnames, '') AS [Customer],		
        t.Cashed_Up, 
        t.Day_End, 
--         t.Customer_Reference, 
--         t.Expiry_Date,
--         com.Comment, 
        t.AW_User_Companies_ID AS [CompanyID],
--         t.Lup_AS_Cashiers_ID AS [CashierID], 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
--         t.Lup_AS_Tills_ID AS [TillID], 
--         t.Lup_AS_Reps_ID AS [RepID], 
        c.AC_Customers_ID AS [CustomerID],
        t.AS_Transactions_ID AS [ID]

--UNFINISHED 22 SEP 02 (include ALL UNINVOICED Job Cards)
--        t.Slu_AW_Active_ID AS [Active]
---------------
	FROM AS_Transactions t 
        LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID 
        LEFT JOIN fn_AW_Comments(-7) com
            ON t.AW_Comments_ID = com.[ID]
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
        LEFT JOIN Lup_AS_Tills tills
            ON t.Lup_AS_Tills_ID = tills.Lup_AS_Tills_ID 
--         LEFT JOIN Lup_AS_Cashiers cashiers
--             ON t.Lup_AS_Cashiers_ID = cashiers.Lup_AS_Cashiers_ID
		LEFT JOIN AW_Users u
            ON t.Lup_AS_Cashiers_ID = u.AW_Users_ID
        LEFT JOIN Lup_AS_Reps reps
            ON t.Lup_AS_Reps_ID = reps.Lup_AS_Reps_ID
	WHERE t.AW_User_Companies_ID = @CompanyID AND
            DATEDIFF(n,Day_End , @Date) = 0

--UNFINISHED 22 SEP 02 (include ALL UNINVOICED Job Cards)
--       OR
--           (t.AW_User_Companies_ID = @CompanyID
--              AND  DATEDIFF(d, Day_End, @Date) >= 0
--              AND  t.Sys_AW_Transaction_Types_ID = 2
--              AND  t.Slu_AW_Active_ID <> 0)
-- 
--     ORDER BY t.Transaction_Date
---------------

SET NOCOUNT OFF
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









--*** NOT USED ***
-------------------------------------------------------------------------------
--Description	:sp_RPT_AS_Transaction_Headers_Cash_Up
--Purpose       :Day End Sales
--Date			:2002/02/04
--Authors		:TB
--Version		:1.0.0
--MODS          :01/10/02 - Replaced references to Lup_AS_Cashiers with AW_Users
--              :                and commented JOIN to Lup_AS_Cashiers
-------------------------------------------------------------------------------

CREATE    PROCEDURE sp_RPT_AS_Transaction_Headers_Cash_Up
	(
		@CompanyID int,
		@Date DateTime
	)

AS

SET NOCOUNT ON

	SELECT     
        ISNULL(t.Transaction_Number,'') AS [No], 
        ISNULL(t.Total_Cost,0) AS [Cost], 
        ISNULL(t.Amount,0) AS [Amount], 
        ISNULL(t.Total_Tax_Amount,0) AS [Tax], 
        ISNULL(t.Total_Discount_Amount,0) AS [Discount], 
        ISNULL(t.Total_Amount,0) AS [Total], 
        ISNULL(t.Payment_Amount,0) AS [Payment], 
        t.Transaction_Date, 
        tt.[Description] AS [TransactionType], 
        tills.[Description] AS [Till], 
--        cashiers.[Description] AS [Cashier],
        ISNULL(u.Surname, '') + ISNULL(', ' + u.FirstName, '') as [Cashier],
        reps.[Description] AS [Rep], 
        ISNULL(c.Surname, '') + ISNULL(', ' + c.Firstnames, '') AS [Customer],		
        t.Cashed_Up, 
        t.Day_End, 
        t.Customer_Reference, 
        t.Expiry_Date,
        com.Comment, 
        t.AW_User_Companies_ID AS [CompanyID],
        t.Lup_AS_Cashiers_ID AS [CashierID], 
        t.Sys_AW_Transaction_Types_ID AS [TransactionTypeID], 
        t.Lup_AS_Tills_ID AS [TillID], 
        t.Lup_AS_Reps_ID AS [RepID], 
        c.AC_Customers_ID AS [CustomerID],
        t.AS_Transactions_ID AS [ID]
	FROM AS_Transactions t 
        LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID 
        LEFT JOIN fn_AW_Comments(-7) com
            ON t.AW_Comments_ID = com.ID
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
        LEFT JOIN Lup_AS_Tills tills
            ON t.Lup_AS_Tills_ID = tills.Lup_AS_Tills_ID 
--         LEFT JOIN Lup_AS_Cashiers cashiers
--             ON t.Lup_AS_Cashiers_ID = cashiers.Lup_AS_Cashiers_ID 
		LEFT JOIN AW_Users u
            ON t.Lup_AS_Cashiers_ID = u.AW_Users_ID
        LEFT JOIN Lup_AS_Reps reps
            ON t.Lup_AS_Reps_ID = reps.Lup_AS_Reps_ID
	WHERE t.AW_User_Companies_ID = @CompanyID AND
            datediff(n,Cashed_Up, @Date) = 0


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO









-------------------------------------------------------------------------------
--Description	:sp_RPT_AS_Transaction_Payments
--Purpose       :Day End Sales
--Date			:2002/02/04
--Authors		:TB
--Version		:1.0.0
-------------------------------------------------------------------------------

CREATE        PROCEDURE sp_RPT_AS_Transaction_Payments
	(
		@TransactionID int
	)

AS

SET NOCOUNT ON

    SELECT     
        pm.[Description] AS [Method], 
        ci.[Description] AS [Institution], 
        tp.Payor_Name AS [Payor], 
        tp.Card_Expiry_Date AS [Expiry], 
        tp.Card_Number AS [No], 
        tp.Authorisation_Number AS [Auth], 
        tp.Amount AS [Amount],
        tp.AS_Transactions_ID AS [TransactionID],
        tp.AS_Transaction_Payments_ID AS [ID]
    FROM AS_Transaction_Payments tp 
        INNER JOIN Sys_AW_Payment_Methods pm
            ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID 
        INNER JOIN Slu_AS_Card_Institutions ci
            ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID
    WHERE tp.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description	:sp_RPT_AS_Transaction_Payments_Cash_Up
--Purpose       :Day End Sales for Cash Up 'Cash Up Analysis' Grid
--              :Grid.Band(2) in Cash Up Shape
--              :Selects AS_Transaction_Payments per Cashier
--Date			:2002/02/04
--Authors		:TB
--Version		:1.0.0
--MODS          :25/07/02 - Added t.Transaction_Number AS [No] and
--              :            renamed tp.Card_Number AS [Card No] (was [No])
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AS_Transaction_Payments_Cash_Up
	(
		@CompanyID int,
		@Date varchar(20),
		@CashierID int = 0
	)

AS

SET NOCOUNT ON

	IF  @CashierID <> 0    -- AND @TillID = 0 
		BEGIN
			SELECT     
				tp.Payor_Name AS [Payor], 
				tp.Amount AS [Amount],
                t.Transaction_Number AS [No],
				tp.AS_Transactions_ID AS [TransactionID],
				ci.[Description] AS [Institution], 
				tp.Card_Expiry_Date AS [Expiry], 
				tp.Card_Number AS [Card No],        --[No], 
				tp.Authorisation_Number AS [Auth], 
				t.Cashed_Up,
				tp.Sys_AW_Payment_Methods_ID as [MethodID],
				pm.[Description] AS [Method], 
				tp.AS_Transaction_Payments_ID AS [ID]
			FROM AS_Transaction_Payments tp 
				LEFT JOIN AS_Transactions t
                    ON tp.AS_Transactions_ID = t.AS_Transactions_ID
				INNER JOIN Sys_AW_Payment_Methods pm
                    ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID 
				INNER JOIN Slu_AS_Card_Institutions ci
                    ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID
			WHERE t.AW_User_Companies_ID = @CompanyID AND
                  DATEDIFF(mi, t.cashed_up, @Date) = 0 AND
			      t.Lup_AS_Cashiers_ID = @CashierID
		END
-- 	ELSE
-- 	IF @CashierID = 0 AND @TillID <> 0
-- 		BEGIN
-- 			SELECT     
-- 				tp.Payor_Name AS [Payor], 
-- 				tp.Amount AS [Amount],
--                 t.Transaction_Number AS [No],
-- 				tp.AS_Transactions_ID AS [TransactionID],
-- 				ci.[Description] AS [Institution], 
-- 				tp.Card_Expiry_Date AS [Expiry], 
-- 				tp.Card_Number AS [Card No],        --[No], 
-- 				tp.Authorisation_Number AS [Auth], 
-- 				t.Cashed_Up,
-- 				tp.Sys_AW_Payment_Methods_ID as [MethodID],
-- 				pm.[Description] AS [Method], 
-- 				tp.AS_Transaction_Payments_ID AS [ID]
-- 			FROM AS_Transaction_Payments tp 
-- 				LEFT JOIN AS_Transactions t
--                     ON tp.AS_Transactions_ID = t.AS_Transactions_ID
-- 				INNER JOIN Sys_AW_Payment_Methods pm
--                     ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID 
-- 				INNER JOIN Slu_AS_Card_Institutions ci
--                     ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID
-- 			WHERE t.AW_User_Companies_ID = @CompanyID AND
--                   DATEDIFF(n,t.cashed_up, @Date) = 0 AND
-- 			      t.Lup_AS_Tills_ID = @TillID
-- 		END
-- 	ELSE
-- 	IF @CashierID <> 0 AND @TillID <> 0 
-- 		BEGIN
-- 			SELECT     
-- 				tp.Payor_Name AS [Payor], 
-- 				tp.Amount AS [Amount],
--                 t.Transaction_Number AS [No],
-- 				tp.AS_Transactions_ID AS [TransactionID],
-- 				ci.[Description] AS [Institution], 
-- 				tp.Card_Expiry_Date AS [Expiry], 
-- 				tp.Card_Number AS [Card No],        --[No], 
-- 				tp.Authorisation_Number AS [Auth], 
-- 				t.Cashed_Up,
-- 				tp.Sys_AW_Payment_Methods_ID as [MethodID],
-- 				pm.[Description] AS [Method], 
-- 				tp.AS_Transaction_Payments_ID AS [ID]
-- 			FROM AS_Transaction_Payments tp 
-- 				LEFT JOIN AS_Transactions t
--                     ON tp.AS_Transactions_ID = t.AS_Transactions_ID
-- 				INNER JOIN Sys_AW_Payment_Methods pm
--                     ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID 
-- 				INNER JOIN Slu_AS_Card_Institutions ci
--                     ON tp.Slu_AS_Card_Institutions_ID = ci.Slu_AS_Card_Institutions_ID
-- 			WHERE t.AW_User_Companies_ID = @CompanyID AND
--                   DATEDIFF(n,t.cashed_up, @Date) = 0 AND
-- 					t.Lup_AS_Tills_ID = @TillID AND
-- 					t.Lup_AS_Cashiers_ID = @CashierID
-- 		END


SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO















-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Transactions_XREF
--Purpose       :POS XREF Transactions AUDIT report
--Functionality :
--Date          :2003/01/04
--Authors       :TB
--Version       :1.0.0
--MODS:         :01/07/04 - Added ORDER BY hi.Transaction_Number ASC
--              :01/07/04 - Replaced unused @TranTypeID input parameter with
--              :           Check/Unchecked status parameter @Checkstatus:
--              :           0 = Unchecked Jobcards, 1 = Checked Jobcards
--              :01/07/04 - Added [Checked] and [CheckedBy] field
--              :03/10/04 - Added [User] field
-------------------------------------------------------------------------------

CREATE                PROCEDURE sp_RPT_AS_Transactions_XREF
    (
        @Date datetime,        
        @CompanyID int,
        @Checkstatus int
    )

AS

SET NOCOUNT ON


-- SET @Date = '2002/11/01 00:00:01'
-- SET @CompanyID = 1
-- SET @TranTypeID = 2        -- 1 = Quotes, 2 = Jobcards
-- SEt @Checkstatus = 0       -- 0 = Unchecked Jobcards (No), 1 = Checked Jobcards (Yes)
 

    IF @Checkstatus = 0    --Unchecked Jobcards
        BEGIN

            SELECT
                x.AS_Transactions_Xref_ID AS [ID],
                hi.AS_Transactions_ID AS [hiID],
                ISNULL(ci.Surname, '') + ISNULL(', ' + ci.Firstnames, '') AS [Inv Customer],
                ISNULL(iu.Surname, '') + ISNULL(', ' + iu.Firstname, '') AS [Inv User],
                ISNULL(iu.UserName, '') AS [User],
                ISNULL(hi.Transaction_Date, '') AS [Inv Date],
                ISNULL(hi.Transaction_Number, '') AS [Inv Ref No],
                ISNULL(tti.[Description], '') AS [Inv Type],
                ISNULL(hi.Comment, '') AS [Inv Comment],
                ISNULL(hicom.Comment, '') AS [Inv Notes],
                ISNULL(ip.[Description], '') AS [Inv Product],
            --> Invoice
                ISNULL(di.Quantity, 0) AS [Inv Qty],
                ISNULL((di.Unit_Price - di.Original_Price) * di.Quantity, 0) AS [Inv PriceDisc],
                ISNULL(di.Discount_Amount, 0) AS [Inv SalesDisc],
                ISNULL(di.Extended_Amount - di.Tax_Amount, 0) AS [Inv NetSales],
                ISNULL((di.Quantity * di.Unit_Cost), 0) AS [Inv Cost],
                ISNULL((di.Extended_Amount - di.Tax_Amount) - (di.Quantity * di.Unit_Cost), 0) AS [Inv GP],
                CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(di.Original_Price, di.Quantity) <> 0
                     THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(di.Original_Price, di.Unit_Cost, di.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(di.Original_Price, di.Quantity)) * 100))
                     ELSE 0.00
                     END AS [Inv StdGP%],
                CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(di.Extended_Amount, di.Tax_Amount) <> 0
                     THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(di.Extended_Amount, di.Tax_Amount, di.Quantity, di.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(di.Extended_Amount, di.Tax_Amount)) * 100))
                     ELSE 0.00
                     END AS [Inv ActGP%],
                ISNULL(yn.[Description], '') AS [Checked],
                ISNULL(aud.Firstname, '') + ISNULL(' ' + aud.Surname, '') AS [CheckedBy]
            FROM AS_Transactions_Xref x
                INNER JOIN AS_Transactions hi
                    ON hi.AS_Transactions_ID = x.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tti
                    ON tti.Sys_AW_Transaction_Types_ID = hi.Sys_AW_Transaction_Types_ID
                INNER JOIN AS_Transaction_Details di
                    ON di.AS_Transactions_ID = hi.AS_Transactions_ID
                INNER JOIN AC_Customers ci
                    ON ci.AC_Customers_ID = hi.AC_Customers_ID
                INNER JOIN AP_Products ip
                    ON ip.AP_Products_ID = di.AP_Products_ID
                LEFT JOIN AW_Comments hicom
                    ON hicom.AW_Comments_ID = hi.AW_Comments_ID
                INNER JOIN AW_Users iu
                    ON iu.AW_Users_ID = hi.[User_ID]
                LEFT JOIN Slu_AW_YesNo yn
                    ON yn.Slu_AW_YesNo_ID = x.AW_YesNo_Checked_ID
                LEFT JOIN AW_Users aud
                    ON aud.AW_Users_ID = x.Checked_User_ID
            WHERE  hi.Transaction_Date >= @Date AND
                   hi.AW_User_Companies_ID = @CompanyID AND
                   x.AW_YesNo_Checked_ID = 0
            ORDER BY hi.Transaction_Number ASC

        END

    ELSE                   --Checked Jobcards
        BEGIN

            SELECT
                x.AS_Transactions_Xref_ID AS [ID],
                hi.AS_Transactions_ID AS [hiID],
                ISNULL(ci.Surname, '') + ISNULL(', ' + ci.Firstnames, '') AS [Inv Customer],
                ISNULL(iu.Surname, '') + ISNULL(', ' + iu.Firstname, '') AS [Inv User],
                ISNULL(iu.UserName, '') AS [User],
                ISNULL(hi.Transaction_Date, '') AS [Inv Date],
                ISNULL(hi.Transaction_Number, '') AS [Inv Ref No],
                ISNULL(tti.[Description], '') AS [Inv Type],
                ISNULL(hi.Comment, '') AS [Inv Comment],
                ISNULL(hicom.Comment, '') AS [Inv Notes],
                ISNULL(ip.[Description], '') AS [Inv Product],
            --> Invoice
                ISNULL(di.Quantity, 0) AS [Inv Qty],
                ISNULL((di.Unit_Price - di.Original_Price) * di.Quantity, 0) AS [Inv PriceDisc],
                ISNULL(di.Discount_Amount, 0) AS [Inv SalesDisc],
                ISNULL(di.Extended_Amount - di.Tax_Amount, 0) AS [Inv NetSales],
                ISNULL((di.Quantity * di.Unit_Cost), 0) AS [Inv Cost],
                ISNULL((di.Extended_Amount - di.Tax_Amount) - (di.Quantity * di.Unit_Cost), 0) AS [Inv GP],
                CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(di.Original_Price, di.Quantity) <> 0
                     THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(di.Original_Price, di.Unit_Cost, di.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(di.Original_Price, di.Quantity)) * 100))
                     ELSE 0.00
                     END AS [Inv StdGP%],
                CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(di.Extended_Amount, di.Tax_Amount) <> 0
                     THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(di.Extended_Amount, di.Tax_Amount, di.Quantity, di.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(di.Extended_Amount, di.Tax_Amount)) * 100))
                     ELSE 0.00
                     END AS [Inv ActGP%],
                ISNULL(yn.[Description], '') AS [Checked],
                ISNULL(aud.Firstname, '') + ISNULL(' ' + aud.Surname, '') AS [CheckedBy]
            FROM AS_Transactions_Xref x
                INNER JOIN AS_Transactions hi
                    ON hi.AS_Transactions_ID = x.AS_Transactions_ID
                INNER JOIN Sys_AW_Transaction_Types tti
                    ON tti.Sys_AW_Transaction_Types_ID = hi.Sys_AW_Transaction_Types_ID
                INNER JOIN AS_Transaction_Details di
                    ON di.AS_Transactions_ID = hi.AS_Transactions_ID
                INNER JOIN AC_Customers ci
                    ON ci.AC_Customers_ID = hi.AC_Customers_ID
                INNER JOIN AP_Products ip
                    ON ip.AP_Products_ID = di.AP_Products_ID
                LEFT JOIN AW_Comments hicom
                    ON hicom.AW_Comments_ID = hi.AW_Comments_ID
                INNER JOIN AW_Users iu
                    ON iu.AW_Users_ID = hi.[User_ID]
                LEFT JOIN Slu_AW_YesNo yn
                    ON yn.Slu_AW_YesNo_ID = x.AW_YesNo_Checked_ID
                LEFT JOIN AW_Users aud
                    ON aud.AW_Users_ID = x.Checked_User_ID
            WHERE  hi.Transaction_Date >= @Date AND
                   hi.AW_User_Companies_ID = @CompanyID AND
                   x.AW_YesNo_Checked_ID <> 0
            ORDER BY hi.Transaction_Number ASC

        END



SET NOCOUNT OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO













-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Transactions_Xref_Sources
--Purpose       :POS XREF Transactions Sources AUDIT report
--Functionality :
--Date          :2003/01/04
--Authors       :TB
--Version       :1.0.0
--MODS:         :03/10/04 - Added [User] field
-------------------------------------------------------------------------------

CREATE              PROCEDURE sp_RPT_AS_Transactions_Xref_Sources
    (
        @XrefID int
    )

AS

SET NOCOUNT ON


-- SET @Date = '2002/11/01 00:00:01'
-- SET @CompanyID = 1
-- SET @TranTypeID = 2        -- 1 = Quotes, 2 = Jobcards
 

    SELECT
        xs.AS_Transactions_Xref_ID AS [xID],
        xs.AS_Transactions_Xref_Sources_ID AS [xsID],
        hj.AS_Transactions_ID AS [hjID],
        ISNULL(cj.Surname, '') + ISNULL(', ' + cj.Firstnames, '') AS [Job Customer],
        ISNULL(ju.Surname, '') + ISNULL(', ' + ju.Firstname, '') AS [Job User],
        ISNULL(ju.UserName, '') AS [User],
        ISNULL(hj.Transaction_Date, '') AS [Job Date],
        ISNULL(hj.Transaction_Number, '') AS [Job Ref No],
        ISNULL(ttj.[Description], '') AS [Job Type],
        ISNULL(hj.Comment, '') AS [Job Comment],
        ISNULL(hjcom.Comment, '') AS [Job Notes],
        ISNULL(jp.[Description], '') AS [Job Product],
    --> Source (Jobcard)
        ISNULL(dj.Quantity, 0) AS [Job Qty],
        ISNULL(dj.Unit_Price, 0) AS [JobUnitPrice],
        ISNULL((dj.Unit_Price - dj.Original_Price) * dj.Quantity, 0) AS [JobPriceDisc],
        ISNULL(dj.Discount_Amount, 0) AS [JobSalesDisc],
        ISNULL(dj.Extended_Amount - dj.Tax_Amount, 0) AS [JobNetSales],
--         ISNULL((dj.Quantity * dj.Unit_Cost), 0) AS [Job Cost],
--         ISNULL((dj.Extended_Amount - dj.Tax_Amount) - (dj.Quantity * dj.Unit_Cost), 0) AS [Job GP],
        CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(dj.Original_Price, dj.Quantity) <> 0
             THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(dj.Original_Price, dj.Unit_Cost, dj.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(dj.Original_Price, dj.Quantity)) * 100))
             ELSE 0.00
             END AS [Job StdGP%],
        CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(dj.Extended_Amount, dj.Tax_Amount) <> 0
             THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(dj.Extended_Amount, dj.Tax_Amount, dj.Quantity, dj.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(dj.Extended_Amount, dj.Tax_Amount)) * 100))
             ELSE 0.00
             END AS [Job ActGP%]
    FROM AS_Transactions_Xref_Sources xs
        INNER JOIN AS_Transactions hj
            ON hj.AS_Transactions_ID = xs.AS_Transactions_ID
        INNER JOIN Sys_AW_Transaction_Types ttj
            ON ttj.Sys_AW_Transaction_Types_ID = hj.Sys_AW_Transaction_Types_ID
        INNER JOIN AS_Transaction_Details dj
            ON dj.AS_Transactions_ID = hj.AS_Transactions_ID
        INNER JOIN AC_Customers cj
            ON cj.AC_Customers_ID = hj.AC_Customers_ID
        INNER JOIN AP_Products jp
            ON jp.AP_Products_ID = dj.AP_Products_ID
        LEFT JOIN AW_Comments hjcom
            ON hjcom.AW_Comments_ID = hj.AW_Comments_ID
        INNER JOIN AW_Users ju
            ON ju.AW_Users_ID = hj.[User_ID]
    WHERE  xs.AS_Transactions_Xref_ID = @XrefID



SET NOCOUNT OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Uninvoiced_Jobcards
--Purpose       :Uninvoiced Jobcards from Starting DayEnd date to Ending DayEnd date
--Functionality :
--Date          :2003/01/11
--Authors       :TB
--MODS:         :
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
-------------------------------------------------------------------------------

CREATE            PROCEDURE sp_RPT_AS_Uninvoiced_Jobcards
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(5000)


-- SET @Option = 'Groups'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        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], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '       h.Sys_AW_Transaction_Types_ID = 2 AND ' +
        '       h.Slu_AW_Active_ID = 1'

    SET @sql = @sql +
        ' ORDER BY [Filter], [Customer], [TranDate] '

--PRINT @sql

EXEC (@sql)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_RPT_Customer_Delivery_Details
--Purpose       :Get Customer Delivery Details
--Parameters    :
--Date          :2014-10-30
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

 
CREATE PROCEDURE [dbo].[sp_RPT_Customer_Delivery_Details]
	@FromDate			DateTime,
	@ToDate				DateTime,
	@AC_Customer_ID		Int,
	@Sales_Rep_ID		Int,
	@Customer_Rep_ID	Int,
	@Cashier_ID			Int,
	@Invoice			Int,
	@Refunds			Int,
	@Quotes				Int,
	@Sales_Orders		Int,
	@ProFormas			Int,
	@CompanyID			Int
AS

SET NOCOUNT ON

	DECLARE @WhichName			Tinyint
		
	DECLARE @Tbl_T Table
		(
			AS_Transaction_Details_ID	Int,
			AS_Transactions_ID		Int,
			AC_CustomersID			Int,
			Transaction_Number		Varchar(20),
			Transaction_Date		Datetime,
			Quantity				Money,
			Unit_Cost				Money,
			Tax_Amount				Money,
			Extended_Amount			Money,
			AP_Products_ID			Int,
			P_Description			Varchar(50),
			Lup_AS_Sales_Reps_ID	Int,
			Sales_Rep				Varchar(50),
			Lup_AS_Cashiers_ID		Int,
			Cashier					Varchar(50),
			Lup_AS_Customer_Reps_ID	Int,
			Customer_Rep			Varchar(50),	
			Lup_AC_Sales_Areas_ID	Int,
			Customer_Sales_Area		Varchar(50),			
			
			C_Surname				Varchar(40),
			C_Initials				Varchar(10),
			C_Firstnames			Varchar(50),
			C_Title					Varchar(50),						
			C_ID_Number				Varchar(20),
			C_PostalAddress1		Varchar(40),			
			C_PostalAddress2		Varchar(40),
			C_PostalCode			Varchar(10),
			C_HomeTelNo				Varchar(20),
			C_WorkTelNo				Varchar(20),
			C_MobileTelNo			Varchar(20),
			C_Street_Address		Varchar(40),
			C_Suburb				Varchar(30),
			C_City					Varchar(30),
			C_Street_Post_Code		Varchar(10),
			C_Delivery_Address		Varchar(40),
			C_Delivery_Suburb		Varchar(40),
			C_Delivery_City			Varchar(30),
			C_Delivery_Post_Code	Varchar(10),

			T_Surname				Varchar(50),
			T_Inv_Address1			Varchar(40),
			T_Inv_Address2			Varchar(40),
			T_Inv_City				Varchar(40),
			T_Inv_Code				Varchar(10),
			T_Delivery_Address		Varchar(40),
			T_Delivery_Suburb		Varchar(40),
			T_Delivery_City			Varchar(30),
			T_PostalCode			Varchar(10)
		)		
                      	
	SELECT TOP 1 @WhichName = ISNULL(Control_Index, '0')
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
	Control_Name = 'optPOSPrintAddress' AND
	Control_Value = 'True'			  

	--Insert Sales Records
	INSERT INTO @Tbl_T
	(
		AS_Transaction_Details_ID, AS_Transactions_ID, AC_CustomersID, Transaction_Number, Transaction_Date, 		
		Quantity, Unit_Cost, Tax_Amount, Extended_Amount, 
		
		AP_Products_ID, P_Description,
		Lup_AS_Sales_Reps_ID, Sales_Rep, 
		Lup_AS_Cashiers_ID, Cashier, 
		Lup_AS_Customer_Reps_ID, Customer_Rep, 
		Lup_AC_Sales_Areas_ID, Customer_Sales_Area,	

		C_Surname, C_Initials, C_Firstnames,
		C_Title, C_ID_Number, C_PostalAddress1, 
		C_PostalAddress2, C_PostalCode, 
		C_HomeTelNo, C_WorkTelNo, C_MobileTelNo,	
		C_Street_Address, C_Suburb,	C_City,	C_Street_Post_Code,
		
		C_Delivery_Address,	C_Delivery_Suburb, C_Delivery_City,	C_Delivery_Post_Code,
		T_Surname, T_Inv_Address1, T_Inv_Address2,
		T_Inv_City, T_Inv_Code,
		T_Delivery_Address, T_Delivery_Suburb, 
		T_Delivery_City, T_PostalCode
	)
	SELECT
		DISTINCT td.AS_Transaction_Details_ID, tt.AS_Transactions_ID, tt.AC_Customers_ID, tt.Transaction_Number, tt.Transaction_Date,		
		ISNULL(td.Quantity,0), ISNULL(td.Unit_Cost,0), ISNULL(td.Tax_Amount,0), ISNULL(td.Extended_Amount,0),	
		td.AP_Products_ID, LTRIM(RTRIM(ISNULL(p.[Description],''))),
		tt.Lup_AS_Reps_ID, LTRIM(RTRIM(ISNULL(sr.[Description],''))),
		tt.Lup_AS_Cashiers_ID, LTRIM(RTRIM(ISNULL(u.FirstName,''))) + ' ' + LTRIM(RTRIM(ISNULL(u.Surname,''))), 
		c.Lup_AS_Reps_ID, LTRIM(RTRIM(ISNULL(cr.[Description],''))),
		c.Lup_AC_Sales_Areas_ID, LTRIM(RTRIM(ISNULL(sa.[Description],''))),
		
		LTRIM(RTRIM(ISNULL(c.Surname,''))), LTRIM(RTRIM(ISNULL(c.Initials,''))), LTRIM(RTRIM(ISNULL(c.Firstnames,''))),
		LTRIM(RTRIM(ISNULL(x.[Description],''))), LTRIM(RTRIM(ISNULL(c.IDReg_Number,''))), LTRIM(RTRIM(ISNULL(c.Post_Box,''))),
		LTRIM(RTRIM(ISNULL(c.Post_Office,''))),	LTRIM(RTRIM(ISNULL(c.Post_Code,''))),
		LTRIM(RTRIM(ISNULL(c.Home_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Work_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Cell_No,''))),
		LTRIM(RTRIM(ISNULL(c.Street_Address,''))),	LTRIM(RTRIM(ISNULL(c.Suburb,''))), LTRIM(RTRIM(ISNULL(c.City,''))), LTRIM(RTRIM(ISNULL(c.Street_Post_Code,''))),
				
		LTRIM(RTRIM(ISNULL(c.Delivery_Address,''))), LTRIM(RTRIM(ISNULL(c.Delivery_Suburb,''))), LTRIM(RTRIM(ISNULL(c.Delivery_City,''))), LTRIM(RTRIM(ISNULL(c.Delivery_Post_Code,''))),
		LTRIM(RTRIM(ISNULL(d.Customer_Name,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address1,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address2,''))),
		LTRIM(RTRIM(ISNULL(d.Inv_City,''))), LTRIM(RTRIM(ISNULL(d.Inv_Code,''))),
		LTRIM(RTRIM(ISNULL(d.Delivery_Address,''))), LTRIM(RTRIM(ISNULL(d.Delivery_Suburb,''))),
		LTRIM(RTRIM(ISNULL(d.Delivery_City,''))), LTRIM(RTRIM(ISNULL(d.Delivery_Post_Code,'')))
	FROM 
		AS_Transactions tt
		INNER JOIN AS_Transaction_Details td
			ON tt.AS_Transactions_ID = td.AS_Transactions_ID
		LEFT OUTER JOIN AC_Customers c
			ON tt.AC_Customers_ID = c.AC_Customers_ID
		LEFT OUTER JOIN AS_Transactions_Address a
			ON tt.AS_Transactions_ID = a.AS_Transactions_ID
		LEFT OUTER JOIN AS_Transactions_Address_Detail d
			ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID			
		LEFT OUTER JOIN Slu_AW_Titles x
			ON x.Slu_AW_Titles_ID = c.Slu_AW_Titles_ID
		LEFT OUTER JOIN AP_Products p
			ON td.AP_Products_ID = p.AP_Products_ID
		LEFT OUTER JOIN Lup_AS_Reps sr
			ON tt.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID
		LEFT OUTER JOIN Lup_AS_Reps cr
			ON c.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID
		LEFT OUTER JOIN AW_Users u
			ON tt.[User_ID] = u.AW_Users_ID
		LEFT OUTER JOIN Lup_AC_Sales_Areas sa
			ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID		
	WHERE 
		tt.Slu_AW_Active_ID = 1 AND
		tt.AW_User_Companies_ID = @CompanyID AND
--		(tt.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
--		 tt.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds			 
		 tt.Transaction_Date BETWEEN @FromDate AND @ToDate AND
		 --tt.Transaction_Date BETWEEN '2014-01-01' AND '2014-07-01' AND
		 tt.Total_Amount <> 0
		 AND tt.Sys_AW_Transaction_Types_ID IN (1,3,4,13,16)
		--AND t.AS_Transactions_ID = 49757
	






	SELECT
		CASE C_Firstnames
			WHEN '' THEN C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
													WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
													ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
												END
			ELSE C_Firstnames + ', ' + C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
																	WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
																	ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
																END
		END AS [Customer_Delivery],
		
		CASE C_Firstnames
			WHEN '' THEN C_Surname
			ELSE C_Firstnames + ', ' + C_Surname 
		END AS [Customer],	
		CASE T_Surname
			WHEN '' THEN C_Firstnames + ' ' + C_Surname
			ELSE T_Surname
		END AS [InoicedTo],
		
		CASE @WhichName
			WHEN 0 THEN
				CASE LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code))
					WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_PostalAddress1 + ', ' + C_PostalAddress2 + ', ' + C_PostalCode)) ,',,,',','),',,',',') 
					ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code)) ,',,,',','),',,',',')
				END
			ELSE
				CASE LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code))
					WHEN ',,,' THEN  REPLACE(REPLACE( LTRIM(RTRIM(C_Street_Address + ', ' + C_Suburb + ', ' + C_City + ', ' + C_Street_Post_Code)) ,',,,',','),',,',',')
					ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code)) ,',,,',','),',,',',')
				END
		END	AS [Invoice_Address],
		
		CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
			WHEN ',,,' THEN  REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
			ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
		END AS [Delivery_Address],
		
		P_Description,
		CONVERT(money,(Quantity * Unit_Cost) ) AS [Quantity],
		CONVERT(money,(Extended_Amount - Tax_Amount) - (Quantity * Unit_Cost) ) AS [GP],
		CASE 
			WHEN dbo.fn_AS_Calc_Act_Sales_Value(Extended_Amount, Tax_Amount) <> 0 
			THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(Extended_Amount, Tax_Amount, Quantity, Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(Extended_Amount, Tax_Amount) * 100)) 
			ELSE 0.00 
		END AS [Act GP%],
		(Extended_Amount - Tax_Amount) AS [NetSales],
		Sales_Rep AS [Sales_Rep],
		Cashier AS [Cashier],
		Customer_Rep AS [Customer_Rep],
		Customer_Sales_Area AS [Customer_Sales_Area],
		Transaction_Date				
	FROM @Tbl_T	
	ORDER BY	CASE C_Firstnames
					WHEN '' THEN C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
															WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
															ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
														END
				ELSE C_Firstnames + ', ' + C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
																		WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
																		ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
																	END
		END

	
	
--	Transaction_Date, C_Firstnames + ', ' + C_Surname, Customer_Rep, Customer_Sales_Area
	
	
	 
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Get
--Purpose       :Get Sys_AC_Status
--Parameters    :
--Date          :2014-05-03
--Authors       :RL
--Version       :6.0
--MODS          :
--V6.4	RL		:2018-02-20 Add TDHeader and TDDetail to '#*D*# record
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Sys_AC_Status_Get]
AS

SET NOCOUNT ON


	DECLARE @DB								Varchar(256),
			@SpiralID						Int,
			@LastDayEND						DateTime,
			@DB_Ver							Varchar(30),
			@Company_Name					Varchar(50),
			@Company_Trading_Name			Varchar(50),
			@Company_Registration_Number	Varchar(16),
			@TAX_Number						Varchar(20),
			@Company_Addr1					Varchar(30),
			@Company_Addr2					Varchar(30),
			@Company_City					Varchar(20),
			@Company_Post_Code				Varchar(6),
			@Tel_No							Varchar(20),
			@Fax_No							Varchar(20),
			@E_Mail							Varchar(80),
			@Web_Home						Varchar(50),
			@Delivery_Addr1					Varchar(40),
			@Delivery_Addr2					Varchar(40),
			@Delivery_Addr3					Varchar(40),
			@Country						Varchar(50),
			
			@Today							DateTime,
    		@M1								Tinyint,
    		@Y1								Int,
    		@M2								Tinyint,
    		@Y2								Int,
    		@M3								Tinyint,
    		@Y3								Int,
    		@M4								Tinyint,
    		@Y4								Int,
    		@M5								Tinyint,
    		@Y5								Int,
    		@M6								Tinyint,
    		@Y6								Int,
    		@M7								Tinyint,
    		@Y7								Int,
    		@MinTransactionDate				DateTime,
    		@MaxTransactionDate				DateTime,
    		
			@chkCostSalesEditorGL_0			Varchar(10),
			@optZeroCostOverride_0			Varchar(10),
			@optZeroCostOverride_1			Varchar(10),
			@optZeroCostOverride_2			Varchar(10),
			@optInventoryValuation_0		Varchar(10),
			@optInventoryValuation_1		Varchar(10),
			@optInventoryValuation_2		Varchar(10),
			@chkUseStockAdjGL_0				Varchar(10),
			@chkUseProductPurchasesGL_0		Varchar(10),
			@chkUseProductSalesGL_0    		Varchar(10),
			@Network_Identity_Number    	Varchar(20),
			@Contact1_Email					Varchar(50),
			@Contact2_Email					Varchar(50),

			@chkHistoryDataSent				Integer,
			@txtCSalesExclusions			Varchar(250),
			@txtCSalesInclusions			Varchar(250),
			@txtCInsuranceFile				Varchar(250),

			@AS_CBilling_Providers_No		Integer,
			@AS_CBilling_Providers			Varchar(50),
			@chkSendConnectivitySales		Integer,
			@chkSendCBillingSales			Integer,
			@chkSendCInsuranceData			Integer,
			@chkSendCRewardsData			Integer,
			@txtNextCBFileNo				Varchar(50),
			@txtClickatellSMS				Varchar(50)
			
	DECLARE @Tbl Table
		(
			UniqueID [int] IDENTITY(1,1) PRIMARY KEY,		
			[Rec] [varchar](8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
		)
		
	SELECT @DB = DB_NAME()
	SELECT @Today = GETDATE()

	IF Exists	
	(
		SELECT 1
		FROM AS_Day_ENDs
	)
	BEGIN 
		SELECT @LastDayEND = MAX(Day_END) FROM AS_Day_ENDs
		SELECT @LastDayEND = DateAdd(d,-14,@LastDayEND)
	END
	ELSE
	BEGIN		
		SELECT @LastDayEND = '2016-01-01'
	END

	SET @chkHistoryDataSent = 0
	
	SELECT @chkHistoryDataSent = Control_Index
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkHistoryDataSent' 

	--Mark Stats Records
	UPDATE Sys_AC_Status
	SET Field12 = 1
	WHERE Field12 = 0

	--If this is the first time this procedure runs then select everything from 2016-01-01
	IF @chkHistoryDataSent = 0
	BEGIN
		SET @LastDayEND = '2016-01-01'

		--Mark Stats Records
		UPDATE Sys_AC_Status
		SET Field12 = 1
		WHERE Date_Captured >= @LastDayEND
	END
	
	--Get Ageing
	--@Y1,@M1
	SET @M1 = MONTH(@Today)

    SELECT @Y1 = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@Today)))
	
	--Handeled On The Stats DB
	--SET @MinTransactionDate = '1900-01-01'
	--SELECT @MinTransactionDate = MIN(Transaction_Date)	
	--FROM AS_Transactions
	--WHERE Transaction_Date IS NOT NULL
	
	--SET @MaxTransactionDate = '1900-01-01'
	--SELECT @MaxTransactionDate = MAX(Transaction_Date)
	--FROM AS_Transactions
	--WHERE Transaction_Date IS NOT NULL

	--Sys_AW_Options
	SELECT @chkCostSalesEditorGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkCostSalesEditorGL'
	AND Control_Index = 0
	
	SELECT @optZeroCostOverride_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optZeroCostOverride'
	AND Control_Index = 0

	SELECT @optZeroCostOverride_1 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optZeroCostOverride'
	AND Control_Index = 1

	SELECT @optZeroCostOverride_2 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optZeroCostOverride'
	AND Control_Index = 2

	SELECT @optInventoryValuation_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optInventoryValuation'
	AND Control_Index = 0

	SELECT @optInventoryValuation_1 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optInventoryValuation'
	AND Control_Index = 1

	SELECT @optInventoryValuation_2 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optInventoryValuation'
	AND Control_Index = 2
	
	SELECT @chkUseStockAdjGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkUseStockAdjGL'
	AND Control_Index = 0
	
	SELECT @chkUseProductPurchasesGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkUseProductPurchasesGL'
	AND Control_Index = 0

	SELECT @chkUseProductSalesGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkUseProductSalesGL'
	AND Control_Index = 0

	SELECT @txtCSalesExclusions = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCSalesExclusions'
	AND Control_Index = 0

	SELECT @txtCSalesInclusions = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCSalesExclusions'
	AND Control_Index = 1

	Select @AS_CBilling_Providers_No = Control_Index From Sys_AW_Options Where Control_Name like 'optCBillingProvider' And Control_Value = 'True'

	SELECT @AS_CBilling_Providers = [Description] FROM Lup_AS_CBilling_Providers a WHERE @AS_CBilling_Providers_No =	(	
																															SELECT count(Lup_AS_CBilling_Providers_ID) 
																															FROM Lup_AS_CBilling_Providers b WHERE AW_User_Companies_ID = 1 AND
																															Slu_AW_Active_ID = 1 AND a.Lup_AS_CBilling_Providers_ID >= b.Lup_AS_CBilling_Providers_ID
																														)

	SELECT @chkSendConnectivitySales = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendConnectivitySales'

	SELECT @chkSendCBillingSales = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCBillingSales'

	SELECT @txtCInsuranceFile = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCInsuranceFile'

	SELECT @chkSendCInsuranceData = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCInsuranceData'

	SELECT @chkSendCRewardsData = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCRewardsData'

	SELECT @txtNextCBFileNo = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtNextCBFileNo'

	SELECT @txtClickatellSMS = ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 0

	SELECT @txtClickatellSMS = @txtClickatellSMS + '/' + ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 1

	SELECT @txtClickatellSMS = @txtClickatellSMS + '/' + ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 2

	SELECT @txtClickatellSMS = @txtClickatellSMS + '/' + ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 3

	--@Y2,@M2	
    SET @M2 = @M1 - 1
    SET @Y2 = @Y1

    IF @M2 = 0
	BEGIN
		SET @M2 = 12
		SET @Y2 = @Y2 - 1
	END

	--@Y3,@M3	
    SET @M3 = @M2 - 1
    SET @Y3 = @Y2

    IF @M3 = 0
	BEGIN
		SET @M3 = 12
		SET @Y3 = @Y3 - 1
	END

	--@Y4,@M4	
    SET @M4 = @M3 - 1
    SET @Y4 = @Y3

    IF @M4 = 0
	BEGIN
		SET @M4 = 12
		SET @Y4 = @Y4 - 1
	END

	--@Y5,@M5	
    SET @M5 = @M4 - 1
    SET @Y5 = @Y4

    IF @M5 = 0
	BEGIN
		SET @M5 = 12
		SET @Y5 = @Y5 - 1
	END

	--@Y6,@M6	
    SET @M6 = @M5 - 1
    SET @Y6 = @Y5

    IF @M6 = 0
	BEGIN
		SET @M6 = 12
		SET @Y6 = @Y6 - 1
	END

	--@Y7,@M7	
    SET @M7 = @M6 - 1
    SET @Y7 = @Y6

    IF @M7 = 0
	BEGIN
		SET @M7 = 12
		SET @Y7 = @Y7 - 1
	END

	SELECT 
		@SpiralID = Sp_Account_ID,
		@Company_Name = Replace(IsNull(Company_Name,''),'~',''),
		@Company_Trading_Name = Replace(IsNull(Company_Trading_Name,''),'~',''),
		@Company_Registration_Number = Replace(IsNull(Company_Registration_Number,''),'~',''),
		@TAX_Number = Replace(IsNull(TAX_Number,''),'~',''),
		@Company_Addr1 = Replace(IsNull(Company_Addr1,''),'~',''),
		@Company_Addr2 = Replace(IsNull(Company_Addr2,''),'~',''),
		@Company_City = Replace(IsNull(Company_City,''),'~',''),
		@Company_Post_Code = Replace(IsNull(Company_Post_Code,''),'~',''),
		@Tel_No = Replace(IsNull(Tel_No,''),'~',''),
		@Fax_No = Replace(IsNull(Fax_No,''),'~',''),
		@E_Mail	= Replace(IsNull(E_Mail,''),'~',''),
		@Web_Home = Replace(IsNull(Web_Home,''),'~',''),
		@Delivery_Addr1 = Replace(IsNull(Delivery_Addr1,''),'~',''),
		@Delivery_Addr2	 = Replace(IsNull(Delivery_Addr2,''),'~',''),
		@Delivery_Addr3 = Replace(IsNull(Delivery_Addr3,''),'~',''),
		@Country = Replace(IsNull(s.[Description],''),'~',''),
		@Network_Identity_Number = Replace(IsNull(Network_Identity_Number,''),'~',''),
		@Contact1_Email = Replace(IsNull(Contact1_Email,''),'~',''),
		@Contact2_Email = Replace(IsNull(Contact2_Email,''),'~','')
	FROM AW_User_Companies c
		LEFT OUTER JOIN Slu_AW_Countries s
			ON c.Slu_AW_Countries_ID = s.Slu_AW_Countries_ID
	
	SELECT Top 1 @DB_Ver = Release FROM AA_Release Order By AA_Release_ID Desc

	--Insert Header Record		
	INSERT INTO @Tbl
	SELECT '#*H*#' + '~' + Convert(varchar(10),@SpiralID)  + '~' + @DB + '~2018.6.4'

	--Insert Sales Records
	INSERT INTO @Tbl
	SELECT
		'#*M*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(20),IsNull(t.Transaction_Number,-9)) + '~' +									
		Convert(varchar(20),IsNull(t.Transaction_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(5),IsNull(t.Sys_AW_Transaction_Types_ID,255)) + '~' + 		
		Convert(varchar(20),IsNull(t.Total_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Total_Tax_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Total_Discount_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Total_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Payment_Amount,0)) + '~' + 
		Replace(IsNull(t.Customer_Reference,''),'~','') + '~' + 
		Replace(IsNull(t.Comment,''),'~','') + '~' + 		
		Convert(varchar(10),IsNull(t.[User_ID],-9)) + '~' +
		Replace(IsNull(u.FirstName,''),'~','') + ' ' + Replace(IsNull(u.Surname,''),'~','') + '~' +		--User_Full_Name					Varchar(100)
		Replace(IsNull(u.[UserName],''),'~','') + '~' +													--User_Name							Varchar(20)
		Convert(varchar(10),IsNull(t.Lup_AS_Reps_ID,-9)) + '~' +										--Transaction_Rep_ID				Int
		Case IsNull(tr.[Description],'')																
		When '<SELECT>' Then '1'
		When '<None>' Then '1'
		ELSE Replace(IsNull(tr.[Description],''),'~','')
		END + '~' +																						--Transaction Rep					Varchar(30)
		Convert(varchar(10),IsNull(c.Lup_AS_Reps_ID,-9)) + '~' +										--Customer_Rep_ID					Int
		Case IsNull(cr.[Description],'')
		When '<SELECT>' Then '1'
		When '<None>' Then '1'
		ELSE Replace(IsNull(cr.[Description],''),'~','')
		END + '~' +																						--Customer_Rep						Varchar(30)
		Convert(varchar(5),IsNull(c.Sys_AC_Account_Types_ID,255)) + '~' + 
		Replace(IsNull(c.Surname,''),'~','') + '~' + 
		Replace(IsNull(c.Firstnames,''),'~','') + '~' + 
		Replace(IsNull(c.Initials,''),'~','') + '~' + 
		Replace(IsNull(c.IDReg_Number,''),'~','') + '~' + 
		Replace(IsNull(c.Customer_Number,''),'~','') + '~' + 
		Replace(IsNull(c.Post_Box,''),'~','') + '~' + 
		Replace(IsNull(c.Post_Office,''),'~','') + '~' + 
		Replace(IsNull(c.Post_Code,''),'~','') + '~' + 
		Replace(IsNull(c.Street_Address,''),'~','') + '~' + 
		Replace(IsNull(c.Suburb,''),'~','') + '~' + 
		Replace(IsNull(c.Street_Post_Code,''),'~','') + '~' + 
		Replace(IsNull(c.City,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Address,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Suburb,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_City,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Suburb,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Post_Code,''),'~','') + '~' + 
		Replace(IsNull(c.Head_Office,''),'~','') + '~' + 
		Replace(IsNull(ct.[Description],''),'~','') + '~' + 
		Replace(IsNull(c.Cell_No,''),'~','') + '~' + 
		Replace(IsNull(c.Home_Tel_No,''),'~','') + '~' + 
		Replace(IsNull(c.Work_Tel_No,''),'~','') + '~' + 
		Replace(IsNull(c.Fax_No,''),'~','') + '~' + 
		Replace(IsNull(c.Web_Site_URL,''),'~','') + '~' + 
		Replace(IsNull(c.Orders_URL,''),'~','') + '~' + 
		Replace(IsNull(c.Home_Email,''),'~','') + '~' + 
		Replace(IsNull(c.Work_Email,''),'~','') + '~' + 
		Replace(IsNull(c.Tax_Number,''),'~','') + '~' + 
		Replace(IsNull(cg.[Description],''),'~','') + '~' + 				
		Replace(IsNull(td.Inv_Address1,''),'~','') + '~' + 
		Replace(IsNull(td.Inv_Address2,''),'~','') + '~' + 
		Replace(IsNull(td.Inv_City,''),'~','') + '~' + 
		Replace(IsNull(td.Inv_Code,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_Address,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_Suburb,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_City,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_Post_Code,''),'~','') + '~' + 
		Replace(IsNull(td.Customer_Name,''),'~','') + '~' + 
		Replace(IsNull(td.Tax_Number,''),'~','') + '~' + 
		--Added V6.3
		Convert(varchar(5),IsNull(c.Sys_AC_Account_Status_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(c.Credit_Limit,0)) + '~' + 
		Replace(IsNull(z.[Description],''),'~','') + '~' +												--Credit_Terms						Varchar(20)
		Convert(varchar(5),IsNull(z.Terms_Value,0)) + '~' +												--Credit_Terms_Value				Int
		Convert(varchar(5),IsNull(c.Sys_AC_Credit_Term_Types_ID,255)) + '~' +									
		Convert(varchar(5),IsNull(c.Sys_AC_Account_Types_ID,255)) + '~' + 
		Replace(IsNull(c.Credit_Insurers_Reference,''),'~','') + '~' +									--									Varchar(20)
		Convert(varchar(20),IsNull(c.Credit_Insurers_Limit,0)) + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +										--Slu_AW_Active_ID_Transaction_H	Int
		Convert(varchar(5),IsNull(c.Slu_AW_Active_ID,255)) + '~' +										--Slu_AW_Active_ID_Customer			Int 
		Convert(varchar(20),ISNULL(t.Day_End,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' + 
		Convert(varchar(10),IsNull(t.AC_Customers_ID,-9)) + '~' +										--Product_Description				Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +									--Date_Extracted 
		'0'	+ '~' +																							--Transaction_Detail_Link			Int

		--V6.4
		--Erick 2018-04-13
		Replace(IsNull('',''),'~','') + '~' +													--Cell_No	Varchar(16)
		Replace(IsNull('',''),'~','')																--Email		Varchar(100)
	FROM AS_Transactions t
		Left Join AC_Customers c
			On t.AC_Customers_ID = c.AC_Customers_ID
		Left Join Lup_AS_Reps tr
			On t.Lup_AS_Reps_ID = tr.Lup_AS_Reps_ID
		Left Join Lup_AS_Reps cr
			On c.Lup_AS_Reps_ID = cr.Lup_AS_Reps_ID
		Left Join AW_Users u
			On t.[User_ID] = u.AW_Users_ID		
		Left Join Sys_AC_Account_Types at
			On c.Sys_AC_Account_Types_ID = at.Sys_AC_Account_Types_ID
		Left Join Lup_AC_Customer_Types ct
			On c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID
		Left Join Lup_AC_Customer_Groups cg
			On c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID	
		Left Join AS_Transactions_Address ta
			On ta.AS_Transactions_ID = t.AS_Transactions_ID
		Left Join AS_Transactions_Address_Detail td
			On ta.AS_Transactions_Address_Detail_ID = td.AS_Transactions_Address_Detail_ID
		Left Join Slu_AW_Credit_Terms z
			On c.Slu_AW_Credit_Terms_ID = z.Slu_AW_Credit_Terms_ID
	WHERE
		t.Sys_AW_Transaction_Types_ID in (1,2,3,4,5,7,13,15,16,17,18,21,22,23,24,33,34,35,36)  AND
		t.Date_Captured > @LastDayEND

	INSERT INTO @Tbl
	SELECT
		'#*D*#'  + '~' + 
		Convert(varchar(10),IsNull(d.AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(d.AS_Transaction_Details_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(d.AP_Products_ID,-9)) + '~' + 
		Convert(varchar(20),IsNull(d.Quantity,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Unit_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Unit_Price,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Original_Price,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Original_Discount,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Discount_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Tax_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Extended_Amount,0)) + '~' + 
		Convert(varchar(10),IsNull(d.AS_Job_References_ID,-9)) + '~' + 
		--V6.3
		Convert(varchar(5),IsNull(d.Slu_AW_Active_ID,255)) + '~' +										--Slu_AW_Active_ID_Transaction_D	Int 
		Convert(varchar(20),IsNull(d.Back_Order,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Date_Captured,'1900-01-01'),120) + '~' + 
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +												--									Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +												--Product_Description				Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +									--Date_Extracted
		--V6.4
		Replace(IsNull(d.TDHeader,''),'~','') + '~' +													--TDHeader							Varchar(256)
		Replace(IsNull(d.TDDetail,''),'~','')															--TDDetail							Varchar(256)
	FROM AS_Transactions t
		Left Join AS_Transaction_Details d
			On t.AS_Transactions_ID = d.AS_Transactions_ID
		Left Join AP_Products p
			On d.AP_Products_ID = p.AP_Products_ID
	WHERE 
		t.Sys_AW_Transaction_Types_ID in (1,2,3,4,5,7,13,15,16,17,18,21,22,23,24,33,34,35,36)  AND
		t.Date_Captured > @LastDayEND
	
	--V6.3
	INSERT INTO @Tbl
	SELECT
		'#*Y*#'  + '~' + 
		Convert(varchar(10),IsNull('',-9)) + '~' + 
		Convert(varchar(10),IsNull('',-9)) + '~' + 
		Convert(varchar(5),IsNull('',255)) + '~' + 
		Convert(varchar(20),IsNull('',0)) + '~' + 
		Convert(varchar(20),IsNull('','1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull('','1900-01-01'),120)											--Date_Extracted
	--FROM AS_Transaction_Payments
	--WHERE Date_Captured > @LastDayEND

	--V6.4
	INSERT INTO @Tbl
	SELECT
		'#*I*#'  + '~' + 
		Convert(varchar(10),IsNull('',-9)) + '~' +							--Int
		Replace(IsNull('',''),'~','') + '~' +													--Varchar(10)
		Convert(varchar(10),IsNull('',-9)) + '~' +										--Int
		Convert(varchar(10),IsNull('',-9)) + '~' +								--Int
		Replace(IsNull('',''),'~','') + '~' +														--Varchar(50)
		Replace(IsNull('',''),'~','') + '~' +												--Varchar(50)
		Replace(IsNull('',''),'~','') + '~' +												--Varchar(50)
		Replace(IsNull('',''),'~','') + '~' +														--Varchar(250)
		Convert(varchar(10),IsNull('',-9)) + '~' +												--Int
		Replace(IsNull('',''),'~','') + '~' +														--Varchar(20)
		Replace(IsNull('',''),'~','') + '~' +														--Varchar(100)
		Replace(IsNull('',''),'~','') + '~' +													--Varchar(50)
		Replace(IsNull('',''),'~','') + '~' +											--Varchar(250)
		Replace(IsNull('',''),'~','') + '~' +													--Varchar(20)
		Convert(varchar(20),IsNull('','1900-01-01'),120) + '~' +								--Datetime
		Convert(varchar(20),IsNull('','1900-01-01'),120) + '~' + 											--Date_Extracted
		
		--V6.4
		--Erick 2018-04-13
		Convert(varchar(20),IsNull('',0))															--Amount		Decimal(18,3)
	

	--V6.3
	INSERT INTO @Tbl
	SELECT
		'#*X*#'  + '~' + 
		Convert(varchar(10),IsNull(AS_Transactions_Transactions_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(Source_AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(Destination_AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(20),IsNull(Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)											--Date_Extracted		
	FROM AS_Transactions_Transactions
	WHERE Date_Captured > @LastDayEND

	--Centralised Sales
	INSERT INTO @Tbl
	SELECT
		'#*N*#'  + '~' +
		Convert(varchar(10),IsNull(AS_Transactions_ID,-9)) + '~' +										--Integer
		Replace(IsNull(Customer_Number,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Network_Identity_Number,''),'~','') + '~' +										--Varchar(10)
		Convert(varchar(10),IsNull(Sys_AW_Transaction_Types_ID,255)) + '~' +							--Integer
		Replace(IsNull(Transaction_Number,''),'~','') + '~' +											--Varchar(19)
		Replace(IsNull(Original_Number,''),'~','') + '~' +												--Varchar(19)
		Convert(varchar(20),IsNull(Transaction_Date,'1900-01-01'),120) + '~' +							--Datetime
		Replace(IsNull(Manufacturer_Code,''),'~','') + '~' +											--Varchar(18)
		Convert(varchar(20),IsNull(Quantity,0)) + '~' +													--Decimal(18,3)
		Convert(varchar(20),IsNull(Extended_Amount,0)) + '~' +											--Decimal(18,3)
		Convert(varchar(20),IsNull(Tax_Amount,0)) + '~' +												--Decimal(18,3)
		Convert(varchar(20),IsNull(Discount_Amount,0)) + '~' +											--Decimal(18,3)
		Convert(varchar(10),IsNull(Lup_AP_Fail_Reasons_ID,255)) + '~' +									--Integer
		Convert(varchar(10),IsNull(Item_No,255)) + '~' +												--Integer
		Replace(IsNull(Authorization_No,''),'~','') + '~' +												--Varchar(30)
		Replace(IsNull(Registration_No,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Odometer_Reading,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Make,''),'~','') + '~' +															--Varchar(30)
		Replace(IsNull(Model,''),'~','') + '~' +														--Varchar(30)
		Replace(IsNull(Model_Year,''),'~','') + '~' +													--Varchar(10)
		Replace(IsNull(Client_ID_No,''),'~','') + '~' +													--Varchar(13)
		Replace(IsNull(Engine_No,''),'~','') + '~' +													--Varchar(24)
		Replace(IsNull(Chassis_No,''),'~','') + '~' +													--Varchar(24)
		Convert(varchar(10),IsNull(Lup_AP_Claim_Codes_ID,255)) + '~' +									--Integer
		Convert(varchar(20),IsNull(Xmit_Date,'1900-01-01'),120) + '~' +									--Datetime
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +								--Datetime
		Convert(varchar(10),IsNull(Slu_AW_Active_ID,255)) + '~' +										--Integer
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)											---Date_Extracted			Datetime
	From AS_Transactions_CBilling
	WHERE Date_Captured > @LastDayEND 

	--Insert Customer Asset Details
	INSERT INTO @Tbl
	SELECT
		'#*L*#'  + '~' +
		Convert(varchar(10),IsNull(AC_Customers_ID,-9)) + '~' +									--Integer
		Replace(IsNull(Make,''),'~','') + '~' +													--Varchar(30)
		Replace(IsNull(Model,''),'~','') + '~' +												--Varchar(30)
		Replace(IsNull(Model_Year,''),'~','') + '~' +											--Varchar(10)
		Convert(varchar(5),IsNull(Lup_AC_Asset_Types_ID,255)) + '~' +							--Integer
		Replace(IsNull(Reg_No,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Engine_No,''),'~','') + '~' +											--Varchar(24)
		Replace(IsNull(Chassis_No,''),'~','') + '~' +											--Varchar(24)
		Replace(IsNull(VIN_No,''),'~','') + '~' +												--Varchar(24)
		Replace(IsNull(Mileage,''),'~','') + '~' +												--Varchar(24)
		Replace(IsNull(Mileage_Date,''),'~','') + '~' +											--Varchar(10)
		Replace(IsNull(Tyre_Size,''),'~','') + '~' +											--Varchar(24)
		Replace(IsNull(Tyre_Qty,''),'~','') + '~' +												--Varchar(24)
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +						--Datetime
		Convert(varchar(5),IsNull(Slu_AW_Active_ID,255)) + '~' +								--Integer
		Convert(varchar(10),IsNull(AS_Transactions_ID,-9)) + '~' +								--Integer
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)									--Date_Extracted
	FROM AC_Assets
	WHERE Date_Captured > @LastDayEND

	--Insert Product Records
	INSERT INTO @Tbl
	SELECT
		'#*P*#'  + '~' + 
		Convert(varchar(10),IsNull(p.AP_Products_ID,-9)) + '~' + 
		Replace(IsNull(p.[Description],''),'~','') + '~' + 
		Replace(IsNull(p.Product_Code,''),'~','') + '~' + 
		Replace(IsNull(p.Manufacturer_Code,''),'~','') + '~' + 
		Replace(IsNull(m.[Description],''),'~','') + '~' + 
		Convert(varchar(20),IsNull(p.Last_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(p.Average_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(p.Standard_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(p.Price1_Effective_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(20),IsNull(p.Price1_Price1,0)) + '~' + 
		Convert(varchar(5),IsNull(p.Slu_AW_YesNo_Non_Stock_Item,255)) + '~' + 
		Convert(varchar(5),IsNull(p.Slu_AW_YesNo_Levy_Item,255)) + '~' + 
		Convert(varchar(20),IsNull(p.On_Hand,0)) + '~' + 
		--V6.3
		Replace(IsNull(t.[Description],''),'~','') + '~' +													--Product_Types						Varchar(50) 
		Replace(IsNull(g.[Description],''),'~','') + '~' +													--Product_Groups					Varchar(50)  
		Replace(IsNull(d.[Description],''),'~','') + '~' +													--Product_Departments				Varchar(50)  
		Replace(IsNull(l.[Description],''),'~','') + '~' +													--Product_Locations					Varchar(50)  
		Replace(IsNull(c.[Description],''),'~','') + '~' +													--Product_Purchase_Categories		Varchar(50)  
		Convert(varchar(5),IsNull(p.Slu_AW_Active_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(Last_Sale_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(20),IsNull(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0)) + '~' +		--Consignment_Supplier				Decimal(18,4)
		Convert(varchar(20),IsNull(dbo.fn_AP_Get_Products_Out_On_Consignment(p.AP_Products_ID),0)) + '~' +	--Consignment_Customer				Decimal(18,4)
		Convert(varchar(20),IsNull(p.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Replace(IsNull(p.Manufacturer_Description,''),'~','') + '~' +										--Manufacturer_Description			Varchar(50)
		Replace(IsNull(s.Supplier_Name,''),'~','') + '~' +													--Supplier Name						Varchar(50)
		Replace(IsNull(p.SKU_Code,''),'~','') + '~' +														--SKU_Code							Varchar(20)
		Replace(IsNull(p.Supercession,''),'~','') + '~' +													--Supercession						Varchar(20)
		Replace(IsNull(p.Alternate_Code1,''),'~','') + '~' +												--Alternate_Code1					Varchar(20)
		Replace(IsNull(p.Alternate_Code2,''),'~','') + '~' +												--Alternate_Code2					Varchar(20)
		Convert(varchar(5),IsNull(p.Sys_AW_Tax_Codes_ID,255)) + '~' +										--Sys_AW_Tax_Codes_ID				Integer
		Convert(varchar(20),IsNull(p.Min_Stock_Level,0)) + '~' +											--Min_Stock_Level					Varchar(20)
		Convert(varchar(20),IsNull(p.Service_Level,0)) + '~' +												--Service_Level						Decimal(18,3)
		Convert(varchar(20),IsNull(p.Max_Order_Qty,0)) + '~' +												--Max_Order_Qty						Decimal(18,3)
		Convert(varchar(20),IsNull(p.Min_Order_Qty,0))														--Min_Order_Qty						Decimal(18,3)
	FROM AP_Products p
		Left Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
		Left Join Lup_AP_Product_Types t
			On p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID	
		Left Join Lup_AP_Product_Groups g
			On p.Lup_AP_Product_Groups_ID = g.Lup_AP_Product_Groups_ID	
		Left Join Lup_AP_Product_Departments d
			On p.Lup_AP_Product_Departments_ID = d.Lup_AP_Product_Departments_ID	
		Left Join Lup_AP_Product_Locations l
			On p.Lup_AP_Product_Locations_ID = l.Lup_AP_Product_Locations_ID	
		Left Join Lup_AP_Purchase_Categories c
			On p.Lup_AP_Purchase_Categories_ID = c.Lup_AP_Purchase_Categories_ID
		Left Join AO_Suppliers s
			On p.Default_Supplier_ID = s.AO_Suppliers_ID

	--V6.3
	--Insert Supplier / GRV Info
	INSERT INTO @Tbl
	SELECT 
		'#*S*#'  + '~' +  
		Convert(varchar(10),IsNull(t.AO_Transactions_ID,-9)) + '~' +
		Convert(varchar(10),IsNull(t.AO_Suppliers_ID,-9)) + '~' +
		Replace(IsNull(s.Supplier_Name,''),'~','') + '~' +
		Replace(IsNull(c.[Description],''),'~','') + '~' +													--Credit_Terms					Varchar(20)
		Replace(IsNull(c.Terms_Value,''),'~','') + '~' +													--Credit_Terms_Value			Int
		Convert(varchar(20),IsNull(s.Credit_Limit,0)) + '~' +
		Convert(varchar(20),IsNull(t.Document_Date,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Convert(varchar(10),IsNull(t.AO_GRV_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(t.Trade_Discount_Total,0)) + '~' +										--H_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Rebate_Discount_Total,0)) + '~' +										--H_Rebate_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Other_Discount_Total,0)) + '~' +										--H_Other_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Net_Amount,0)) + '~' +													--H_Net_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(t.Total_Tax_Amount,0)) + '~' +											--H_Total_Tax_Amount			Decimal(18,4)
		Convert(varchar(20),IsNull(t.Total_Amount,0)) + '~' +												--H_Total_Amount				Decimal(18,4)
		Convert(varchar(20),IsNull(t.Payment_Amount,0)) + '~' +												--H_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Settlement_Discount,0)) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +											--H_Slu_AW_Active_ID			Int
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +								--H_Date_Captured				Datetime		
		Convert(varchar(20),IsNull(g.Date_Received,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(d.AP_Products_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(d.Qty,0)) + '~' +
		Convert(varchar(20),IsNull(d.Unit_Price,0)) + '~' +
		Convert(varchar(20),IsNull(d.Trade_Discount_Amount,0)) + '~' +										--D_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Rebate_Discount_Amount,0)) + '~' +										--D_Rebate_Discount_Amount		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Other_Discount_Amount,0)) + '~' +										--D_Other_Discount_Amount		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Net_Amount,0)) + '~' +													--D_Net_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(d.Tax_Amount,0)) + '~' +													--D_Tax_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(d.Total_Cost,0)) + '~' +													--D_Total_Cost					Decimal(18,4)
		Convert(varchar(5),IsNull(d.Slu_AW_Active_ID,255)) + '~' +											--D_Slu_AW_Active_ID			Int		
		Convert(varchar(20),IsNull(d.Date_Captured,'1900-01-01'),120) + '~' +								--D_Date_Captured				Datetime		
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +													--								Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +													--Product_Description			Varchar(50)
 		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted  
 		Replace(IsNull(m.[Description],''),'~','') + '~' +													--Product_Manufacturer			Varchar(50) 
		Replace(IsNull(y.[Description],''),'~','') + '~' +													--Product_Types					Varchar(50) 
		Replace(IsNull(r.[Description],''),'~','') + '~' +													--Product_Groups				Varchar(50)
		Convert(varchar(10),IsNull(d.AO_GRV_Details_ID,-9)) + '~' +  
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AO_Transactions t
		Inner Join AO_Suppliers s
			On t.AO_Suppliers_ID = s.AO_Suppliers_ID
		Inner Join Slu_AW_Credit_Terms c
			On s.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
		Left Outer Join AO_GRV g
			On t.AO_GRV_ID = g.AO_GRV_ID
		Left Outer Join AO_GRV_Details d
			On t.AO_GRV_ID = d.AO_GRV_ID
		Left Outer Join AP_Products p
			On p.AP_Products_ID = d.AP_Products_ID
		Left Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
		Left Join Lup_AP_Product_Types y
			On p.Lup_AP_Product_Types_ID = y.Lup_AP_Product_Types_ID	
		Left Join Lup_AP_Product_Groups r
			On p.Lup_AP_Product_Groups_ID = r.Lup_AP_Product_Groups_ID
	WHERE t.Date_Captured > @LastDayEND
	OR g.Date_Captured > @LastDayEND
	
	--V6.3
	--Product Adjustments
	INSERT INTO @Tbl
	SELECT 
		'#*A*#'  + '~' +
		Convert(varchar(10),IsNull(i.AP_Products_ID,-9)) + '~' +
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +													--								Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +													--Product_Description			Varchar(50)
		Convert(varchar(5),IsNull(Sys_AP_Adjustment_Types_ID,255)) + '~' +
		Convert(varchar(20),IsNull(Previous_Last_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(Previous_Average_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(Previous_On_Hand,0)) + '~' +
		Convert(varchar(20),IsNull(New_Last_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(New_Average_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(New_On_Hand,0)) + '~' +
		Replace(IsNull(Note,''),'~','') + '~' +																--								Varchar(70)
		Convert(varchar(20),IsNull(i.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(i.AP_Inventory_Adjustments_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted	
		Convert(varchar(10),IsNull(i.[User_ID],-9))															--User_ID						Int
	From AP_Inventory_Adjustments i
			Left Outer Join AP_Products p
				On p.AP_Products_ID = i.AP_Products_ID	
	WHERE i.Date_Captured > @LastDayEND
	
	--V6.3
	--GL Accounts Info
	INSERT INTO @Tbl
	SELECT 
		'#*G*#'  + '~' + 
 		Convert(varchar(10),IsNull(aa.AB_Accounts_ID,-9)) + '~' +
		Replace(IsNull(aa.[Description],''),'~','') + '~' +													--Account_Description			Varchar(50)
		Replace(IsNull(aa.Account_Number,''),'~','') + '~' +
		Replace(IsNull(ac.[Description],''),'~','') + '~' +													--Account_Categories			Varchar(100)
		Replace(IsNull(tc.[Description],''),'~','') + '~' +													--Tax_Codes						Varchar(50)
		Convert(varchar(18),IsNull(tc.Tax_Rate,0)) + '~' +													--								Char(1)
		Replace(IsNull(cc.[Description],''),'~','') + '~' +													--Account_Cost_Centers			Varchar(50)
		Convert(varchar(20),IsNull(aa.AB_Account_Balance,0)) + '~' +
		Convert(varchar(5),IsNull(aa.AW_YesNo_Controllable_ID,255)) + '~' +
		Convert(varchar(20),IsNull(aa.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(aa.Slu_AW_Active_ID,255)) + '~' +
		Replace(IsNull(ag.[Description],''),'~','') + '~' +													--Account_Groups				Varchar(50)
		Replace(IsNull(ad.[Description],''),'~','') + '~' +													--Account_Divisions				Varchar(50)
		Replace(IsNull(dp.[Description],''),'~','') + '~' +													--Account_Departments			Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted		
		Convert(varchar(5),IsNull(ca.Control_Number,255)) + '~' +											--Control_Number				Integer
		Replace(IsNull(ca.[Description],''),'~','') + '~' +													--Control_Account				Varchar(50)	
		Replace(IsNull(ca.[User_Description],''),'~','') + '~' +											--Control_Account_User			Varchar(50)	
		Convert(varchar(5),IsNull(ca.Control_Type,255)) + '~' +												--Control_Type					Integer
		Replace(IsNull(aa.Sys_AB_Account_Categories_ID,''),'~','')											--Sys_AB_Account_Categories_ID  Integer
	FROM AB_Accounts aa
		Inner Join Sys_AB_Account_Categories ac
			On aa.Sys_AB_Account_Categories_ID = ac.Sys_AB_Account_Categories_ID
		Inner Join Sys_AW_Tax_Codes tc
			On aa.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
		Inner Join Lup_AB_Cost_Centers cc
			On aa.Lup_AB_Cost_Centers_ID = cc.Lup_AB_Cost_Centers_ID
		Inner Join Lup_AB_Account_Groups ag
			On aa.Lup_AB_Account_Groups_ID = ag.Lup_AB_Account_Groups_ID
		Inner Join Lup_AB_Account_Divisions ad
			On aa.Lup_AB_Account_Divisions_ID = ad.Lup_AB_Account_Divisions_ID
		Inner Join Lup_AB_Account_Departments dp
			On aa.Lup_AB_Account_Departments_ID = dp.Lup_AB_Account_Departments_ID

		Left Join AB_Control_Accounts ca
			On aa.AB_Accounts_ID = ca.AB_Accounts_ID

	--V6.3
	--Income & Balance Sheet Statement Setup
	INSERT INTO @Tbl
	SELECT
		'#*B*#'  + '~' +  
		'Sys_AB_B1' + '~' +																					--Statement_Level					Varchar(10)
		Convert(varchar(10),IsNull(Sys_AB_B1_ID,-9)) + '~' +												--Statement_ID						Integer
		Replace(IsNull([Description],''),'~','')															--Statement_Description				Varchar(100)
	FROM Sys_AB_B1
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_B2' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_B2_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_B2
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_B3' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_B3_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_B3
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I1' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I1_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I1
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I2' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I2_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I2
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I3' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I3_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I3
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I4' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I4_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I4
	ORDER BY 1
	
	--V6.3
	--Income & Balance Sheet Statement Setup
	INSERT INTO @Tbl
	SELECT
		'#*C*#'  + '~' + 
		Convert(varchar(10),IsNull(Sys_AB_Account_Categories_ID,-9)) + '~' +								--Sys_AB_Account_Categories_ID		Integer
		Replace(IsNull([Description],''),'~','') + '~' +													--Description						Varchar(100)
		Convert(varchar(10),IsNull(Sys_AB_B1_ID,-9)) + '~' +												--Sys_AB_B1_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_B2_ID,-9)) + '~' +												--Sys_AB_B2_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_B3_ID,-9)) + '~' +												--Sys_AB_B3_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I1_ID,-9)) + '~' +												--Sys_AB_I1_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I2_ID,-9)) + '~' +												--Sys_AB_I2_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I3_ID,-9)) + '~' +												--Sys_AB_I3_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I4_ID,-9)) + '~' +												--Sys_AB_I4_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_Account_Types_ID,255)) + '~' +									--Sys_AB_Account_Types_ID			Integer
		Convert(varchar(18),IsNull(Notes,0))																--Notes								Decimal(5,2)
	FROM Sys_AB_Account_Categories

	--V6.3 Budgets
	INSERT INTO @Tbl
 	SELECT
 		'#*F*#'  + '~' + 
		Convert(varchar(10),IsNull(b.AB_Budgets_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(b.AB_Accounts_ID,-9)) + '~' +
		Replace(IsNull(a.[Description],''),'~','') + '~' +
		Convert(varchar(10),IsNull(b.Slu_AW_Years_ID,255)) + '~' +
		Convert(varchar(10),IsNull(b.Slu_AW_Months_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(b.Budget_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(b.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(b.Slu_AW_Active_ID,255)) + '~' +		
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +
		
		Convert(varchar(5),IsNull(ca.Control_Number,255)) + '~' +											--Control_Number				Integer
		Replace(IsNull(ca.[Description],''),'~','') + '~' +													--Control_Account				Varchar(50)	
		Replace(IsNull(ca.[User_Description],''),'~','') + '~' +											--Control_Account_User			Varchar(50)	
		Convert(varchar(5),IsNull(ca.Control_Type,255))														--Control_Type					Integer
	FROM AB_Budgets b
		Inner Join AB_Accounts a
			On b.AB_Accounts_ID = a.AB_Accounts_ID
		Left Join AB_Control_Accounts ca
			On a.AB_Accounts_ID = ca.AB_Accounts_ID
	
	--V6.3 Transactions
	INSERT INTO @Tbl
 	SELECT
 		'#*T*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AB_GL_Transactions_ID,-9)) + '~' + 
		Replace(Replace(IsNull(t.[Description],''),'~',''), CHAR(13) + CHAR(10) , ', ' ) + '~' +			--GL_Description					Varchar(50)
		Convert(varchar(5),IsNull(t.Sys_AB_Transaction_Types_ID,255)) + '~' + 
		Convert(varchar(10),IsNull(t.AB_Accounts_ID,-9)) + '~' +  
		Replace(IsNull(a.[Description],''),'~','') + '~' +													--Account_Description				Varchar(50)
		Convert(varchar(20),IsNull(t.AB_Transaction_Date,'1900-01-01'),120) + '~' + 
		Replace(IsNull(t.AB_Source_Ref,''),'~','') + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +  
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Replace(IsNull(t.AB_Transaction_Ref,''),'~','') + '~' + 
		Convert(varchar(20),IsNull(t.AB_Transaction_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AB_GL_Transactions t
		LEFT JOIN AB_Accounts a
			On t.AB_Accounts_ID = a.AB_Accounts_ID
	WHERE t.Date_Captured > @LastDayEND
	
	INSERT INTO @Tbl
 	SELECT
 		'#*T*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AB_GL_Transactions_ID,-9)) + '~' + 
		Replace(Replace(IsNull(t.[Description],''),'~',''), CHAR(13) + CHAR(10) , ', ' ) + '~' +			--GL_Description					Varchar(50)
		Convert(varchar(5),IsNull(t.Sys_AB_Transaction_Types_ID,255)) + '~' + 
		Convert(varchar(10),IsNull(t.AB_Accounts_ID,-9)) + '~' +  
		Replace(IsNull(a.[Description],''),'~','') + '~' +													--Account_Description				Varchar(50)
		Convert(varchar(20),IsNull(t.AB_Transaction_Date,'1900-01-01'),120) + '~' + 
		Replace(IsNull(t.AB_Source_Ref,''),'~','') + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +  
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Replace(IsNull(t.AB_Transaction_Ref,''),'~','') + '~' + 
		Convert(varchar(20),IsNull(t.AB_Transaction_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AB_GL_Transactions t
		INNER JOIN AB_GL_Transactions_Audit x
			On t.AB_GL_Transactions_ID = x.AB_GL_Transactions_ID
		LEFT JOIN AB_Accounts a
			On t.AB_Accounts_ID = a.AB_Accounts_ID
	WHERE x.Date_Captured > @LastDayEND

	--Customer Condensed Age Analysis
	SET FMTONLY ON
	Exec sp_AC_Customer_Statements_Temp_Insert @Today, 0, 0, 1, 1
	SET FMTONLY OFF
	
	--V6.3
	INSERT INTO @Tbl
    SELECT
		'#*W*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AC_Customers_ID,-9)) + '~' +
		Replace(IsNull(t.FullName,''),'~','') + '~' +														--								Varchar(100)
		Replace(IsNull(t.Customer_Number,''),'~','') + '~' +												--								Varchar(10)
		Convert(varchar(20),IsNull(t.Account_Balance, 0)) + '~' +
		Convert(varchar(20),IsNull(t.[Current],0)) + '~' +
		Convert(varchar(20),IsNull(t.[30Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[60Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[90Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[120Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[150Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[180+Days],0)) + '~' +
		Convert(varchar(20),IsNull(dbo.fn_AC_Get_Last_Payment_Date(t.AC_Customers_ID),'1900-01-01'),120) + '~' +--[Last_Pay_Date]				Datetime
		Convert(varchar(20),IsNull(dbo.fn_AC_Get_Last_Payment_Amount(t.AC_Customers_ID),0)) + '~' + 		--[Last_Pay_Amount]				Decimal(18,4)
		Convert(varchar(20),IsNull(c.Credit_Limit,0)) + '~' +
		Replace(IsNull(tt.[Description],''),'~','') + '~' +													--Credit_Terms					Varchar(20)
		Convert(varchar(10),IsNull(tt.Terms_Value,0)) + '~' +												--Credit_Terms_Value			Int
		Convert(varchar(5),IsNull(c.Sys_AC_Credit_Term_Types_ID,255)) + '~' +    
	    Convert(varchar(20),IsNull(c.Credit_Insurers_Limit,0)) + '~' +										--								Decimal(18,4)
	    Replace(IsNull(s.[Description],''),'~','') + '~' +													--Customer_Account_Status		Varchar(50)
	    Convert(varchar(18),IsNull(c.Default_Settlement_Discount,0)) + '~' +								--								Decimal(18,4)    
	    Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120)
	FROM AC_Statements_Temp t    
		INNER JOIN AC_Customers c 
			ON t.AC_Customers_ID = c.AC_Customers_ID
		LEFT JOIN Sys_AC_Account_Status s
			ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
		LEFT JOIN Slu_AW_Credit_Terms tt
			ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID
				
	--Supplier Age Analysis
	SET FMTONLY ON
	EXEC sp_AO_Supplier_Remittances_Temp_Insert @Today, 1, 1, 0, @M1, @Y1, @M2, @Y2, @M3, @Y3, @M4, @Y4, @M5, @Y5, @M6, @Y6, @M7, @Y7
	SET FMTONLY Off
	
	--V6.3
	INSERT INTO @Tbl
    SELECT
		'#*K*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AO_Suppliers_ID,-9)) + '~' +
		Replace(IsNull(t.Supplier,''),'~','') + '~' +
		Convert(varchar(20),IsNull(t.Credit_Limit,0)) + '~' +
		Replace(IsNull(t.Credit_Terms,''),'~','') + '~' +
		Convert(varchar(20),IsNull(t.Default_Settlement_Discount,0)) + '~' +
		Convert(varchar(20),(  
								IsNull(t.[Current], 0) +
								IsNull(t.[30Days], 0) +
								IsNull(t.[60Days], 0) +
								IsNull(t.[90Days], 0) +
								IsNull(t.[120Days], 0) +
								IsNull(t.[150Days], 0) +
								IsNull(t.[180+Days], 0) 
							)
				) + '~' +																					--Account_Balance				Decimal(18,4)
		Convert(varchar(20),IsNull(t.[Current],0)) + '~' +
		Convert(varchar(20),IsNull(t.[30Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[60Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[90Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[120Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[150Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[180+Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.To_Be_Paid_Total,0)) + '~' +
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120)
	FROM AO_Remittances_Temp t 
		LEFT JOIN AO_Suppliers s
			ON s.AO_Suppliers_ID = t.AO_Suppliers_ID
	WHERE (ISNULL(t.[Current], 0) +
		ISNULL(t.[30Days], 0) +
		ISNULL(t.[60Days], 0) +
		ISNULL(t.[90Days], 0) +
		ISNULL(t.[120Days], 0) +
		ISNULL(t.[150Days], 0) +
		ISNULL(t.[180+Days], 0)) <> 0
							
	--Insert Usage Records							
	INSERT INTO @Tbl
	SELECT 
		'#*U*#'  + '~' + 
		Convert(Varchar(10), Sys_AC_Status_ID) + '~' +  --ID
		[Field1] + '~' + 								--S ID		
		Replace([Field2],'~','') + '~' + 				--Server
		Replace([Field3],'~','') + '~' + 				--DB
		Replace([Field4],'~','') + '~' + 				--Computer Name
		Replace([Field5],'~','') + '~' + 				--App
		Replace([Field6],'~','') + '~' + 				--User
		Replace([Field7],'~','') + '~' + 				--Module
		Replace([Field8],'~','') + '~' + 				--Mac ADD
		Replace([Field9],'~','') + '~' + 				--Key
		Replace([Field10],'~','') + '~' + 				--App Ver And DB Ver
		Replace([Field11],'~','') + '~' + 				--SQL Ver
		Convert(Varchar(20), [Date_Captured], 120) 
	FROM
		Sys_AC_Status
	WHERE
		ISNULL(Field12,0) = 1

	--Insert Users						
	INSERT INTO @Tbl
	SELECT 
		'#*Q*#'  + '~' + 
		Convert(varchar(10),IsNull(u.AW_Users_ID,-9)) + '~' +										--AW_Users_ID			
		Replace(IsNull(u.UserName,''),'~','') + '~' +												--UserName					Varchar(20)
		Replace(IsNull(u.Password,''),'~','') + '~' +												--Password					Varchar(20)
		Replace(IsNull(u.Surname,''),'~','') + '~' +												--Surname					Varchar(40)
		Replace(IsNull(u.FirstName,''),'~','') + '~' +												--FirstName					Varchar(40)
		Replace(IsNull(u.User_Home_Tel_Number,''),'~','') + '~' +									--User_Home_Tel_Number		Varchar(16)
		Replace(IsNull(u.User_Cell_Number,''),'~','') + '~' +										--User_Cell_Number			Varchar(16)
		Replace(IsNull(u.User_Email,''),'~','') + '~' +												--User_Email				Varchar(50)
		Convert(varchar(20),IsNull(u.Activation_Date,'1900-01-01'),120) + '~' +						--Activation_Date			Datetime
		Convert(varchar(20),IsNull(u.Deactivation_Date,'1900-01-01'),120) + '~' +					--Deactivation_Date			Datetime

		Convert(varchar(5),IsNull(u.Sys_AW_Applications_ID,255)) + '~' +							--Sys_AW_Applications_ID	Int
		Convert(varchar(5),IsNull(u.IsCashier,255)) + '~' +											--IsCashier					Int
		Convert(varchar(5),IsNull(u.IsSupervisor,255)) + '~' +										--IsSupervisor				Int
		Convert(varchar(5),IsNull(u.IsDBAdmin,255)) + '~' +											--IsDBAdmin					Int
		Convert(varchar(5),IsNull(u.IsCRM,255)) + '~' +												--IsCRM						Int
		Convert(varchar(5),IsNull(u.IsController,255)) + '~' +										--IsController				Int
		Convert(varchar(5),IsNull(u.IsAccountant,255)) + '~' +										--IsAccountant				Int
		Convert(varchar(5),IsNull(u.IsDataExporter,255)) + '~' +									--IsDataExporter			Int
		Convert(varchar(5),IsNull(u.IsProcurementSupervisor,255)) + '~' +							--IsProcurementSupervisor	Int
		Convert(varchar(5),IsNull(u.Slu_AW_Active_ID,255)) + '~' +									--Slu_AW_Active_ID			Int
		Convert(varchar(5),IsNull(u.IsLevyController,255)) + '~' +									--IsLevyController			Int
		Convert(varchar(5),IsNull(u.IsRecordsManager,255)) + '~' +									--IsRecordsManager			Int
		Convert(varchar(5),IsNull(u.IsBinSuper,255)) + '~' +										--IsBinSuper				Int
		Convert(varchar(5),IsNull(u.IsTillPayout,255)) + '~' +										--IsTillPayout				Int
		Convert(varchar(10),IsNull(u.[User_ID],-9)) + '~' +											--User_ID					Int
		Replace(IsNull(u.Lup_AP_Product_Bins_ID,''),'~','') + '~' +									--Lup_AP_Product_Bins_ID	Int
		Replace(IsNull([Description],''),'~','') + '~' +											--Bin						Varchar(50)
		Convert(Varchar(20), u.Date_Captured, 120)													--Date_Captured				Datetime
	FROM
		AW_Users u
			Left Join Lup_AP_Product_Bins b
				ON u.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID

	--Insert Usage Records							
	INSERT INTO @Tbl
	SELECT 
		DISTINCT
		'#*Z*#'  + '~' + 		
		Convert(Varchar(5),@SpiralID) + '~' +
		@Company_Name + '~' +
		@Company_Trading_Name + '~' +
		@Company_Registration_Number + '~' +
		@TAX_Number + '~' +
		@Country + '~' +
		@Company_Addr1 + '~' +
		@Company_Addr2 + '~' +
		@Company_City + '~' +
		@Company_Post_Code + '~' +
		@Tel_No + '~' +
		@Fax_No + '~' +
		@E_Mail + '~' +
		@Web_Home + '~' +
		@Delivery_Addr1 + '~' +
		@Delivery_Addr2 + '~' +
		@Delivery_Addr3 + '~' +
		
		--Convert(Varchar(20), @MinTransactionDate, 120) + '~' +											--Min Transaction Date  
		--Convert(Varchar(20), @MaxTransactionDate, 120) + '~' +											--Max Transaction Date
		'' + '~' +																							--Min Transaction Date  
		'' + '~' +																							--Max Transaction Date
		Convert(varchar(10),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Convert(varchar(10),IsNull(@chkCostSalesEditorGL_0,-9)) + '~' +										--chkCostSalesEditorGL_0		Varchar(10)
		Convert(varchar(10),IsNull(@optZeroCostOverride_0,-9)) + '~' +										--optZeroCostOverride_0			Varchar(10)
		Convert(varchar(10),IsNull(@optZeroCostOverride_1,-9)) + '~' +										--optZeroCostOverride_1			Varchar(10)
		Convert(varchar(10),IsNull(@optZeroCostOverride_2,-9)) + '~' +										--optZeroCostOverride_2			Varchar(10),
		Convert(varchar(10),IsNull(@optInventoryValuation_0,-9)) + '~' +									--optInventoryValuation_0		Varchar(10),
		Convert(varchar(10),IsNull(@optInventoryValuation_1,-9)) + '~' +									--optInventoryValuation_1		Varchar(10),
		Convert(varchar(10),IsNull(@optInventoryValuation_2,-9)) + '~' +									--optInventoryValuation_2		Varchar(10),
		Convert(varchar(10),IsNull(@chkUseStockAdjGL_0,-9)) + '~' +											--chkUseStockAdjGL_0			Varchar(10),
		Convert(varchar(10),IsNull(@chkUseProductPurchasesGL_0,-9)) + '~' +									--chkUseProductPurchasesGL_0	Varchar(10),
		Convert(varchar(10),IsNull(@chkUseProductSalesGL_0,-9)) + '~' +										--chkUseProductSalesGL_0		Varchar(10)		
		@Network_Identity_Number + '~' +																	--Network_Identity_Number		Varchar(20)
		@Contact1_Email + '~' +																				--Contact1_Email				Varchar(50)
		@Contact2_Email + '~' + 																			--Contact2_Email				Varchar(50)	
		Convert(varchar(10),IsNull(@chkHistoryDataSent,-9)) + '~' +											--chkHistoryDataSent			Integer
		Replace(IsNull(@txtCSalesExclusions,''),'~','') + '~' +												--txtCSalesExclusions			Varchar(250)	
		Replace(IsNull(@txtCSalesInclusions,''),'~','') + '~' +												--txtCSalesInclusions			Varchar(250)
		Replace(IsNull(@txtCInsuranceFile,''),'~','') + '~' +												--txtCInsuranceFile				Varchar(250)
		Replace(IsNull(@AS_CBilling_Providers,''),'~','') + '~' +											--AS_CBilling_Providers			Varchar(50)
		Convert(varchar(10),IsNull(@chkSendConnectivitySales,-9)) + '~' +									--chkSendConnectivitySales		Integer
		Convert(varchar(10),IsNull(@chkSendCBillingSales,-9)) + '~' +										--chkSendCBillingSales			Integer
		Convert(varchar(10),IsNull(@chkSendCInsuranceData,-9)) + '~' +										--chkSendCInsuranceData			Integer
		Convert(varchar(10),IsNull(@chkSendCRewardsData,-9)) + '~' +										--chkSendCRewardsData			Integer
		Replace(IsNull(@txtNextCBFileNo,''),'~','') + '~' +													--txtNextCBFileNo				Varchar(50)
		Replace(IsNull(@txtClickatellSMS,''),'~','')														--txtClickatellSMS				Varchar(50)
	FROM
		Sys_AC_Status
	WHERE
		ISNULL(Field12,0) = 1

	IF @chkHistoryDataSent = 0
	BEGIN
		UPDATE Sys_AW_Options
		SET Control_Index = 1
		WHERE Control_Name = 'chkHistoryDataSent' 
	END

	SELECT Rec FROM @Tbl ORDER BY UniqueID

SET NOCOUNT OFF
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Insert
--Purpose       :INSERT Sys_AC_Status
--Parameters    :
--Date          :2014-04-29
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Sys_AC_Status_Insert]
	(
		@Field1 [varchar](200),	--S ID		
		@Field2 [varchar](200),	--Server
		@Field3 [varchar](200),	--DB
		@Field4 [varchar](200),	--Computer Name
		@Field5 [varchar](200),	--App
		@Field6 [varchar](200),	--User
		@Field7 [varchar](200),	--Module
		@Field8 [varchar](200),	--Mac ADD
		@Field9 [varchar](200),	--Key
		@Field10 [varchar](200), --APP, DB Ver
		@Field11 [varchar](200)  --SQL Ver
	)
AS

SET NOCOUNT ON    

    INSERT Sys_AC_Status
        (
            Field1,
            Field2,
            Field3,
            Field4,
            Field5,
            Field6,
            Field7,
            Field8,
            Field9,
            Field10,
            Field11,
            Date_Captured
        )
    VALUES
        (
            @Field1,
            @Field2,
            @Field3,
            @Field4,
            @Field5,
            @Field6,
            @Field7,
            @Field8,
            @Field9,
            @Field10,
            @Field11,
            GETDATE()
        )

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Mark
--Purpose       :Update Sys_AC_Status Status
--Parameters    :
--Date          :2014-04-29
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Sys_AC_Status_Mark]
	(
		@From_Status	Int,
		@ToStatus		Int
	)
AS

SET NOCOUNT ON    

    UPDATE Sys_AC_Status
    SET Field12 = @ToStatus
    Where Field12 = @From_Status

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Add_BO_To_SO]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Add_BO_To_SO
--Purpose       :Creates or updates a SO with BO Qty
--Date          :2017/09/10
--Authors       :RL
--V6.4	RL	2018-05-14	:Fixed Back Order Issues
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
    (
		@DocumentID				Int = NULL,
		@ProductID				Int = NULL,
		@Back_Order				Decimal(9,3) = 0,

		@Qty					Decimal(9,3) = 0,
		@Cost					Money = 0,
		@Price					Money = 0,
		@OriginalPrice			Money = 0,
		@Discount				Money = 0,
		@Tax					Money = 0,
		@TotalAmount			Money = 0,
		@Commission				Money = 0,
		@PromotionProductID		Int = 0,
		@PromotionPrice			Money = 0,
		@JobRefID				Int = 0,
        @SerialNo				Varchar(13) = '',
        @Make					Varchar(6) = '',
        @Customer				Varchar(20) = '',
		@TDHeader				Varchar(256) = '',
		@TDDetail				Varchar(256) = '',
		@ProductBinsID			Int,
		@TransactionTypeID		Int,
		@OldTransactionTypeID	Int,		
		@UserID					Int = NULL,
		@CompanyID				Int =  NULL
    )
AS

SET NOCOUNT ON

--Insert Into Temp_Test (Field1) Values ('In sp_AS_POS_Add_BO_To_SO')

	Declare @SO_TransID						Int,
			@CustomerID						Int,
			@Customer_Reference				Varchar(15),
			@NewTransID						Int,
			@Transaction_Number				Varchar(19),

			@NewDiscount					Decimal(18,2),
			@NewTax							Decimal(18,2),
			@NewTotalAmount					Decimal(18,2),
			@TaxRate						Decimal(18,2),
			@chkSOAutoAddPO					Varchar(5),
			@AO_Suppliers_ID				Int,
			@RemoteID						Int,
			@Customer_Name					Varchar(100),
			@PONotes						Varchar(50),
			@AO_Order_Candidates_ID			Int,

			@H_Total_Cost					Decimal(18,2),
			@H_Total_Discount_Amount		Decimal(18,2),
			@H_Amount						Decimal(18,2),
			@H_Total_Tax_Amount				Decimal(18,2),
			@H_Total_Amount					Decimal(18,2),
			@DocumentDetailsID				Int,
			--@DateCaptured					Datetime,
			--@Sys_AW_Transaction_Types_ID	Int,
			@Transaction_Type				Varchar(30),
			@OrigTransaction_Number			Varchar(19),
			@chkSOAutoAddPO_DocType			Varchar(5),
			@Found							Int,
			@SO_CommentID					Int,
			@SO_Comment						Varchar(500),
			@OrigDocCommentID				Int,
			@OrigDocComment					Varchar(500),
			@SO_OrigTransaction_Number		Varchar(19)

	SET @DocumentDetailsID = 0
	SET @SO_TransID = 0
	SET @CustomerID = 0

	IF @TransactionTypeID <> 16
	BEGIN
		SET @SO_TransID = 0

		SELECT	@CustomerID = AC_Customers_ID,
				@Customer_Reference = ISNULL(Customer_Reference,''),
				@OrigTransaction_Number = Transaction_Number
		FROM AS_Transactions
		WHERE AS_Transactions_ID = @DocumentID

		SELECT	@SO_TransID = AS_Transactions_ID,
				@SO_CommentID = ISNULL(AW_Comments_ID,0),
				@SO_OrigTransaction_Number = Transaction_Number
		FROM AS_Transactions
		WHERE AC_Customers_ID = @CustomerID AND
			  ISNULL(Customer_Reference,'') = ISNULL(@Customer_Reference,'') AND
			  AW_User_Companies_ID = @CompanyID AND
			  Slu_AW_Active_ID = 1 AND
			  Sys_AW_Transaction_Types_ID = 16 AND 
			  ISNULL(@Customer_Reference,'') <> ''

		IF @SO_TransID <> 0 --Sales Order already exists
		BEGIN

			SELECT @NewTransID = @SO_TransID

			--Update original document with a reference to the Sales Order just created
			SET @OrigDocCommentID = 0
			SET @OrigDocComment = ''

			SELECT	@OrigDocCommentID = ISNULL(c.AW_Comments_ID,0),
					@OrigDocComment = ISNULL(c.Comment,'')
			FROM AS_Transactions t
				INNER JOIN AW_Comments c
					ON t.AW_Comments_ID = c.AW_Comments_ID
			WHERE AS_Transactions_ID = @DocumentID

			IF @OrigDocCommentID = 0
			BEGIN
				SET @OrigDocCommentID = NULL
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @SO_OrigTransaction_Number + ' for details'

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

				UPDATE AS_Transactions
				SET AW_Comments_ID = @OrigDocCommentID
				WHERE AS_Transactions_ID = @DocumentID
			END
			ELSE
			BEGIN
				IF @OrigDocComment NOT Like '%Item was placed on Sales Order for Back Order. Please refer to Sales Order No %'
				BEGIN
					SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @SO_OrigTransaction_Number + ' for details' + '
	' + @OrigDocComment

					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
				END
			END

			--Insert Or update Sales Order transaction comments
			SET @SO_Comment = ''
			IF ISNULL(@SO_CommentID ,0) <> 0
			BEGIN
				SELECT @SO_Comment = LTRIM(RTRIM(ISNULL(Comment,'')))
				FROM AW_Comments
				WHERE AW_Comments_ID = @SO_CommentID
			END

			SELECT @Transaction_Type = [Description]
			FROM Sys_AW_Transaction_Types
			WHERE Sys_AW_Transaction_Types_ID = @TransactionTypeID

			IF @SO_Comment <> '' 
			BEGIN
				IF ( (LEFT(@SO_Comment,5) = 'Quote') OR (LEFT(@SO_Comment,8) = 'Job Card') OR (LEFT(@SO_Comment,11) = 'Tax Invoice') OR (LEFT(@SO_Comment,9) = 'Pro Forma') OR (LEFT(@SO_Comment,16) = 'Consignment Note') )
				BEGIN
					SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + ', ' + @SO_Comment))
					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
				END
				ELSE
				BEGIN
					SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + '
' + @SO_Comment))
					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
				END
			END
			ELSE
			BEGIN
				SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number))
				SET @SO_CommentID = NULL
				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
			END
		END

		IF @SO_TransID = 0
		BEGIN

			If @Transaction_Number = '' OR @Transaction_Number Is Null
				EXEC sp_AW_Get_Next_Transaction_Number 16, 1, @Transaction_Number Output

			SET @SO_Comment = ''
			IF ISNULL(@SO_CommentID ,0) <> 0
			BEGIN
				SELECT @SO_Comment = ISNULL(Comment,'')
				FROM AW_Comments
				WHERE AW_Comments_ID = @SO_CommentID
			END

			SELECT @Transaction_Type = [Description]
			FROM Sys_AW_Transaction_Types
			WHERE Sys_AW_Transaction_Types_ID = @TransactionTypeID

			SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + '
	' + @SO_Comment))
			SET @SO_CommentID = NULL
			EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment


			INSERT INTO AS_Transactions
			(
				AC_Customers_ID, 
				AB_Accounts_ID, 
				Sys_AW_Transaction_Types_ID, 
				Transaction_Date, 
				Transaction_Number, 
				Total_Cost, 
				Amount, 
				Total_Tax_Amount, 
				Total_Discount_Amount, 
				Total_Amount, 
				Payment_Amount, 
				[Expiry_Date], 
				Version_Number, 
				Customer_Reference, 
				Comment, 
				AW_Comments_ID, 
				Lup_AS_Marketing_Indicators_ID, 
				Lup_AW_Stores_ID, 
				Lup_AW_Workstations_ID, 
				Lup_AS_Tills_ID, 
				Lup_AS_Cashiers_ID, 
				Lup_AS_Reps_ID, 
				Slu_AW_Currencies_ID, 
				Old_Sys_AW_Transaction_Types_ID, 
				Cancelled_User_ID, 
				Cancelled_DateTime, 
				Cashed_Up, 
				Day_End, 
				Transmitted, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			SELECT 
				AC_Customers_ID, 
				AB_Accounts_ID, 
				16, 
				Transaction_Date, 
				@Transaction_Number, 
				0,--Total_Cost, 
				0,--Amount, 
				0,--Total_Tax_Amount, 
				0,--Total_Discount_Amount, 
				0,--Total_Amount, 
				0,--Payment_Amount, 
				[Expiry_Date], 
				Version_Number, 
				ISNULL(Customer_Reference,''),
				ISNULL(Comment,''), 
				@SO_CommentID, 
				Lup_AS_Marketing_Indicators_ID, 
				Lup_AW_Stores_ID, 
				Lup_AW_Workstations_ID, 
				Lup_AS_Tills_ID, 
				Lup_AS_Cashiers_ID, 
				Lup_AS_Reps_ID, 
				Slu_AW_Currencies_ID, 
				Old_Sys_AW_Transaction_Types_ID, 
				Cancelled_User_ID, 
				Cancelled_DateTime, 
				Cashed_Up, 
				Day_End, 
				Transmitted, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @DocumentID

			SET @NewTransID = (SELECT TOP 1 MAX(AS_Transactions_ID) FROM AS_Transactions WHERE Sys_AW_Transaction_Types_ID = 16);

			--Update original document with a reference to the Sales Order just created
			SET @OrigDocCommentID = 0
			SET @OrigDocComment = ''

			SELECT	@OrigDocCommentID = c.AW_Comments_ID,
					@OrigDocComment = c.Comment
			FROM AS_Transactions t
				INNER JOIN AW_Comments c
					ON t.AW_Comments_ID = c.AW_Comments_ID
			WHERE AS_Transactions_ID = @DocumentID

			IF @OrigDocCommentID = 0
			BEGIN
				SET @OrigDocCommentID = NULL
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @Transaction_Number + ' for details'

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

				UPDATE AS_Transactions
				SET AW_Comments_ID = @OrigDocCommentID
				WHERE AS_Transactions_ID = @DocumentID
			END
			ELSE
			BEGIN
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @Transaction_Number + ' for details' + '
' + @OrigDocComment

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
			END

		END

	END --@TransactionTypeID <> 16

		IF @Qty = 0
		BEGIN

			--V6.4
			SELECT	@CustomerID = AC_Customers_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @DocumentID

			SELECT @TaxRate = Tax_Rate
			FROM AC_Customers c
				INNER JOIN Sys_AW_Tax_Codes t
					ON c.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
			WHERE AC_Customers_ID = @CustomerID

			SELECT @NewDiscount = 0
			SET @NewTax = 0

--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@CustomerID) + ' @CustomerID')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@Back_Order) + ' @Back_Order')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@Price) + ' @Price')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@TaxRate) + ' @TaxRate')

				SELECT @NewTax =  ROUND(( ROUND(@Back_Order * @Price, 2) - @NewDiscount) * (@TaxRate / 100), 2)
				SELECT @NewTotalAmount = ROUND((ROUND(@Back_Order * @Price, 2) - @NewDiscount) + @NewTax, 2)
				
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewTax) + ' @NewTax')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewTotalAmount) + ' @NewTotalAmount')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewDiscount) + ' @NewDiscount')

		END
		ELSE
		BEGIN

			SELECT @NewDiscount = Round( ((@Discount / @Qty) * @Back_Order),2)

			SET @NewTax = 0

			IF @Tax <> 0
			BEGIN

				SELECT @TaxRate = ROUND( (@Tax / (@TotalAmount - @Tax) * 100) ,0)

				SELECT @NewTax =  ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) * (@TaxRate / 100) ,2)

				SELECT @NewTotalAmount = ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) + @NewTax ,2)

			END
		END

		--Update Sales Order detail record with new quantity
		SELECT @DocumentDetailsID = AS_Transaction_Details_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @SO_TransID AND
			    AP_Products_ID = @ProductID AND
			    --Unit_Cost = @Cost AND
			    Unit_Price = @Price AND
			    Original_Price = @OriginalPrice AND
				Lup_AP_Product_Bins_ID = @ProductBinsID
		
		IF ISNULL(@DocumentDetailsID,0) <> 0
		BEGIN
			Update AS_Transaction_Details
			SET Quantity = Quantity,
				Back_Order = Back_Order + @Back_Order,
				Unit_Cost = @Cost,
				Unit_Price = @Price,
				Original_Price = @OriginalPrice,
				Discount_Amount = Discount_Amount + @Discount,
				Tax_Amount = Tax_Amount + @Tax,
				Extended_Amount = Extended_Amount + @TotalAmount
			WHERE AS_Transaction_Details_ID = @DocumentDetailsID
		END

		--Insert detail record into Sales order
		IF @DocumentDetailsID = 0
		BEGIN
		
			--V6.4
			--SELECT @NewTransID = @SO_TransID		
			--V6.4
			--IF ISNULL(@NewTransID,0) = 0
				--SELECT @NewTransID = @DocumentID
			
			INSERT AS_Transaction_Details
				(
					AS_Transactions_ID,
					AP_Products_ID,
					Quantity,
					Back_Order,

					Unit_Cost,
					Unit_Price,
					Original_Price,
					Discount_Amount,
					Tax_Amount,
					Extended_Amount,
					Commission_Amount,

					AP_Promotion_Products_ID,
					AS_Job_References_ID,
					Serial_No,
					Make,
					Customer,
					User_ID,
					AW_User_Companies_ID,
					TDHeader,
					TDDetail,
					Lup_AP_Product_Bins_ID
				)
			VALUES
				(
					@NewTransID,
					@ProductID,
					0,	--Qty will always be zero because it is created from another document -- @Qty
					@Back_Order,
					
					ISNULL(@Cost,0),
					ISNULL(@Price,0),
					ISNULL(@OriginalPrice,0),
					ISNULL(@NewDiscount,0),
					ISNULL(@NewTax,0),
					ISNULL(@NewTotalAmount,0),
					NULL,

					@PromotionProductID,
					@JobRefID,
					@SerialNo,
					@Make,
					@Customer,
					@UserID,
					@CompanyID,
					ISNULL(@TDHeader,''),
					ISNULL(@TDDetail,''),
					@ProductBinsID
				)

			SELECT @DocumentDetailsID = Scope_Identity()
		END

		SELECT @H_Total_Cost = SUM((Quantity + @Back_Order) * Unit_Cost),
				@H_Total_Discount_Amount = SUM(Discount_Amount),
				@H_Amount = SUM(Extended_Amount - Tax_Amount),
				@H_Total_Tax_Amount = SUM(Tax_Amount),
				@H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @NewTransID
		
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
			Total_Discount_Amount = @H_Total_Discount_Amount,
			Amount = @H_Amount,
			Total_Tax_Amount = @H_Total_Tax_Amount,
			Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @NewTransID
	


IF @OldTransactionTypeID <> -88
BEGIN		
	SET @chkSOAutoAddPO = '0'

	SELECT @chkSOAutoAddPO = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOAutoAddPO'
		--Add to purchase orders
	IF @chkSOAutoAddPO = '1'
	BEGIN
	
		SET @chkSOAutoAddPO_DocType = '0'

		IF @TransactionTypeID = 1
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOQuote'
		END

		IF @TransactionTypeID = 2
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOJobcard'
		END

		IF @TransactionTypeID = 3
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOInvoice'
		END

		IF @TransactionTypeID = 13
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOProForma'
		END

		IF @TransactionTypeID = 16
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOSalesOrder'
		END

		IF @TransactionTypeID = 33
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOConsignment'
		END

		IF @chkSOAutoAddPO_DocType = '1'
		BEGIN

			SET @AO_Suppliers_ID = 1
				
			SELECT TOP 1 @AO_Suppliers_ID = s.AO_Suppliers_ID
			FROM AP_Products_Suppliers ps
				INNER JOIN AO_Suppliers s
					ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
			WHERE ps.AP_Products_ID = @ProductID AND
				  ps.Slu_AW_Active_ID = 1 AND
				  s.Slu_AW_Active_ID = 1 And
				  GETDATE() Between ps.[Start_Date] And '2999-01-01'
				
			SET @RemoteID = 0
				
			SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
			FROM AW_Remote_Access
			WHERE AW_User_Companies_ID = @CompanyID AND
				  Default_Connection = 1

			IF @CustomerID = 0
			BEGIN
				SELECT	@CustomerID = AC_Customers_ID
				FROM AS_Transactions
				WHERE AS_Transactions_ID = @DocumentID
			END

			SELECT @Customer_Name = Surname
			FROM AC_Customers
			WHERE AC_Customers_ID = @CustomerID
		
   			SELECT @PONotes = Notes
    		FROM AO_Order_Candidates
    		WHERE AP_Products_ID = @ProductID AND
    			  AO_Suppliers_ID = @AO_Suppliers_ID AND
    			  AW_User_Companies_ID = @CompanyID

			SELECT @PONotes = ISNULL(@PONotes,'')

			IF @PONotes = ''
			BEGIN
				SET @PONotes = LEFT('Back Order for ' + @Customer_Name,50)
			END
			ELSE
			BEGIN
				
				SELECT @Found = 0
				SELECT @Found = CHARINDEX(@Customer_Name,@PONotes)

				IF @Found = 0
				BEGIN
					SET @PONotes = LEFT(@PONotes + LEFT(' / ' + @Customer_Name,50),50)
				END				
				
				SET @PONotes = LEFT(@PONotes + LEFT(' / ' + @Customer_Name,50),50)

			END
								
			EXEC @AO_Order_Candidates_ID = sp_AO_Add_Product_To_Order_Candidates_RET @ProductID, @AO_Suppliers_ID, @Back_Order, @PONotes, @UserID ,@UserID , @CompanyID, @RemoteID
		END
	END
END
GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Comment_Insert_Update
--Purpose       :Creates or updates Document's transaction comment
--Date          :2018/09/27
--Authors       :EB
--V6.4	EB	2018-09-27	:Fixed Back Order Issues
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]
	(
		@CommentID int OUTPUT,	
		@Comment varchar(500)
	)

AS

	SET NOCOUNT ON

	IF (@CommentID IS NULL AND @Comment <> '')
	BEGIN
	
		INSERT AW_Comments
        (
            Sys_AT_Actor_Types_ID,
            Comment
        ) 
        VALUES
        (
            -7,
            @Comment
        )

		SELECT @CommentID = Scope_Identity()
		
	END
	ELSE IF (EXISTS(SELECT TOP 1 1 FROM AW_Comments WHERE AW_Comments_ID = @CommentID AND Comment <> @Comment))
	BEGIN
	
		INSERT AW_Comments
        (
            Sys_AT_Actor_Types_ID,
            Comment
        ) 
        VALUES
        (
            -7,
            @Comment
        )

		SELECT @CommentID = Scope_Identity()
		
	END
	ELSE
	BEGIN
		UPDATE AW_Comments
        SET Sys_AT_Actor_Types_ID = -7,
			Comment = @Comment
		WHERE AW_Comments_ID = @CommentID
	END
	
	SET NOCOUNT OFF
GO