﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[_8DGetAuditItem]    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].[_8DGetAuditItem] -- Add the parameters for the stored procedure here
	@AuditNo 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
		_8DAudit
	WHERE
		RecordLockIndicator = 1
		AND AuditNo = @AuditNo
) BEGIN
UPDATE
	_8DAudit
SET
	RecordLockIndicator = 1,
	RecordLockedBy = @UserID,
	RecordLockedDate = GETDATE(),
	LastUpdateDate = GETDATE()
WHERE
	AuditNo = @AuditNo
END -- Insert statements for procedure here
SELECT
	DISTINCT A.AuditNo,
	OriginatorID,
	AuditTitle,
	AuditTypeID,
	AuditScore,
	AuditDate,
	AuditorID,
	AuditStatus,
	AuditedAreaID,
	Auditees,
	RecordLockedBy,
	RecordLockIndicator,
	RecordLockedDate,
	LastUpdateDate,
	InsertTimeStamp,
	AC.Categories AS AuditFindingCategories,
	U.FirstName + ' ' + U.LastName AS OwnerName,
	U1.FirstName + ' ' + U1.LastName AS RecordLockByName,
	(
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = 'Major'
			AND AuditNo = @AuditNo
	) AS NoOfMajorNonConformities,
	(
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = 'Minor'
			AND AuditNo = @AuditNo
	) AS NoOfMinorNonConformities,
	(
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = '5S'
			AND AuditNo = @AuditNo
	) AS NoOf5SFindings,
	(
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = 'OFI'
			AND AuditNo = @AuditNo
	) AS NoOfOFIFindings
FROM
	_8DAudit A
	INNER JOIN Users U ON A.OriginatorID = U.UserID
	LEFT JOIN Users U1 ON A.RecordLockedBy = U1.UserID
	LEFT JOIN v8DAuditFindingsByAudit AC ON A.AuditNo = AC.AuditNo
WHERE
	A.AuditNo = @AuditNo
SELECT
	AuditorID
FROM
	_8DAuditorsByAudit
WHERE
	AuditNo = @AuditNo
SELECT
	AuditTypeID
FROM
	_8DAuditTypeByAudit
WHERE
	AuditNo = @AuditNo
SELECT
	AuditedAreaID
FROM
	_8DAuditedAreaByAudit
WHERE
	AuditNo = @AuditNo
END
GO