﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__setInvoiceFinal]
	@Id varchar(8),
	@authuser varchar(25)
AS
BEGIN
	SET NOCOUNT ON;
	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__setInvoiceFinal' ,@authuser , (SELECT * FROM (VALUES(@Id, @authuser)) as z ([id],[authuser]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER));

	DECLARE @now datetime = GETUTCDATE();

	DECLARE @ids as TABLE([Id] varchar(10));

	DECLARE @Replaces TABLE([RefInvID] varchar(10));
	INSERT INTO @Replaces SELECT [reference_invid] FROM [dbo].[fds__invoice_items] as itm where itm.[InvId] = @Id and itm.[Type] = 'CanceledInvoice' AND ISNULL([reference_invid],'') <>'';
	DECLARE @Replaces_InvId varchar(50) = CASE WHEN EXISTS(SELECT * FROM @Replaces) THEN STUFF( (SELECT ',' + [refinvid] as [Text] FROM @replaces FOR XML PATH, TYPE).value('.', 'nvarchar(max)'), 1, 1, '') ELSE NULL END;


    UPDATE [dbo].[fds__invoices] SET [DateFinalized] = @now, [UserFinalized] = @authuser, [DateModified] = @now, [UserModified] = @authuser, [invoiceid] = [dbo].[fds__newInvoiceId](Year(@now)), [version] = (ISNULL([version],0) + 1), [Replaces_InvId] = @Replaces_InvId
	OUTPUT inserted.[id]
		INTO @ids
	WHERE [Id] = @Id AND @Id is not null and [isFinal] = 0 and [isSent] = 0;

	SELECT iv.* FROM [dbo].[fds__invoices] as iv JOIN @ids as ids on iv.[id] = ids.Id;   --this is necessary to get calculated fields also


	--  update references of intermediate invoices
	WITH IntInvoiceAllocs as(
		SELECT [tgtInvId] = @Id, [reference_InvId] FROM [dbo].[fds__invoice_items] where [Type] = 'IntInvoiceAllocation' AND [InvId] = @Id
	), existing as (
		SELECT intermediates.Id 
			FROM [dbo].[fds__invoice_details] as id 
				JOIN [dbo].[fds__invoices] as intermediates on id.[InvId] = intermediates.[id] 
				JOIN IntInvoiceAllocs as iia on iia.[reference_InvId] = intermediates.[Id]
			WHERE ISNULL(intermediates.[iscanceled], 0) = 0 AND isnull(intermediates.[isfinal],0) = 1    -- reallocation is allowed for cancelled inv.
				and ISNULL(id.[AllocatedTo_InvId], '6AA609E8-1') <> @id 
	)
	MERGE [dbo].[fds__invoice_details] as TARGET
		USING IntInvoiceAllocs as iia ON TARGET.[InvID] = iia.[reference_InvId]
	WHEN NOT MATCHED BY TARGET 
		AND NOT EXISTS (SELECT * FROM existing WHERE existing.[id] = iia.[reference_InvId])  THEN 
		INSERT ([InvId] ,[AllocatedTo_InvId])
		VALUES (iia.[reference_InvId], iia.[tgtInvId])
	WHEN NOT MATCHED BY SOURCE THEN
		UPDATE 
			SET [AllocatedTo_InvId] = NULL 
	;

	--updated replaced invoices
	 UPDATE refinv
		SET [DateCancelled] = @now, [UserCancelled] = @authuser, [version] = (ISNULL([version],0) + 1)
	FROM [dbo].[fds__invoices] as refinv JOIN @Replaces as r on refinv.Id = r.[RefInvID]
		WHERE refinv.[isFinal] = 1 and refinv.[IsCanceled] = 0;


	--update replaced invoices   (by stornos)
	EXECUTE [dbo].[fds__maint__updateCancelledStatus];
END