﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[backup__fds__setInvoicePayed]
	@Id varchar(15),
	@authuser varchar(25)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @now datetime = GETUTCDATE();

	IF [dbo].[fis_getModuleAuth]('fds_inv', @authuser) < 2
		THROW 60000, N'not authorized', 1;  
	
	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__setInvoicePayed' ,@authuser , (SELECT * FROM (VALUES(@Id, @authuser)) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER));

    UPDATE [dbo].[fds__invoices] SET [IsPayed] = 1, [paymentstatus] = 'm', [DateModified] = @now, [UserModified] = @authuser, [version] = (ISNULL([version],0) + 1)
	OUTPUT inserted.*
		WHERE [Id] = @Id AND @Id is not null and [IsPayed] = 0;

	IF TRY_CAST(@id as bigint) is not null and EXISTS(SELECT 0 FROM [dbo].[mfr__invoices] as i where i.[id] = TRY_CAST(@id as bigint))
		BEGIN
			MERGE [dbo].[fds__custom_invoiceinfo] as TARGET
			USING (VALUES
					   (TRY_CAST(@id as bigint)
					   ,CAST('m' as char(1))
					   ,CAST(1 as bit))) as SOURCE([InvId],[PaymentStatus],[isPayed]) 
					ON TARGET.[InvID] = SOURCE.[InvID]
			WHEN MATCHED THEN
				UPDATE SET TARGET.[PaymentStatus] = SOURCE.[PaymentStatus]
					,TARGET.[isPayed] = SOURCE.[isPayed]
			WHEN NOT MATCHED THEN 
				INSERT ([InvId],[PaymentStatus],[isPayed],[file])
				VALUES(
					SOURCE.[InvId]
					,SOURCE.[PaymentStatus]
					,SOURCE.[isPayed]
					,NULL
				);

		END

END