﻿CREATE FUNCTION [dbo].[MatchMIS] (
     @workOrderNumber BIGINT,
     @itemNumber VARCHAR(25),
     @branchCode VARCHAR(12),
     @routingType VARCHAR(3),
     @issueDate DATETIME,
     @workCenterCode VARCHAR(12),
     @sequenceNumber DECIMAL(7, 2),
     @steptimestamp DATETIME,
     @functionCode VARCHAR(15),
     @functionOperationDescription VARCHAR(80)
    )
RETURNS @MIS TABLE 
(
     WorkOrderNumber BIGINT,
     ItemNumber VARCHAR(25),
	 ItemDescription VARCHAR(30),
     BranchCode VARCHAR(12),
     WorkCenterCode VARCHAR(12),
     StepTimestamp DATETIME,
     SequenceNumber DECIMAL(7, 2),
     FunctionCode VARCHAR(15),
     FunctionOperationDescription VARCHAR(80),
     MatchedSequenceNumber DECIMAL(7, 2),
     RoutingMatch BIT,
     MasterMatch BIT,
     MisNumber VARCHAR(32),
     RevID VARCHAR(32),
     CharNumber VARCHAR(32),
     MisSequenceNumber VARCHAR(32),
     TestDescription VARCHAR(2000),
     SamplingType VARCHAR(32),
     SamplingValue VARCHAR(32),
     ToolsGauges VARCHAR(2000),
     WorkInstructions VARCHAR(2000),
     Status VARCHAR(32),
     ReleaseDate DATETIME
)
    BEGIN
		--Lookup item description
		DECLARE @itemDescription VARCHAR(30);
		SELECT TOP 1 @itemDescription = i.Description FROM dbo.Item AS i WHERE i.ItemNumber = @itemNumber;

		--Find aliases for sequence number
        DECLARE @alias TABLE 
		(
             SequenceNumber DECIMAL(7, 2),
             RoutingMatch BIT,
             MasterMatch BIT
        );

		--Lookup parent work order info
		DECLARE @p_WorkOrderNumber BIGINT;
		SELECT @p_WorkOrderNumber = COALESCE(TRY_CONVERT(BIGINT, wo.ParentWorkOrderNumber), wo.WorkOrderNumber) FROM dbo.WorkOrder AS wo WHERE wo.WorkOrderNumber = @workOrderNumber;

		--Add F3112Z1 records to aliases
		WITH routing_cte AS (
			SELECT DISTINCT wor.StepNumber AS SequenceNumber
			FROM   dbo.WorkOrderRouting AS wor
			WHERE  wor.WorkOrderNumber = @p_WorkOrderNumber AND
				   wor.WorkCenterCode = @workCenterCode AND
				   wor.FunctionCode = @functionCode AND
				   wor.TransactionDate = (SELECT MIN(wor2.TransactionDate) FROM dbo.WorkOrderRouting AS wor2 WHERE wor2.WorkOrderNumber = @p_WorkOrderNumber)
		)
		MERGE @alias AS TARGET
		USING routing_cte AS SOURCE ON (TARGET.SequenceNumber = SOURCE.SequenceNumber)
		WHEN MATCHED THEN
			UPDATE SET TARGET.RoutingMatch = 1
		WHEN NOT MATCHED BY TARGET THEN
			INSERT(SequenceNumber, RoutingMatch, MasterMatch)
			VALUES (SOURCE.SequenceNumber, 1, 0);

		--Add F3003 records to aliases
		IF(NOT EXISTS(SELECT * FROM @alias AS a)) BEGIN
			WITH master_cte AS 
			(
				SELECT DISTINCT rm.SequenceNumber
				FROM   dbo.RouteMaster AS rm
				WHERE  rm.BranchCode = @branchCode AND
					   rm.ItemNumber = @itemNumber AND
					   rm.RoutingType = @routingType AND
					   @issueDate BETWEEN rm.StartDate AND rm.EndDate AND
					   rm.WorkCenterCode = @workCenterCode AND
					   rm.FunctionCode = @functionCode
			)
			MERGE @alias AS TARGET
			USING master_cte AS SOURCE ON (TARGET.SequenceNumber = SOURCE.SequenceNumber)
			WHEN MATCHED THEN
				 UPDATE SET TARGET.MasterMatch = 1
			WHEN NOT MATCHED BY TARGET THEN
				 INSERT(SequenceNumber, RoutingMatch, MasterMatch)
				 VALUES(SOURCE.SequenceNumber, 0, 1);
		END
		ELSE BEGIN
 			WITH master_cte AS 
			(
				SELECT DISTINCT rm.SequenceNumber
				FROM   dbo.RouteMaster AS rm
				WHERE  rm.BranchCode = @branchCode AND
					   rm.ItemNumber = @itemNumber AND
					   rm.RoutingType = @routingType AND
					   @issueDate BETWEEN rm.StartDate AND rm.EndDate AND
					   rm.WorkCenterCode = @workCenterCode AND
					   rm.FunctionCode = @functionCode
			)
			MERGE @alias AS TARGET
			USING master_cte AS SOURCE ON (TARGET.SequenceNumber = SOURCE.SequenceNumber)
			WHEN MATCHED THEN
				 UPDATE SET TARGET.MasterMatch = 1;     
		END
        

        --Try to match to 'Current'
		INSERT INTO @MIS
        (
            WorkOrderNumber,
            ItemNumber,
			ItemDescription,
            BranchCode,
            WorkCenterCode,
            StepTimestamp,
            SequenceNumber,
            FunctionCode,
            FunctionOperationDescription,
            MatchedSequenceNumber,
            RoutingMatch,
            MasterMatch,
            MisNumber,
            RevID,
            CharNumber,
            MisSequenceNumber,
            TestDescription,
            SamplingType,
            SamplingValue,
            ToolsGauges,
            WorkInstructions,
            Status,
            ReleaseDate
	    )
        SELECT  @workOrderNumber,
                @itemNumber,
				@itemDescription,
                @branchCode,
                @workCenterCode,
                @steptimestamp,
                @sequenceNumber,
                @functionCode,
                @functionOperationDescription,
                a.SequenceNumber AS MatchedSequenceNumber,
                a.RoutingMatch,
                a.MasterMatch,
                md.MisNumber,
                md.RevID,
                md.CharNumber,
                md.SequenceNumber AS MisSequenceNumber,
                md.TestDescription,
                md.SamplingType,
                md.SamplingValue,
                md.ToolsGauges,
                md.WorkInstructions,
                md.Status,
                md.ReleaseDate
        FROM    @alias AS a INNER JOIN 
		        dbo.MisData AS md ON (
                                         md.BranchCode = @branchCode AND
                                         md.ItemNumber = @itemNumber AND
                                         md.SequenceNumber = CAST(CAST(a.SequenceNumber AS INT) AS VARCHAR(32)) AND
                                         @steptimestamp BETWEEN COALESCE(md.ReleaseDate, '1970-01-01') AND COALESCE(md.ObsoleteDate, '2029-01-01')
                                     )
        WHERE   md.Status = 'Current';

        --Exit if any MIS info found
        IF (EXISTS ( SELECT *FROM @MIS ))
        BEGIN
            RETURN;
        END

		--Try to match to 'BackLevel'
        INSERT INTO @MIS
        (
            WorkOrderNumber,
            ItemNumber,
			ItemDescription,
            BranchCode,
            WorkCenterCode,
            StepTimestamp,
            SequenceNumber,
            FunctionCode,
            FunctionOperationDescription,
            MatchedSequenceNumber,
            RoutingMatch,
            MasterMatch,
            MisNumber,
            RevID,
            CharNumber,
            MisSequenceNumber,
            TestDescription,
            SamplingType,
            SamplingValue,
            ToolsGauges,
            WorkInstructions,
            Status,
            ReleaseDate
	    )
        SELECT  @workOrderNumber,
                @itemNumber,
				@itemDescription,
                @branchCode,
                @workCenterCode,
                @steptimestamp,
                @sequenceNumber,
                @functionCode,
                @functionOperationDescription,
                a.SequenceNumber AS MatchedSequenceNumber,
                a.RoutingMatch,
                a.MasterMatch,
                md.MisNumber,
                md.RevID,
                md.CharNumber,
                md.SequenceNumber AS MisSequenceNumber,
                md.TestDescription,
                md.SamplingType,
                md.SamplingValue,
                md.ToolsGauges,
                md.WorkInstructions,
                md.Status,
                md.ReleaseDate
        FROM    @alias AS a INNER JOIN 
		        dbo.MisData AS md ON (
                                         md.BranchCode = @branchCode AND
                                         md.ItemNumber = @itemNumber AND
                                         md.SequenceNumber = CAST(CAST(a.SequenceNumber AS INT) AS VARCHAR(32)) AND
										 md.ReleaseDate BETWEEN @issueDate AND @steptimestamp
                                     )
        WHERE   md.Status = 'BackLevel';

		--Exit if any MIS info found
        IF (EXISTS ( SELECT * FROM @MIS ))
        BEGIN
            RETURN;
        END

        INSERT  INTO @MIS
        (
			WorkOrderNumber,
			ItemNumber,
			ItemDescription,
			BranchCode,
			WorkCenterCode,
			StepTimestamp,
			SequenceNumber,
			FunctionCode,
			FunctionOperationDescription,
			MatchedSequenceNumber,
			RoutingMatch,
			MasterMatch
		)
        SELECT  @workOrderNumber,
                @itemNumber,
				@itemDescription,
                @branchCode,
                @workCenterCode,
                @steptimestamp,
                @sequenceNumber,
                @functionCode,
                @functionOperationDescription,
                a.SequenceNumber,
                a.RoutingMatch,
                a.MasterMatch
        FROM    @alias AS a;

		--Exit if any MIS info found
        IF (EXISTS ( SELECT * FROM @MIS ))
        BEGIN
            RETURN;
        END

		--Insert parameter data if no MIS or alias found
        INSERT  INTO @MIS
		(
			WorkOrderNumber,
			ItemNumber,
			ItemDescription,
			BranchCode,
			WorkCenterCode,
			StepTimestamp,
			SequenceNumber,
			FunctionCode,
			FunctionOperationDescription,
			MatchedSequenceNumber,
			RoutingMatch,
			MasterMatch
		)
        VALUES  
		(
            @workOrderNumber,
            @itemNumber,
			@itemDescription,
            @branchCode,
            @workCenterCode,
            @steptimestamp,
            @sequenceNumber,
            @functionCode,
            @functionOperationDescription,
            NULL,
            0,
            0
        );

        RETURN;
    END;