﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__remInvoice]
	@Id varchar(10),
	@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__remInvoice' ,@authuser , '');


	BEGIN TRANSACTION

	DECLARE @out TABLE([InvId] varchar(10), [json] nvarchar(max));

	INSERT INTO [dbo].[fds__removed] ([Id], [json],[dateDeleted_utc])
		OUTPUT inserted.[Id], inserted.[json]
			Into @out
	SELECT [Id]
		, [json] = (
					SELECT 
						[invoice] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoices] where [Id] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
						, [items] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoice_items] where [invId] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
						, [servicerequests] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoice_servicerequests] where [invId] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
						, [details] = JSON_QUERY( (SELECT * FROM [dbo].[fds__invoice_details] where [invId] = Inv.[InvId] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
					 FROM (VALUES([Id])) as Inv ([InvId])
					 FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
					)
		, [dateDeleted_utc] = GETUTCDATE()
	FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND @Id is not null AND [isFinal] = 0 AND [IsSent] = 0
	;

	IF EXISTS(SELECT 0 FROM @out CROSS APPLY OPENJSON([json]) where [key] = 'invoice')
    BEGIN
		DELETE FROM [dbo].[fds__invoices] WHERE [Id] = @Id AND @Id is not null AND [isFinal] = 0 AND [IsSent] = 0;
	
		DELETE FROM [dbo].[fds__invoice_items] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id);
	
		DELETE FROM [dbo].[fds__invoice_servicerequests] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id);
	
		DELETE FROM [dbo].[fds__invoice_details] WHERE [InvId] = @Id AND @Id is not null AND NOT EXISTS (SELECT * FROM [dbo].[fds__invoices] WHERE [Id] = @Id)
	END

	COMMIT TRANSACTION;

END