﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[_8DInsertAuditFinding]    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].[_8DInsertAuditFinding] -- Add the parameters for the stored procedure here
	@AuditNo INT,
	@Findings VARCHAR(200),
	@ViolatedClause VARCHAR(100),
	@FindingType VARCHAR(10),
	@FindingCategories VARCHAR(200),
	@CANo INT,
	@Title VARCHAR(500) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

INSERT INTO
	_8DAuditFinding (
		AuditNo,
		Findings,
		ViolatedClause,
		FindingType,
		CANo,
		Title
	)
VALUES
	(
		@AuditNo,
		@Findings,
		@ViolatedClause,
		@FindingType,
		@CANo,
		@Title
	) DECLARE @AuditFindingsID INT
SET
	@AuditFindingsID = SCOPE_IDENTITY() DECLARE @SEPERATOR as VARCHAR(1) DECLARE @SP INT DECLARE @VALUE VARCHAR(1000)
SET
	@SEPERATOR = ',' CREATE TABLE #tempTab (AuditFindingCategory int not null)
	WHILE PATINDEX('%' + @SEPERATOR + '%', @FindingCategories) <> 0 BEGIN
SELECT
	@SP = PATINDEX('%' + @SEPERATOR + '%', @FindingCategories)
SELECT
	@VALUE = LEFT(@FindingCategories, @SP - 1)
SELECT
	@FindingCategories = STUFF(@FindingCategories, 1, @SP, '')
INSERT INTO
	#tempTab (AuditFindingCategory) VALUES (@VALUE)
END
INSERT INTO
	_8DAuditFindingCategoryByAuditFinding
SELECT
	@AuditFindingsID,
	AuditFindingCategory
FROM
	#tempTab
	DROP TABLE #tempTab
	DECLARE @NoOfMajorNonConformities INT DECLARE @NoOfMinorNonConformities INT DECLARE @NoOf5SFindings INT DECLARE @AuditScore INT
SELECT
	@AuditNo = AuditNo
FROM
	_8DAuditFinding
WHERE
	ID = @AuditFindingsID
SET
	@NoOfMajorNonConformities = (
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = 'Major'
			AND AuditNo = @AuditNo
	)
SET
	@NoOfMinorNonConformities = (
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = 'Minor'
			AND AuditNo = @AuditNo
	)
SET
	@NoOf5SFindings = (
		SELECT
			COUNT(*)
		FROM
			_8DAuditFinding
		WHERE
			FindingType = '5S'
			AND AuditNo = @AuditNo
	) -- IF Audit Type is either VDA or External the do not auto calculate the Audit Score
	IF (
		SELECT
			COUNT(*)
		FROM
			_8DAuditTypeByAudit
		WHERE
			(
				AuditTypeID = 4
				OR AuditTypeID = 8
			)
			AND AuditNo = @AuditNo
	) = 0 BEGIN
SET
	@AuditScore = 100 - (
		(@NoOfMajorNonConformities * 10) + (@NoOfMinorNonConformities) + (@NoOf5SFindings)
	)
UPDATE
	_8DAudit
SET
	AuditScore = @AuditScore
WHERE
	AuditNo = @AuditNo
END
END
GO