IF EXISTS (SELECT *	FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[qryMMSGetCustomerIdForOutsideSale]')
			AND type IN (N'P',N'PC'))
	DROP PROCEDURE qryMMSGetCustomerIdForOutsideSale
GO

CREATE PROCEDURE qryMMSGetCustomerIdForOutsideSale 
    @EntityID BIGINT
	,@TransactionSummaryId BIGINT
	,@CustomerId BIGINT OUTPUT
AS
DECLARE @TotalSalesAmount FLOAT
DECLARE @TotalAmountPaid FLOAT

SELECT @TotalSalesAmount = Sales_Incl_GST_INCL
FROM tbTransactionSummary WITH (NOLOCK)
WHERE TransactionSummaryID = @TransactionSummaryId

SELECT @TotalAmountPaid = ISNULL(SUM(Amount),0)
FROM tbTransactionPayment tp WITH (NOLOCK)
JOIN tbPaymentType pt WITH (NOLOCK) ON tp.PaymentTypeID = pt.PaymentTypeID
WHERE TransactionSummaryID = @TransactionSummaryId
	AND pt.Description <> 'ToBeCollected'

IF @TotalSalesAmount <> @TotalAmountPaid
BEGIN
	SET @customerId = 0
END
ELSE
BEGIN
SELECT @CustomerId = customerid
	FROM CustomerInformation ci WITH (NOLOCK)
	WHERE entityid = @EntityID
	    AND customername = 'Systematic Cust - Outside Sls'	
END
