SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID('dbo.usp_GetLowMachineInventory') IS NOT NULL
   DROP PROCEDURE dbo.usp_GetLowMachineInventory
GO
-- ======================================================================
-- Author:		Shyang Tan
-- Create date: 4/5/2016
-- Description:	
-- ======================================================================
CREATE PROCEDURE usp_GetLowMachineInventory 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT		m.[Id] as 'MachinesId',
				p.[PartNum] as 'ProductsPartNum',
				p.[Description] as 'ProductsDescription',
				mb.[Bin] as 'MachineBinsBin', mb.[MinQty] as 'MachineBinsMinQty', 
				mbt.[MachineBinsMinQtyTotal],
				mb.[Capacity] as 'MachineBinsMaxQty',
				mb.[CurrentQty] as 'MachineBinsCurrentQty',
				mbt.[MachineBinsCurrentQtyTotal],
				p.[PackageQty] as 'ProductsPackageQty',
				p.[OrderQty] as 'ProductsOrderQty',
			    p.[Price] as 'ProductsPrice',
			    mbt.[MachineNo],
			    mbt.[ProductNo]

	FROM		MachineBins mb
					JOIN Machines m ON m.[MachineNo] = mb.[MachineNo]
					JOIN Products p ON p.[ProductNo] = mb.[ProductNo]
					LEFT JOIN (
						SELECT mbt.[MachineNo],
									mbt.[ProductNo],
									sum(mbt.[MinQty]) as 'MachineBinsMinQtyTotal', 
									sum(mbt.[CurrentQty]) as 'MachineBinsCurrentQtyTotal'
						FROM		MachineBins mbt
						WHERE		mbt.[ProductNo] <> 1
						Group by mbt.[MachineNo],mbt.[ProductNo]  
						) mbt ON mbt.[MachineNo] = mb.[MachineNo] AND mbt.[ProductNo] = mb.[ProductNo]
	WHERE		m.[Active] = 1 AND
				p.[ProductNo] <> 1 AND
				mbt.[MachineBinsCurrentQtyTotal] < mbt.[MachineBinsMinQtyTotal]
	ORDER BY	m.[Id], p.[PartNum], mb.[Bin]


END
GO
