﻿


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__prepReminder]
	@InvId varchar(15)
	, @authuser varchar(100)
	, @type varchar(1)
	, @level int
AS
BEGIN
	SET NOCOUNT ON;
	IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2
		THROW 60000, N'not authorized', 1;  
	ELSE IF ISNULL(@type,'') NOT IN ('f','m','l') OR ISNULL(@level, 0) < 1 
		THROW 60000, N'inputs not valid', 1;  
	ELSE IF NOT EXISTS (select 0 FROM [dbo].[fds__invoices] WHERE [id] = @InvId)
		THROW 60000, N'invoice not found', 1;
	
	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__prepReminder' ,@authuser , (SELECT * FROM (VALUES(@InvId, @authuser, @type, @level)) as z ([InvId],[authuser],[type],[level]) FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER));
	
	
	DECLARE @now datetime = GETDATE();
	DECLARE @today date = CAST(@now as date);

	
	--output

	With inv as(
		select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId
	)
	SELECT TOP(1) 
			[today] = @today
			, [invid] = inv.[id]
			, [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf'
			, [paymentterms]	= [PaymentTerm]
			, [invoiceemail]	= IIF(ISNULL([SendToemail],'') = '', [dbo].[fds__getCompanyEmail](inv.[customerid]), [SendToemail])
			, [invoiceaddress]	= IIF(ISNULL([SendToAddress],'') = '', [dbo].[fds__getCompanyNameAddress](inv.[customerid]),[SendToAddress])
			, [CustomerId]		= [CustomerId]
			, [subject] = CASE WHEN @type = 'f' THEN N'Zahlungserinnerung'
								WHEN @type = 'm' THEN FORMAT(@level,'0','de-de') + N'. Mahnung' 
								WHEN @type = 'l' THEN N'Letzte außergerichtliche Mahnung' 
								ELSE N'Zahlungserinnerung'
							END
			, [type] = @type
			, [invoiceid] = inv.[Invoiceid]
			, [invoicedate] = inv.[DateFinalized]
			, [amount] = inv.[InvoiceBalance]
			, [amount_payed] = CAST(  ISNULL([dbo].[fds__fn_InvoicePaymentAmount_full](inv.[Id]),0.0)  as numeric(10,2))
		FROM inv;


END