﻿

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__setBankingtransaction_assignToIvoice]
	@taID varchar(10)
	,@invoice_id varchar(10)
	,@authuser varchar(25)
AS
BEGIN
	SET NOCOUNT ON;

	IF [dbo].[fis_getModuleAuth]('fds_bam', @authuser) < 1
		THROW 60000, N'not authorized', 1;  
	IF NOT EXISTS (SELECT 0 FROM [dbo].[fds__invoices] as i_ WHERE i_.[id] = @invoice_id)
		THROW 60000, N'Invoice not found', 1;  
	
	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__setBankingtransaction_assignToIvoice' ,@authuser , ('banking_uid: ' + @taID + ', invoice_id: ' + @invoice_id));
	

	DECLARE @now datetime = GETUTCDATE();
	DECLARE @today date = @now;

	DECLARE @OUT TABLE([uid] varchar(10), [assigned_invoice_id] varchar(25));
	
	MERGE [dbo].[fds__bankingtransactions_settings] as TARGET
		USING (SELECT TOP(1) * FROM [dbo].[fds__bankingtransactions] as b WHERE b.[taID] = @taID) as SOURCE ON TARGET.[taID] = SOURCE.[taID]
	WHEN MATCHED THEN
		UPDATE SET [assigned_invoice_id] = [dbo].[ott_merge_csv]([assigned_invoice_id], @invoice_id), [auto_invoice_id] = NULL
	WHEN NOT MATCHED BY TARGET THEN
		INSERT ([taID],[assigned_invoice_id]) VALUES (SOURCE.[taID], @invoice_id)
	OUTPUT inserted.[taID], inserted.[assigned_invoice_id]
		INTO @out;
	;



	--Process transactions and assignments

	EXECUTE [dbo].[fds__setBankingtransaction_autoAssigns];
	EXECUTE [dbo].[fds__setInvoicePaymentStatus_auto];



	--output to confirm as boolean
	SELECT CAST( (CASE WHEN ISNULL((SELECT TOP(1) [assigned_invoice_id] FROM @out), '') <> '' THEN 1 ELSE 0 END) as bit);

END