﻿
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[backup__fds__getBankingtransfers]
	@mode varchar(1) = 'm'
	, @authuser varchar(100)
AS
BEGIN
	SET NOCOUNT ON;
	IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1
		THROW 60000, N'not authorized', 1;  
	
	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__getBankingtransfers_questionable' ,@authuser , '');
	   
	DECLARE @startdate date, @enddate date, @today date = GETDATE();
	DECLARE @true bit = 1, @false bit = 0;
	SET @mode = LOWER(@mode);

	DECLARE @invidlist [dbo].[fds__tt__idlist_vchar];

	--output admin 
	SELECT [startdate] = @startdate, [enddate] = @enddate, [mode] = @mode, [title] = 'Zahlungen  (neueste zuerst)'
		,[note] = 'Letzes Buchungsdatum: ' + FORMAT((SELECT MAX([valuedate]) from [fds__bankingtransactions]), 'dd.MM.yy');


    select	
		ic.[taID]
		--inv.InvoiceId,
		--[IsPayed], 
		, ic.fds
		, InvoiceId = ISNULL(fi.[invoiceid], mi.[invoiceid])
		, [ValueDate]		= FORMAT(ic.[ValueDate], 'dd.MM.yy') 
		, [InvoiceBalance]	= FORMAT((ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0)), '0.00€', 'de')
		, [Amount]			= FORMAT(ic.[amount], '0.00€', 'de')
		, [Skonto]			= CAST(CASE WHEN ic.[amount] between (0.965 * (ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0))) and (0.975 * (ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0))) THEN 1 ELSE 0 END as bit)
		, [Deviation]		= FORMAT(CASE WHEN ISNULL((ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0)),0) > 9 THEN ic.[amount] / (ISNULL(fi.[InvoiceBalance],0.0) + ISNULL(mi.[InvoiceBalance],0.0)) ELSE NULL END , '0.00%')
		--, ic.*
		,ic.AccountNumberOfPayer
		,ic.NameOfPayer
		,ic.SepaRemittanceInformation
		,ic.EndToEndReference
		, [order] = ROW_NUMBER() OVER (ORDER BY [valuedate] DESC)
	FROM 
			[dbo].[fds__fn_bankingtransactions](null, null, @startdate, @enddate, @invidlist) as ic
			LEFT JOIN [dbo].[fds__invoices] as fi on ic.[fds] = 1 and ic.[invid] = fi.id
			LEFT JOIN [dbo].[mfr__invoices] as mi on ic.[fds] = 0 and ic.[invid] = mi.id
END