﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[fds__fn_isInvoiceCancelled]
(
	@InvId varchar(20)
)
RETURNS bit
AS
BEGIN
	DECLARE @res bit;
	
	--SET @res = CASE WHEN EXISTS (SELECT 0 FROM [dbo].[fds__invoices] as i2 JOIN [dbo].[fds__invoice_details] as id2 ON i2.[id] = id2.[InvId] where id2.[StornoTo_InvId] = @invId AND i2.[IsFinal] = 1 ) THEN 1 ELSE 0 END;

	with storno as(
		SELECT [amount] = SUM(ISNULL(ORIG.[invoicebalance],0.0)), [stornoamount] = SUM(ISNULL(i2.[invoicebalance],0.0) * -1.0)
			FROM [dbo].[fds__invoices] as ORIG
				LEFT JOIN [dbo].[fds__invoice_details] as id2 ON id2.StornoTo_InvId = ORIG.[id] and id2.StornoTo_InvId = @invId
				LEFT JOIN [dbo].[fds__invoices] as i2 on i2.[id] = id2.[InvId] AND i2.[IsFinal] = 1
			WHERE ORIG.[Id] = @invId
	)
	SELECT @res = CASE WHEN [amount] = [stornoamount] THEN 1 ELSE 0 END from storno;

	RETURN cast(ISNULL(@res,0) as bit);

END