USE [DD_ECM]
GO

/****** Object:  StoredProcedure [dbo].[PRCUST_CREATE_PM_REMINDER_MAILS]    Script Date: 21.03.2024 17:08:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PRCUST_CREATE_PM_REMINDER_MAILS] @SUBJECT as VARCHAR(100) = ''
AS
	DECLARE @EMAIL VARCHAR(250), 
			@EMAIL_BODY VARCHAR(MAX),
			@BODYPRAEFIX VARCHAR(1000),
			@BODY_SUFFIX VARCHAR(1000)

	DECLARE @Table TABLE (TITLE Varchar(100),Anzahl VARCHAR(3),PType Varchar(50))

	--#######
	SET @SUBJECT = 'Erinnerung unerledigte Workflowschritte'
	SET @BODYPRAEFIX = 'Sehr geehrte Kollegin, sehr geehrter Kollege, <br><p>diese Email informiert Sie darüber, dass elektronische Eingangsrechnungen für 
			Sie zur Bearbeitung im Workflow bereit stehen: <br><p>'
	SET @BODY_SUFFIX = 'Mit freundlichen Grüßen.<p>Ihr ProcessManager'
	--#######

	DECLARE cUser CURSOR FOR
		SELECT DISTINCT EMail FROM [VWCUST_PM_PROFILE_TODO] 
		ORDER BY Email
	OPEN CUser
		FETCH NEXT FROM cUser INTO @EMAIL
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM @Table
		
			SET @EMAIL_BODY = '<!DOCTYPE html><html><body style=''font-family:"Arial";font-size:10.0pt''">' + @BODYPRAEFIX +
			'<table border = 1 style=''font-family:"arial";font-size:10.0pt''">
			<tr>
			<th>Workflow-Titel</th><th>Anzahl Belege</th><th>Aufgaben-Typ</th>'
	
			DECLARE @Anz Varchar(3),@Title Varchar(250),@PType Varchar(50)
		
			DECLARE cJobs CURSOR FOR
				SELECT Title,Convert(varchar(3), Anzahl),PType FROM [VWCUST_PM_PROFILE_TODO] WHERE Email = @EMAIL order by oSequence
			OPEN cJobs
			FETCH NEXT FROM cJobs INTO @Title,@Anz,@PType
			WHILE @@FETCH_STATUS = 0
			BEGIN
				INSERT INTO @Table (TITLE,Anzahl,PType) Values (@Title,@Anz,@PType);
				--Print @EMAIL + '#' + @Anz + ' ' + @Title
				FETCH NEXT FROM cJobs INTO @Title,@Anz,@PType
			END
			CLOSE cJobs
			DEALLOCATE cJobs

			Declare @xml NVARCHAR(Max)
			SET @xml = CAST((SELECT TITLE as 'td','',Anzahl as 'td','',PType as 'td','' FROM @Table FOR XML PATH('tr'),ELEMENTS) as NVARCHAR(MAX))
			SET @EMAIL_BODY = @EMAIL_BODY + @xml + '</table><p>' + @BODY_SUFFIX + 
			'</body></html>' --</body></html>
			Print @EMAIL_BODY

			IF NOT EXISTS(SELECT GUID FROM TBEMLP_EMAIL_OUT WHERE [EMAIL_ADRESS] = @EMAIL AND [EMAIL_SUBJ] = @SUBJECT and [EMAIL_SENT] is not null)
			--				AND DATEDIFF(Minute,ADDED_WHEN,GETDATE()) = 0)
				BEGIN

					INSERT INTO [dbo].[TBEMLP_EMAIL_OUT]
							([SENDING_PROFILE]
							,[REFERENCE_ID]
							,[WF_ID]
							,[EMAIL_ADRESS]
							,[EMAIL_SUBJ]
							,[EMAIL_BODY]
							,[COMMENT]
							,[ADDED_WHO])
						VALUES (1,
							88888,
							0,
							@EMAIL,-- + ';m.schreiber@digitaldata.works',
							@SUBJECT,
							@EMAIL_BODY,
							'PM Reminder',
							'PRPM_CUST_CREATE_REMINDER_MAILS')
				END

			ELSE
				PRINT 'ALREADY SENT IN THIS MINUTE'


			--Print '######'
			FETCH NEXT FROM cUser INTO @EMAIL
		END
	CLOSE cUser
	DEALLOCATE cUser
GO


