39 lines
1.8 KiB
Transact-SQL
39 lines
1.8 KiB
Transact-SQL
-- =============================================
|
|
-- Description: Finalized, not-paid, not-canceled, not-storno'd invoices with a balance > 0.
|
|
-- [PaymentAmount] / [OpenAmount] come from one set-based pass over the banking
|
|
-- transactions ([fds__fn_InvoicePaymentAmounts]) — use them instead of calling the
|
|
-- scalar [fds__fn_InvoicePaymentAmount](Id) per row, which re-runs the whole
|
|
-- banking TVF for every invoice and timed out the dashboard widgets.
|
|
-- =============================================
|
|
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 inv.*
|
|
,[PaymentAmount] = ISNULL(pay.[Amount], 0.0)
|
|
,[OpenAmount] = CAST(inv.[InvoiceBalance] - ISNULL(pay.[Amount], 0.0) as numeric(10,2))
|
|
/*[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
|
|
LEFT JOIN [dbo].[fds__fn_InvoicePaymentAmounts]() as pay ON pay.[InvId] = inv.[Id]
|
|
)
|