﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[ECN_TECNExpirationNotification]    Script Date: 11/21/2024 11:29:04 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE PROCEDURE [dbo].[ECN_TECNExpirationNotification] -- Add the parameters for the stored procedure here
	AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @Alert_Msg VARCHAR(1000) DECLARE @Subject VARCHAR(200) DECLARE @ECNUNumber INT,
@ExpirationDate DATETIME,
@OriginatorEmail VARCHAR(50),
@Title VARCHAR(200) DECLARE TECNExpirationNotification_cursor CURSOR FOR
SELECT
	E.ECNNumber,
	CASE
		WHEN E.ExtensionDate IS NOT NULL THEN E.ExtensionDate
		ELSE ExpirationDate
	END AS ExpirationDate,
	U.Email,
	Title
FROM
	ECN E
	INNER JOIN Users U ON E.OriginatorID = U.UserID
WHERE
	IsTECN = 1
	AND (
		(
			DATEDIFF(
				day,
				CAST(GETDATE() AS DATE),
				CAST(ExtensionDate AS DATE)
			) BETWEEN 1
			AND 14
		)
		OR (
			ExtensionDate IS NULL
			AND DATEDIFF(
				day,
				CAST(GETDATE() AS DATE),
				CAST(ExpirationDate AS DATE)
			) BETWEEN 1
			AND 14
		)
	)
	AND CancellationApproved = 0
	AND CancellationInProgress = 0
	AND ExpirationProcessed = 0
	AND ExpirationInProgress = 0
	AND CloseDate IS NOT NULL OPEN TECNExpirationNotification_cursor FETCH NEXT
FROM
	TECNExpirationNotification_cursor INTO @ECNUNumber,
	@ExpirationDate,
	@OriginatorEmail,
	@Title WHILE @ @FETCH_STATUS = 0 BEGIN
SET
	@Subject = 'TECN To Be Expired Notice - TECN#' + CONVERT(VARCHAR(10), @ECNUNumber) + ' for ' + @Title + ', Expires On: ' + CONVERT(VARCHAR(20), @ExpirationDate)
SET
	@Alert_Msg = '****** Please DO NOT reply to this email ****** ' + CHAR(10) + CHAR(13)
SET
	@Alert_Msg = @Alert_Msg + 'TECN#' + CONVERT(VARCHAR(10), @ECNUNumber) + ' will expire on ' + CONVERT(VARCHAR(20), @ExpirationDate) + '.' + CHAR(13)
SET
	@Alert_Msg = @Alert_Msg + 'Please log on to the Approval Website and review this item for extension if applicable.' + CHAR(10)
SET
	@Alert_Msg = @Alert_Msg + 'http://temsa01ec.ec.local:8021/ECN/Edit?issueID=' + CONVERT(VARCHAR(10), @ECNUNumber) + CHAR(10) + CHAR(13)
SET
	@Alert_Msg = @Alert_Msg + 'If you have any questions on it, please contact the site administrator' EXEC msdb.dbo.sp_send_dbmail @recipients = @OriginatorEmail,
	@body = @Alert_Msg,
	@subject = @Subject,
	@profile_name = 'DBAdmin' FETCH NEXT
FROM
	TECNExpirationNotification_cursor INTO @ECNUNumber,
	@ExpirationDate,
	@OriginatorEmail,
	@Title
END CLOSE TECNExpirationNotification_cursor;

DEALLOCATE TECNExpirationNotification_cursor;

END
GO