﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[fds__fn_unpaidInvoices]
(	
	
)
RETURNS TABLE 
AS
RETURN 
(
	WITH inv as (
	SELECT [Id]
				,[Invoiceid]
				,[DateFinalized]
				,[InvoiceBalance]
				,[DocumentName]
				--,[file]
				,[InvoiceTitle]
				,[customerid]
				,[dateSent]
				,[fds] = CAST(IIF(iv.isexternal = 0,1,0) as bit) 
			FROM [dbo].[fds__invoices] as iv
				WHERE [isfinal] = 1 
					and CAST(CASE WHEN ISNULL(iv.[IsCanceled],0) = 1 THEN 1 ELSE ISNULL([IsPayed],0) END  as bit) = 0
					and InvoiceBalance > 0
					AND NOT exists (SELECT 0 FROM [dbo].[fds__invoice_details] as d where d.[StornoTo_InvId] = iv.[id])
	)
	SELECT *  /*[Rechnung] = [invoiceId], [Name] = [InvoiceTitle] + CHAR(10) + '  (' + (SELECT TOP(1) c.[name] FROM [dbo].[mfr__companies] as c WHERE inv.[customerid] = c.[id]) + ')', [Betrag (net)] = FORMAT([invoicebalance], '#0.00€', 'de'), [Datum] = FORMAT([DateFinalized], 'dd.MM.yy' , 'de'), [Zahlungen] = FORMAT([dbo].[fds__fn_InvoicePaymentAmount]([id]), '#0.00€', 'de'), [order] = ROW_NUMBER() OVER (ORDER BY [DateFinalized], [DateSent]) */
	FROM inv
)