﻿USE [FabApprovalSystem]
GO
  /****** Object:  StoredProcedure [dbo].[GetApprovalForNotifcation]    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].[GetApprovalForNotifcation] -- Add the parameters for the stored procedure here
  AS BEGIN --Get ECN/TECN/EECN
SELECT
  ApprovalID AS ApprovalKey,
  Approval.IssueID AS IssueID,
  Users.LoginID AS AssignedName,
  Users.Email AS AssignedEmail,
  CONCAT(Users.FirstName, Users.LastName) AS AssignedFullName,
  NotifyDate AS LastNotification,
  AssignedDate,
  RoleAssignedDate,
  DocumentType.DocumentType AS DocType,
  ECN.Title AS Title
FROM
  Approval
  INNER JOIN Users ON Approval.UserID = Users.UserID
  INNER JOIN ECN ON Approval.IssueID = ECN.ECNNumber
  INNER JOIN DocumentType ON Approval.DocumentTypeID = DocumentType.DocumentTypeID
WHERE
  (
    Approval.DocumentTypeID = 3
    OR Approval.DocumentTypeID = 4
    OR Approval.DocumentTypeID = 5
  )
  AND Approval.ItemStatus = 0
  AND Users.IsActive = 1
  AND ECN.Deleted = 0
  AND DATEDIFF(HOUR, NotifyDate, GETDATE()) > 72
UNION
--Get Corrective Action
SELECT
  ApprovalID AS ApprovalKey,
  Approval.IssueID AS IssueID,
  Users.LoginID AS AssignedName,
  Users.Email AS AssignedEmail,
  CONCAT(Users.FirstName, Users.LastName) AS AssignedFullName,
  NotifyDate AS LastNotification,
  AssignedDate,
  RoleAssignedDate,
  DocumentType.DocumentType AS DocType,
  _8DCorrectiveAction.CATitle AS Title
FROM
  Approval
  INNER JOIN Users ON Approval.UserID = Users.UserID
  INNER JOIN _8DCorrectiveAction ON Approval.IssueID = _8DCorrectiveAction.CANo
  INNER JOIN DocumentType ON Approval.DocumentTypeID = DocumentType.DocumentTypeID
WHERE
  (
    Approval.DocumentTypeID = 3
    OR Approval.DocumentTypeID = 4
    OR Approval.DocumentTypeID = 5
  )
  AND Approval.ItemStatus = 0
  AND Users.IsActive = 1
  AND _8DCorrectiveAction.Deleted = 0
  AND DATEDIFF(HOUR, NotifyDate, GETDATE()) > 72
END
GO