﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__setBankingtransaction_autoAssigns]
AS
BEGIN
	SET NOCOUNT ON;

	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__setBankingtransaction_autoAssigns' ,'', '');


	DECLARE @OUT TABLE([taID] varchar(10), [auto_invoice_id] varchar(255));


    with
	icr as (
		SELECT * FROM [dbo].[fds__getInvoiceCredits] (null, null)
	), ic as (
		SELECT 
			icr.[taID]
			, icr.[InvoiceId]
			, [InvID] = CAST(i.[Id] as varchar(15))
			, icr.amount
			, [auto] = CAST(1 as bit)
		FROM icr
			JOIN [dbo].[fds__invoices] as i on icr.[InvoiceId] = i.[InvoiceId] and i.[InvoiceId] is not null and i.[IsFinal] = 1
		WHERE i.[IsCanceled] = 0
			
	), ic2 as (
		SELECT [taID]	= ic.[taID]
			, [amount]			= SUM(ISNULL(ic.[amount], 0.0))
			, [InvID_csv]		= STRING_AGG(ic.[InvID], ',')
		from ic
		WHERE ic.[InvID] is not null
		GROUP BY ic.[taID]
	)
	--select * from ic2
	MERGE [dbo].[fds__bankingtransactions_settings] as TARGET 
		USING ic2 as SOURCE ON TARGET.[taID] = SOURCE.[taID]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT
			   ([taID]
			   ,[auto_invoice_id])
		 VALUES
			   (SOURCE.[taID]
			   ,SOURCE.[InvID_csv])
	WHEN MATCHED 
		AND ISNULL(TARGET.[assigned_invoice_id],'') = ''
		THEN
		UPDATE SET [auto_invoice_id] = [dbo].[ott_merge_csv](TARGET.[auto_invoice_id],SOURCE.[InvID_csv])
	OUTPUT inserted.[taID], inserted.[auto_invoice_id]
		INTO @out;


	WITH SOURCE as (
		SELECT [taID], [invoice_id] = CAST([value] as varchar(15)), [auto] = CAST( 1 as bit)
			FROM @OUT
				CROSS APPLY string_split(ISNULL([auto_invoice_id], ''), ',') as ai
		WHERE ai.[value] <> ''
	)
	MERGE [dbo].[fds__bankingtransactions_assigns] AS TARGET
		USING SOURCE ON TARGET.[taID] = SOURCE.[taID] AND TARGET.[invoice_id] = SOURCE.[invoice_id]
	WHEN NOT MATCHED BY TARGET THEN
		INSERT ([taID], [invoice_id], [auto]) VALUES (SOURCE.[taID], SOURCE.[invoice_id], SOURCE.[auto])
	WHEN NOT MATCHED BY SOURCE AND EXISTS (SELECT NULL FROM @out as o WHERE o.[taID] = TARGET.[taID]) THEN
		DELETE;


END