﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__getInvPayments]
	@InvID varchar(20)
	, @authuser varchar(100)
AS
BEGIN
	SET NOCOUNT ON;

	 IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 1 OR [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1
		THROW 60000, N'not authorized', 1;  
	
	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__getInvPayments' ,@authuser , '');

	DECLARE @InvoiceId varchar(50) = (SELECT TOP(1) [invoiceid] FROM [fds__invoices] WHERE [id] = @InvID);

    WITH bs1 as (
		SELECT bs.[taID], [invid] = value, [manu] = cast(1 as bit)
		FROM [dbo].[fds__bankingtransactions_settings] as bs
			CROSS APPLY STRING_SPLIT(bs.assigned_invoice_id, ',')
		WHERE bs.assigned_invoice_id is not null AND [value] = @InvID
		UNION
		SELECT bs.[taID], [invid] = value, [manu] = cast(0 as bit)  
		FROM [dbo].[fds__bankingtransactions_settings] as bs
			CROSS APPLY STRING_SPLIT(bs.auto_invoice_id, ',')
		WHERE bs.auto_invoice_id is not null AND [value] = @InvID
	), bs as (
		SELECT [taID], [invid], manu = CAST(MAX(CAST([manu] as int))  as bit)
		from bs1
		GROUP BY [taID], [invid]
	)
	SELECT 
			bs.[taID]
			, [account] = bt.[AccountIdentification]
			, [name]	= bt.[NameOfPayer]
			, [text]	= bt.[SepaRemittanceInformation]
			, [InvID]	= @InvID
			, [InvoiceID]	= @InvoiceId
			, [amount]	= FORMAT(ISNULL(bt.[amount], 0.0), '0.00€', 'de')
			, [date]	= FORMAT([ValueDate], 'dd.MM.yyyy', 'de-de')
			, [manual]	= IIF(bs.manu = 1, 'manuell','')
			, [order]	= ROW_NUMBER() OVER (ORDER BY [ValueDate] ASC, [AccountIdentification] ASC)
		FROM [dbo].[fds__bankingtransactions] as bt 
			JOIN bs ON bt.[taID] = bs.[taID];
END