﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[CCGetChangeControl]    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].[CCGetChangeControl] -- Add the parameters for the stored procedure here
	@PlanNumber INT,
	@UserID INT,
	@CanViewITAR INT OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @ITARRowCount INT IF NOT EXISTS (
	SELECT
		*
	FROM
		CCChangeControl
	WHERE
		RecordLockIndicator = 1
		AND PlanNumber = @PlanNumber
) BEGIN
UPDATE
	CCChangeControl
SET
	RecordLockIndicator = 1,
	RecordLockedBy = @UserID,
	RecordLockedDate = GETDATE(),
	LastUpdateDate = GETDATE()
WHERE
	PlanNumber = @PlanNumber
END
SET
	@CanViewITAR = 1 IF EXISTS (
		SELECT
			*
		FROM
			CCChangeControl
		WHERE
			PlanNumber = @PlanNumber
			AND IsITAR = 1
	) BEGIN
SELECT
	@ITARRowCount = COUNT(*)
FROM
	dbo.fnIsUserITARCompliant(@UserID) IF (@ITARRowCount > 0)
SET
	@CanViewITAR = 1
	ELSE
SET
	@CanViewITAR = 0
END -- Insert statements for procedure here
SELECT
	DISTINCT CC.*,
	U.FirstName + ' ' + U.LastName AS OwnerName,
	U1.FirstName + ' ' + U1.LastName AS RecordLockByName,
	(
		SELECT
			COUNT(*)
		FROM
			CCMeeting
		WHERE
			Decision = -1
			AND CCMeeting.PlanNumber = @PlanNumber
	) AS MeetingExist,
	PCR1ID,
	PCR2ID,
	PCR3ID,
	--CAST('M-' + YEAR(InsertTimeStamp) + '-' + PlanYearlyIdentifier AS VARCHAR) AS PlanTitle,
	--CONCAT('M-', YEAR(CC.InsertTimeStamp), '-', CC.PlanYearlyIdentifier) AS PlanTitle,
	MesaPlanNo AS PlanTitle,
	CASE
		WHEN CC.ClosedDate IS NULL THEN 0
		ELSE 1
	END PCRBClosed
FROM
	CCChangeControl CC
	INNER JOIN Users U ON CC.OwnerID = U.UserID
	LEFT JOIN Users U1 ON CC.RecordLockedBy = U1.UserID
WHERE
	CC.PlanNumber = @PlanNumber
SELECT
	GenerationID
FROM
	CCGeneration
WHERE
	PlanNumber = @PlanNumber
SELECT
	LogisticsID
FROM
	CCLogistics
WHERE
	PlanNumber = @PlanNumber
SELECT
	ProcessID
FROM
	CCProcess
WHERE
	PlanNumber = @PlanNumber
END
GO