﻿
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__getReminder]
	@Id varchar(8),
	@includefile bit,
	@authuser varchar(25)
AS
BEGIN
	SET NOCOUNT ON;
	IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 1
		THROW 60000, N'not authorized', 1;  

	
	DECLARE @rem [dbo].[fds__tt__reminder_core];
	

	INSERT INTO @rem
    SELECT TOP(1) [Id]
      ,[Version]
	  ,[DocumentName]
	  ,[InvId]
      ,[CustomerId]
	  ,[SendToAddress]
	  ,[SendToEmail]
      ,[type]
      ,[amount]
	  ,[amount_payed]
	  ,[amount_open]
      ,[subject]
      ,[text]
      ,[IsSent]
      ,[IsFinal]
      ,[CustomValues]
      ,[DateSent]
	  ,[UserSent]
      ,[DateFinalized]
      ,[UserFinalized]
      ,[DateCreated]
      ,[UserCreated]
      ,[DateModified]
      ,[UserModified]
      ,[file] = CASE WHEN ISNULL(@includefile,0) = 1 THEN [file] else NULL END  -- do not return file if not explicitly requested
	  ,[file_guid]
  FROM [dbo].[fds__reminder]
	 WHERE [Id] = @Id AND @Id is not null;


		
	DECLARE @InvId varchar(15) = (SELECT TOP(1) [InvId] fROM @rem);

	---output

	--admin
	SELECT TOP(1) 
			[today]
			, [sender] = N'Sebastian Fuchs GmbH & Co. KG ● Germaniastraße 15 ● 40223 Düsseldorf'
			, [CustomerId] = rem.[CustomerId]
			, [type] = rem.[type]
		FROM (VALUES(CAST(GETDATE() as date)))base ([today]) cross JOIN @rem as rem;
	
	--rem
	With inv as(
		select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId
	)
	SELECT TOP(1) o.*
	  ,inv.[InvoiceId]
	  ,[InvoiceDate] = inv.[DateFinalized]
	  ,[InvoiceFileName] = inv.[DocumentName]
	  ,[InvoiceFile] = CASE WHEN ISNULL(@includefile,0) = 1 THEN inv.[file] else NULL END  -- do not return file if not explicitly requested
	  ,[hasFile] = CAST (  CASE WHEN o.[file] is null THEN 0 ELSE 1 END as bit)
	  ,[UserNameFinalized] =  [dbo].[fis_admin_getUserName_byID](o.[UserFinalized])
	  ,[UserEmailFinalized] =  [dbo].[fis_admin_getUserEmail_byID](o.[UserFinalized])
	from @rem as o 
		join inv on o.[invid] = inv.[id];

END