
PRINT N'Altering Procedure [sMro].[pMROFullViewGet]...';

GO
CREATE OR ALTER PROCEDURE [sMro].[pMROFullViewGet]
@rSourceId bigint,
@rSourceTypeId int,
@rOrgId int,
@rAreaId int,
@rParticipantSourceId bigint,
@rParticipantSourceTypeId int,
@rGenderId int,
@rAge int
as
begin
	declare @lConfigurationValue varchar(5)
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @rOrgId, 0, 0, 0)	
	Declare @rTargetGroupId int, @rSetupId int;
    set @rTargetGroupId = (select TargetGroupId from sExamination.tExamination where id=@rSourceId)  --0049369
    set @rSetupId = (select SetupId from sExamination.tExamination where id=@rSourceId)
	declare @tbltmpArea table
	(
		tid int identity(1,1),t_AreaId int,t_AreaName varchar(200),t_URL varchar(2000),
		t_ImagePath varchar(2000),t_AreaTypeId int
	)
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(1,@rOrgId),'Vital','','../../Images/Icon 16x16/icon_appointmnt.gif',0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(2,@rOrgId),'Habit Hygiene','','~/Images/Icon 16x16/icon_habits.gif',4  --//Mantis:0031798 By-Shivam on 11/03/2024
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(4,@rOrgId),'Existing Disease','','~/Images/Icon 16x16/icon_ExistingDisease.gif',4
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(5,@rOrgId),'Past History','','~/Images/Icon 16x16/icon_PastHistory.gif',4
		
	insert into @tbltmpArea
	select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0
	

	union all
		select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tArchieveTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0


	insert into @tbltmpArea
	select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	union all
		select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tArchieveGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(23,@rOrgId),'Audiometry','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(28,@rOrgId),'Pulmonary','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(10000,@rOrgId),'Diagnosis','','../../Images/Icon 16x16/icon_diagnosis.gif',0
	
	declare @cnt int,@i int
	select @cnt = count(*),@i = 1 from @tbltmpArea
	
	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
	col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
	
	while @i <= @cnt
	begin
		declare @lAreaId int = 0
		select @lAreaId = t_AreaId from @tbltmpArea where tid = @i
		
		if @lAreaId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			union all
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			union all
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			insert into @tbltmpview		
			SELECT 'BMI',convert(varchar,BMI) --+ CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
			,'','',      --0049369
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			union all
						SELECT 'BMI',convert(varchar,BMI) --+ CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
						,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BMI Result',[sExamination].[fBMIValueGet](isnull(BMI,0)) -- + ' /Min'
			,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			Union all

			SELECT 'BMI Result',[sExamination].[fBMIValueGet](isnull(BMI,0))  --+ ' /Min'
			,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			union all

			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			union all

						SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			--insert into @tbltmpview  ---0049369
			--SELECT 'Inhalation',convert(varchar,ChestExpansionInhalation) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tVital where SourceId = @rSourceId
			
			--insert into @tbltmpview  
			--SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tVital where SourceId = @rSourceId

			--union all

			--			SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tArchieveVital where SourceId = @rSourceId
			
			--insert into @tbltmpview
			--SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tVital where SourceId = @rSourceId

			--union all

			--			SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tArchieveVital where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHabitHygine HH
			INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = H.Id and TG.TargetGroupId = @rTargetGroupId -- -mantis id:0049369
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	 and TG.MainTypeId = @rSetupId  and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 10160 --and H.OrgId =@rOrgId  ---Habit

			union all

			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tArchieveHabitHygine HH
			INNER JOIN sExamination.tArchieveHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = H.Id and TG.TargetGroupId = @rTargetGroupId -- -mantis id:0049369
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	 and TG.MainTypeId = @rSetupId  and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 10160 --and H.OrgId =@rOrgId  ---Habit
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](4,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tExistingDisease E
			INNER JOIN sExamination.tExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG  on TG.SourceParameterId = DM.Id   --- -- -mantis id:0049369
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0 and TG.TargetGroupId = @rTargetGroupId  and TG.MainTypeId = @rSetupId and TG.SourceTemplateId = 10161 ---Disease

			union all

						SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tArchieveExistingDisease E
			INNER JOIN sExamination.tArchieveExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG  on TG.SourceParameterId = DM.Id   --- -- -mantis id:0049369
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0 and TG.TargetGroupId = @rTargetGroupId  and TG.MainTypeId = @rSetupId and TG.SourceTemplateId = 10161 ---Disease
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](5,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT DM.Title + '-' + RM.Title,HD.Remark,convert(varchar,HD.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHistory H
			INNER JOIN sExamination.tHistoryDetail HD ON H.Id = HD.HistoryId AND H.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId
			INNER JOIN sCommon.tRelationshipMaster RM on RM.Id=HD.RelationshipId
			WHERE H.ParticipantSourceId = @rParticipantSourceId
			AND H.ParticipantSourceTypeId = @rParticipantSourceTypeId
			AND H.OrgId = @rOrgId AND HD.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](23,@rOrgId)
	begin
	  IF EXISTS (
        SELECT 1
        FROM sExamination.tTargetGroupExaminationTemplate TG
        WHERE TG.TargetGroupId = @rTargetGroupId
          AND TG.MainTypeId = @rSetupId
          AND TG.SourceTemplateId = 10162   -- Audiometry-- -mantis id:0049369
    )
	begin

			insert into @tbltmpview
			SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			union all

						SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview
			SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			union all

						SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId

			union all

						SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId
		
			insert into @tbltmpview			
			SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId

			union all

						SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId

			union all

						SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId

			union all

			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId
		end
		end
		
       ELSE IF @lAreaId = [sCommon].[fGetIntIdForOrg](28, @rOrgId)
       BEGIN                                            -- Pulmonary-- -mantis id:0049369
           IF EXISTS (
               SELECT 1
               FROM sExamination.tTargetGroupExaminationTemplate TG
               WHERE TG.TargetGroupId = @rTargetGroupId
                 AND TG.MainTypeId = @rSetupId
                 AND TG.SourceTemplateId = 10163
           )
           BEGIN
       
               ;WITH Params AS (
                   SELECT 'FVC%' AS Param, 1 AS Seq
                   UNION ALL SELECT 'FEV1%', 2
                   UNION ALL SELECT 'FEV1/FVC%', 3
                   UNION ALL SELECT 'PEFR%', 4
                   UNION ALL SELECT 'RESULT', 5
               ),
               PulmonaryData AS (
                   SELECT *
                   FROM sExamination.tPulmonary
                   WHERE SourceId = @rSourceId
       
                   UNION ALL
       
                   SELECT *
                   FROM sExamination.tArchievePulmonary
                   WHERE SourceId = @rSourceId
               )
               INSERT INTO @tbltmpview
               SELECT
                   P.Param,
                   CASE P.Param
                       WHEN 'FVC%'       THEN CONVERT(nvarchar(100), D.PerOfPredictedFVC)
                       WHEN 'FEV1%'      THEN CONVERT(nvarchar(100), D.PerOfFEV1)
                       WHEN 'FEV1/FVC%'  THEN CONVERT(nvarchar(100), D.PerOfFEV1ByFVC)
                       WHEN 'PEFR%'      THEN CONVERT(nvarchar(100), D.PerPEFR)
                       WHEN 'RESULT'     THEN [sExamination].[fGetPulmonaryResultNew](@rSourceId)
                   END,
                   '', '',
                   'Parameter', 'Value', '', '',
                   1, @lAreaId
               FROM Params P
               LEFT JOIN PulmonaryData D
                   ON 1 = 1        -- ensures rows even if no data
               ORDER BY P.Seq;
       
           END
       END

		if exists (select 1 from sExamination.tGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'Value' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name, --mantis id-49369
			1,@lAreaId from sExamination.tGeneralTemplateExamination GTE
			INNER JOIN sExamination.tGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
			INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = GTP.Id  -- -mantis id:0049369
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
			 and TG.TargetGroupId = @rTargetGroupId and TG.MainTypeId = @rSetupId     and TG.SourceTemplateId = 119 --and   GTM.GeneralTemplateGroupId = 2   --general,Clinical
		end
		if exists (select 1 from sExamination.tArchieveGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'Value' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name,   --mantis id-49369
			1,@lAreaId from sExamination.tArchieveGeneralTemplateExamination GTE
			INNER JOIN sExamination.tArchieveGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
		    INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = GTP.Id  -- -mantis id:0049369
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
					 and TG.TargetGroupId = @rTargetGroupId and TG.MainTypeId = @rSetupId     and TG.SourceTemplateId = 119 --and   GTM.GeneralTemplateGroupId = 2   --general,Clinical
		end
		
		if exists(select 1 from sExamination.tTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
		    INNER JOIN sExamination.tTargetGroupExaminationTemplate TG on TG.SourceParameterId = TPM.Id      --mantis id:0049369
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
				AND TG.MainTypeId = @rSetupId and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 118  ---test
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tDiagnosis WHERE SourceId = @rSourceId
		end

				if exists(select 1 from sExamination.tArchieveTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tArchieveTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tArchieveTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
			INNER JOIN sExamination.tTargetGroupExaminationTemplate TG on TG.SourceParameterId = TPM.Id      --mantis id:0049369
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
			AND TG.MainTypeId = @rSetupId and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 118  ---test
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tArchieveDiagnosis WHERE SourceId = @rSourceId
		end
		
		select @i = @i + 1
	end
	
	declare @rescnt int,@j int,@res varchar(max)='',@newres varchar(max)='',@resab varchar(max)=''
	
	select @cnt = 0, @i = 0
	select @cnt = count(*),@i = 1 from @tbltmpArea
		
	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @Setup nvarchar(100);
	IF EXISTS (SELECT 1 FROM sExamination.tExamination WHERE Id = @rSourceId)
BEGIN
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId
		end
	else IF EXISTS (SELECT 1 FROM sExamination.tArchieveExamination WHERE Id = @rSourceId)
BEGIN
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tArchieveExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId
		end
	select @res = @res + '<div class="content-wrapper">
    <h6 class="p-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>Round: </b>' + @Setup + '</h6>
    <div>'

	while @i <= @cnt
	begin
		declare @areaid int = 0,@areaname varchar(max)='',@imgpath varchar(max)='',@pagepath varchar(max)=''
		declare @testareaid int
		select @areaid = t_AreaId,@areaname = t_AreaName,@imgpath = replace(t_ImagePath,'~/','../../'),
		@pagepath = replace(t_URL,'~/','/') from @tbltmpArea where tid = @i order by tid
		
		declare @lcnt int = 0
		select @lcnt = count(*) from @tbltmpview where AreaId = @areaid
		select @lcnt = isnull(@lcnt,0)
		--<div class="fRight" style="margin-top: -3px;"> 
		--	<img src="' + @imgpath + '" alt="' + @areaname + '" style="border-width:0px;">
		--	</div>

		if @lcnt > 0
		begin
			select @res = @res + '<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header alert alert-light col-md-12 mb-0">
                <h4 class="card-title">' + @areaname + '</h4></div>'
			
			--<a href="' + @pagepath + '" target="_blank">' + @areaname + '</a>
			
			create table #tbltmpnew(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
			col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
			
			insert into #tbltmpnew
			select col1,col2,col3,col4,col1Name,col2Name,col3Name,col4Name,isNormal,AreaId
			from @tbltmpview where AreaId = @areaid
			
			select @rescnt = count(*),@j = 1 from #tbltmpnew
			
			while @j <= @rescnt
			begin
				declare @col1 varchar(max)='',@col2 varchar(max)='',@col3 varchar(max)='',@col4 varchar(max)='',@isnormal int=0,
				@col1Name varchar(max)='',@col2Name varchar(max)='',@col3Name varchar(max)='',@col4Name varchar(max)=''
				
				if @j = 1
				begin
					select top 1 @col1Name=isnull(col1Name,''),@col2Name=isnull(col2Name,''),
					@col3Name=isnull(col3Name,''),@col4Name=isnull(col4Name,'') from #tbltmpnew where AreaId = @areaid
					
					select @newres = @newres + '<div class="card-content">
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                    <div class="table-responsive" id="htmlData" #htmlData>
					<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
					<tbody>
					<tr>
					<th scope="col"> <span>' + @col1Name + '</span> </th>
					<th scope="col"> <span>' + @col2Name + '</span> </th>				
					<th scope="col"> <span>' + @col3Name + '</span> </th>				
					<th scope="col"> <span>' + @col4Name + '</span> </th>				
					</tr>'
				end
				
				select @col1=isnull(col1,''),@col2=isnull(col2,''),@col3=isnull(col3,''),@col4=isnull(col4,''),@isnormal = isnull(isnormal,0) from #tbltmpnew where tid = @j			
				
				select @resab = @resab + '<tr'+ (case when @isnormal=1 then '' else ' style="color:red"' end)+'>'+'
				<td style="width:25%;"><span title="' + @col1 + '" class="boxEllips" style="display:inline-block;">' + @col1 + '</span> </td>
				<td style="width:25%;"><span title="' + @col2 + '" class="boxEllips" style="display:inline-block;">' + @col2 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col3 + '" class="boxEllips" style="display:inline-block;">' + @col3 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col4 + '" class="boxEllips" style="display:inline-block;">' + @col4 + '</span> </td>			
				</tr>'
				
				if @j = @rescnt
				begin
					select @res = @res + @newres + @resab + '</div></div></tbody></table></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>'
					select @newres = '',@resab = ''				
				end
				
				select @j = @j + 1
			end
			drop table #tbltmpnew
		end		
		
		select @i = @i + 1
	end
		
	select @res = isnull(@res,'')	
	select @res as res
end
GO
PRINT N'Altering Procedure [sMro].[pDaignosisViewGet]...';


GO

CREATE OR ALTER PROCEDURE [sMro].[pDaignosisViewGet]
@rSourceId bigint,
@rSourceTypeId int,
@rOrgId int,
@rAreaId int,
@rParticipantSourceId bigint,
@rParticipantSourceTypeId int,
@rGenderId int,
@rAge int
as
begin
	declare @lConfigurationValue varchar(5)
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @rOrgId, 0, 0, 0)	
	declare @tbltmpArea table
	(
		tid int identity(1,1),t_AreaId int,t_AreaName varchar(200),t_URL varchar(2000),
		t_ImagePath varchar(2000),t_AreaTypeId int
	)
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(1,@rOrgId),'Vital','','../../Images/Icon 16x16/icon_appointmnt.gif',0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(2,@rOrgId),'Habit Hygiene','','~/Images/Icon 16x16/icon_habits.gif',4  --//Mantis:0031798 By-Shivam on 11/03/2024
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(4,@rOrgId),'Existing Disease','','~/Images/Icon 16x16/icon_ExistingDisease.gif',4
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(5,@rOrgId),'Past History','','~/Images/Icon 16x16/icon_PastHistory.gif',4
		
	insert into @tbltmpArea
	select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0
	order by TM.OrderIndex 

	insert into @tbltmpArea
	select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(23,@rOrgId),'Audiometry','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(28,@rOrgId),'Pulmonary','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(10000,@rOrgId),'Diagnosis','','../../Images/Icon 16x16/icon_diagnosis.gif',0
	
	declare @cnt int,@i int
	select @cnt = count(*),@i = 1 from @tbltmpArea
	
	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
	col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
	
	while @i <= @cnt
	begin
		declare @lAreaId int = 0
		select @lAreaId = t_AreaId from @tbltmpArea where tid = @i
		
		if @lAreaId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview		
			SELECT 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Pulse',convert(varchar,Pulse) + ' /Min','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Inhalation',convert(varchar,ChestExpansionInhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHabitHygine HH
			INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](4,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tExistingDisease E
			INNER JOIN sExamination.tExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](5,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT DM.Title + '-' + RM.Title,HD.Remark,convert(varchar,HD.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHistory H
			INNER JOIN sExamination.tHistoryDetail HD ON H.Id = HD.HistoryId AND H.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId
			INNER JOIN sCommon.tRelationshipMaster RM on RM.Id=HD.RelationshipId
			WHERE H.ParticipantSourceId = @rParticipantSourceId
			AND H.ParticipantSourceTypeId = @rParticipantSourceTypeId
			AND H.OrgId = @rOrgId AND HD.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](23,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview
			SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId
		
			insert into @tbltmpview			
			SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (28,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'FVC%',CONVERT(nvarchar(100),PerOfPredictedFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'FEV1%',CONVERT(nvarchar(100),PerOfFEV1),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'FEV1/FVc%',CONVERT(nvarchar(100),PerOfFEV1ByFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'PEFR%',CONVERT(nvarchar(100),PerPEFR),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'RESULT',(select item1 + ' ' + item2 from [sExamination].[fGetPulmonaryResults_NEW](@rSourceId)),'','',
			'Parameter','Value','','',1,@lAreaId
		end
		
		if exists (select 1 from sExamination.tGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'ServiceValue' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name,
			1,@lAreaId from sExamination.tGeneralTemplateExamination GTE
			INNER JOIN sExamination.tGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
		end
		
		if exists(select 1 from sExamination.tTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tDiagnosis WHERE SourceId = @rSourceId
		end
		
		select @i = @i + 1
	end
	
	declare @rescnt int,@j int,@res varchar(max)='',@newres varchar(max)='',@resab varchar(max)=''
	
	select @cnt = 0, @i = 0
	select @cnt = count(*),@i = 1 from @tbltmpArea
		
	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @Setup nvarchar(100);
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId

	select @res = @res + '<div class="content-wrapper">
    <h6 class="p-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>Round: </b>' + @Setup + '</h6>
    <div>'

	while @i <= @cnt
	begin
		declare @areaid int = 0,@areaname varchar(max)='',@imgpath varchar(max)='',@pagepath varchar(max)=''
		declare @testareaid int
		select @areaid = t_AreaId,@areaname = t_AreaName,@imgpath = replace(t_ImagePath,'~/','../../'),
		@pagepath = replace(t_URL,'~/','/') from @tbltmpArea where tid = @i order by tid
		
		declare @lcnt int = 0
		select @lcnt = count(*) from @tbltmpview where AreaId = @areaid
		select @lcnt = isnull(@lcnt,0)
		--<div class="fRight" style="margin-top: -3px;"> 
		--	<img src="' + @imgpath + '" alt="' + @areaname + '" style="border-width:0px;">
		--	</div>

		if @lcnt > 0
		begin
			select @res = @res + '<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header alert alert-light col-md-12 mb-0">
                <h4 class="card-title">' + @areaname + '</h4></div>'
			
			--<a href="' + @pagepath + '" target="_blank">' + @areaname + '</a>
			
			create table #tbltmpnew(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
			col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
			
			insert into #tbltmpnew
			select col1,col2,col3,col4,col1Name,col2Name,col3Name,col4Name,isNormal,AreaId
			from @tbltmpview where AreaId = @areaid
			
			select @rescnt = count(*),@j = 1 from #tbltmpnew
			
			while @j <= @rescnt
			begin
				declare @col1 varchar(max)='',@col2 varchar(max)='',@col3 varchar(max)='',@col4 varchar(max)='',@isnormal int=0,
				@col1Name varchar(max)='',@col2Name varchar(max)='',@col3Name varchar(max)='',@col4Name varchar(max)=''
				
				if @j = 1
				begin
					select top 1 @col1Name=isnull(col1Name,''),@col2Name=isnull(col2Name,''),
					@col3Name=isnull(col3Name,''),@col4Name=isnull(col4Name,'') from #tbltmpnew where AreaId = @areaid
					
					select @newres = @newres + '<div class="card-content">
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                    <div class="table-responsive" id="htmlData" #htmlData>
					<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
					<tbody>
					<tr>
					<th scope="col"> <span>' + @col1Name + '</span> </th>
					<th scope="col"> <span>' + @col2Name + '</span> </th>				
					<th scope="col"> <span>' + @col3Name + '</span> </th>				
					<th scope="col"> <span>' + @col4Name + '</span> </th>				
					</tr>'
				end
				
				select @col1=isnull(col1,''),@col2=isnull(col2,''),@col3=isnull(col3,''),@col4=isnull(col4,''),@isnormal = isnull(isnormal,0) from #tbltmpnew where tid = @j			
				
				select @resab = @resab + '<tr'+ (case when @isnormal=1 then '' else ' style="color:red"' end)+'>'+'
				<td style="width:25%;"><span title="' + @col1 + '" class="boxEllips" style="display:inline-block;">' + @col1 + '</span> </td>
				<td style="width:25%;"><span title="' + @col2 + '" class="boxEllips" style="display:inline-block;">' + @col2 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col3 + '" class="boxEllips" style="display:inline-block;">' + @col3 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col4 + '" class="boxEllips" style="display:inline-block;">' + @col4 + '</span> </td>			
				</tr>'
				
				if @j = @rescnt
				begin
					select @res = @res + @newres + @resab + '</div></div></tbody></table></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>'
					select @newres = '',@resab = ''				
				end
				
				select @j = @j + 1
			end
			drop table #tbltmpnew
		end		
		
		select @i = @i + 1
	end
		
	select @res = isnull(@res,'')	
	select @res as res
end
GO
PRINT N'Altering Procedure [sExamination].[pExaminationEmployeeDetailGet]...';


GO
-- EXEC [sExamination].[pExaminationEmployeeDetailGet] 3001000000860,999900001,3001  
-- DROP PROC [sExamination].[pExaminationEmployeeDetailGet]  
CREATE OR ALTER PROCEDURE [sExamination].[pExaminationEmployeeDetailGet]   
@rEmployeeID bigint,  
@rStoreLocationId int,  
@rOrgID int,  
@rAbnoraml int =1   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 DECLARE @SetupName AS nvarchar(max) = '',@DynamicPivotQuery AS nvarchar(max) = ''  
  
  Declare @lConfDiseaseEvaluation varchar(20);
	select Top 1 @lConfDiseaseEvaluation = ISNULL(CS.ItemValue,CM.ItemValue)
	from sConfig.tConfigurationMaster as CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
	where CM.ItemKey = 'Examination.DiagnosisEvaluation'

 IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL  
 BEGIN  
  DROP TABLE #TableOne  
 END  
  
 CREATE TABLE #TableOne  
 (  
  ExaminationId bigint,SetupId int,SetupName varchar(500),ExaminationDate date,ParameterId int,  
  Parameter varchar(500),value nvarchar(2000),eType nvarchar(500),IsHistory int,orderIndex int,  
  SortOrder int,IsNormal int , Remark nvarchar(2000)  
 )  
 INSERT INTO #TableOne  
 SELECT EXM.Id,EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,  
 Vital.ParameterId,Vital.Parameter,CONVERT(varchar(200),Vital.value),  
 'Vital',Vital.IsHistory, 1,2,0,''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN [sExamination].[tVital] AS VTL ON VTL.SourceId = EXM.Id  
 INNER JOIN  
 (  
  SELECT t.*  
  FROM sExamination.tVital v  
  CROSS APPLY  
  (  
   VALUES  
   (  
    SourceId, 1, 100000, 'Height', Height  
   ),  
   (  
    SourceId, 2, 200000, 'Weight', BodyWeight  
   ),  
   (  
    SourceId, 3, 300000, 'BMI', BMI  
   ),  
   (  
    SourceId, 4, 400000, 'Pulse', Pulse  
   ),  
   (  
    SourceId, 5, 500000, 'BP Sys (mmHg)', BloodPressureSystolic  
   ),  
   (  
    SourceId, 6, 600000, 'BP Dia (mmHg)', BloodPressureDiastolic  
   ),  
   (  
    SourceId, 7, 700000, 'Respiration (/Min)', Respiration  
   )  
  ) t  
  (  
   SourceId, ParameterId, IsHistory, Parameter, value  
  )  
 ) AS Vital ON Vital.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2,6)  
  
 UNION ALL  
  
 SELECT EXM.Id,EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,8,TPM.Title,  
 --CASE WHEN ISNULL(TRD.IsAbnormal, 0)= 1 THEN '<span style="background-color:gold;">'+TRD.ServiceValue+'</span>' ELSE TRD.ServiceValue END ,
 TRD.ServiceValue,
 'Test',  
 CASE WHEN SPM.Id IN (2, 3, 8, 17, 30, 31, 32, 34, 35) THEN SPM.Id ELSE 0 END,  
 TPM.OrderIndex,3,ISNULL(TRD.IsAbnormal, 0),
 TRD.Remark
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN sExamination.tTestRequest AS TSR ON TSR.SourceId = EXM.Id  
 INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestRequestId = TSR.Id  
 INNER JOIN sOrderEntry.tTestDetail AS TDL ON TDL.id = TestDetailId  
 INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.Id = TDL.TestParameterId  
 INNER JOIN sOrderEntry.tStaticTestParameterMaster AS SPM ON SPM.Id = TPM.StaticTestParameterId  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)   
 AND ISNULL(TPM.IsObsolete, 0) = 0  
 AND ((ISNULL(TRD.IsAbnormal, 0) = @rAbnoraml) Or (@rAbnoraml=0))  
  
 UNION ALL  
  
 SELECT EXM.Id, EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,9,  
 GTP.Title,GTD.ParameterValue,'General',0,B.OrderIndex,6,ISNULL(GTD.IsAbnormal, 0),''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN sExamination.tGeneralTemplateExamination AS GTE ON GTE.SourceId = EXM.Id  
 INNER JOIN [sExamination].[tGeneralTemplateExaminationDetail] AS GTD ON GTD.GeneralTemplateExaminationId = GTE.ID  
 INNER JOIN [sExamination].[tGeneralTemplateParameter] AS GTP ON GTP.Id = GeneralTemplateParameterId  
 LEFT JOIN sExamination.tStaticGeneralTemplateParameter B ON b.Id = GTP.StaticGeneralTemplateParameterId  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
 AND ISNULL(GTP.IsObsolete, 0) = 0  
 AND ((ISNULL(GTD.IsAbnormal, 0) = @rAbnoraml) or (@rAbnoraml=0))  
  
 UNION ALL  
  
 SELECT EXM.Id,EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,10,Vital.Parameter,  
 CONVERT(varchar(200),Vital.value),'Audiometry',0,ParameterId,4,0,''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN  
 (  
  SELECT AUD.*, AMR.Title Value  
  FROM  
  (  
   SELECT t.* FROM [sExamination].[tAudiometry] AS AUD  
   CROSS APPLY  
   (  
    VALUES(SourceId, 10, 'Left Ac Result', AudiometryAcResultLeftId),  
    (SourceId, 11, 'Left Bc Result', AudiometryBcResultLeftId),  
    (SourceId, 13, 'Right Ac Result', AudiometryAcResultRightId),  
    (SourceId, 14, 'Right Bc Result', AudiometryBcResultRightId)  
   ) t  
   (SourceId, ParameterId, Parameter, ValueId)  
  ) AS AUD INNER JOIN sExamination.tAudiometryResultMaster AS AMR ON AMR.Id = AUD.ValueId  
  UNION ALL  
  SELECT AUD.*, AMR.Title Value  
  FROM  
  (  
   SELECT t.* FROM [sExamination].[tAudiometry] AS AUD  
   CROSS APPLY  
   (  
    VALUES  
    (SourceId, 12, 'Left Remark Result', AudiometryResultRemarkLeftId),  
    (SourceId, 15, 'Right Remark Result', AudiometryResultRemarkRightId)  
   ) t (SourceId, ParameterId, Parameter, ValueId)  
  ) AS AUD INNER JOIN sExamination.tAudioMetryRemarkMaster AS AMR ON AMR.Id = AUD.ValueId  
 ) AS Vital ON Vital.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
   
 UNION ALL  
  
 SELECT EXM.Id, EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,11,Vital.Parameter,  
 CONVERT(varchar(200),Vital.value), 'Pulmonary',  
 CASE WHEN ParameterId IN (800000, 900000, 1000000, 1100000) THEN ParameterId ELSE 0 END,  
 ParameterId,5,0,''
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN  
 (  
  SELECT t.* FROM sExamination.tPulmonary AS PLM CROSS APPLY  
  (  
   VALUES (SourceId, 800000, 'FVC%', CONVERT(varchar, PerOfPredictedFVC)),  
   (SourceId, 900000, 'FEV1%', CONVERT(varchar, PerOfFEV1)),  
   (SourceId, 1000000, 'FEV1/FVc%', CONVERT(varchar, PerOfFEV1ByFVC)),  
   (SourceId, 1100000, 'PEFR%', CONVERT(varchar, PerPEFR)),  
   (SourceId, 1200000, 'RESULT', [sExamination].[fGetPulmonaryResultNew](SourceId))  
  ) t (SourceId, ParameterId, Parameter, value)  
 ) AS Vital ON Vital.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
   
 UNION ALL  
   
 SELECT EXM.Id, EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,12,Diagnosis.Parameter,  
 CONVERT(varchar(500),Diagnosis.value),'Diagnosis',0,ParameterId,1,0,''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN  
 (  
  SELECT t.* FROM sExamination.tDiagnosis  
  CROSS APPLY  
  (  
   VALUES (SourceId, 1, 'Diagnosis', (Case When @lConfDiseaseEvaluation ='True' Then [sExamination].[fReplaceDiagnosisRemark](DiagnosisRemark) ELSE DiagnosisRemark END)),  
   (SourceId, 2, 'Recommendation', RecommendationEnglish),  
   (SourceId, 3, 'HealthIndexPercentage', Convert(varchar(200),HealthIndex)),  
   (SourceId, 4, 'CounsellingRemark', Isnull(CounsellingRemark,''))  
  ) t (SourceId, ParameterId, Parameter, value)  
 ) AS Diagnosis ON Diagnosis.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
 ORDER BY EXM.ExaminationDate DESC  
   
  
 DECLARE @Count int = 0  
   
 DECLARE @SetupNameTable TABLE  
 (  
  tId int IDENTITY (1, 1), SetupName nvarchar(250)  
 )  
 INSERT INTO @SetupNameTable  
 SELECT Title FROM [sExamination].[tSetupMaster] SM  
 --inner join sExamination.tExamination EXM On EXM.SetupID = SM.Id and EXM.OrgID = @rOrgID AND EXM.ParticipantSourceTypeId = 95 AND EXM.ParticipantSourceId = @rEmployeeID  
 WHERE SM.id IN  
 (  
  SELECT DISTINCT SetupId FROM #TableOne   
 )  
 order by ToDate   
   
 --select * from @SetupNameTable  
  
 SELECT @Count = COUNT(0) FROM @SetupNameTable  
  
 WHILE (@Count <> 0)  
 BEGIN  
  SELECT @SetupName = @SetupName + '[' + ISNULL(UPPER(SetupName), '') + '],'  
  FROM @SetupNameTable WHERE tId = @Count  
    
  SET @Count = @Count - 1  
 END  
   
 SET @SetupName = SUBSTRING(@SetupName, 0, LEN(@SetupName))  
   
 --select @SetupName  
  
 insert into #TableOne  
 SELECT DISTINCT 0,SM.id,SM.Title,EXM.ExaminationDate,0,'Examination Date',Convert(varchar,EXM.ExaminationDate,103),'Examination Date',0,1,1,0,''  
 FROM [sExamination].[tSetupMaster] SM  
 inner join sExamination.tExamination EXM On EXM.SetupID = SM.Id and EXM.OrgID = @rOrgID AND EXM.ParticipantSourceTypeId = 95 AND EXM.ParticipantSourceId = @rEmployeeID  
 WHERE SM.id IN  
 (  
  SELECT DISTINCT SetupId FROM #TableOne  
 )  
   
  
 --SELECT * FROM #TableOne  
  
 IF (@SetupName <> '')  
 BEGIN  
 SET @DynamicPivotQuery = '
SELECT eType AS "Examination Type", Parameter,  
  CASE WHEN IsHistory > 0 THEN 
      ''<a style="cursor:pointer;" onclick="Javascript:GetChartDetails('' + CONVERT(varchar, IsHistory) + '');">View History</a>''
    ELSE 
      '''' 
  END AS History, 
  ' + @SetupName + '
FROM  
(  
    SELECT ParameterId, Parameter, 
    CASE 
       WHEN Parameter IN (''ECG'', ''SONOGRAPHY'', ''ECHO'', ''XRAY'') AND value = ''Abnormal'' or (Parameter = ''TMT'') and value = ''Positive'' THEN 
            CASE 
  WHEN Parameter = ''TMT'' AND value = ''Positive'' THEN ''Positive '' + CASE WHEN ISNULL(Remark, '''') = '''' THEN '''' ELSE ''- '' + ISNULL(Remark, '''') END
                WHEN value = ''Abnormal'' THEN ''Abnormal '' + CASE WHEN ISNULL(Remark, '''') = '''' THEN '''' ELSE ''- '' + ISNULL(Remark, '''') END
                ELSE value
            END
        ELSE value
    END AS value, 
    SetupName, eType, IsHistory, orderIndex, SortOrder 
    FROM #TableOne  
) AS Tab1  
PIVOT (MAX(value) FOR SetupName IN (' + @SetupName + ')) AS PVT 
ORDER BY SortOrder, ParameterId, orderIndex;';
  PRINT @DynamicPivotQuery  
  EXECUTE (@DynamicPivotQuery)  
  --Case When IsNormal=0 then '''' Else ''Yes'' End As IsAbnormal,  
 END  
END
GO
PRINT N'Altering Procedure [sExamination].[pDaignosisFullViewGet]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pDaignosisFullViewGet]
@rSourceId bigint,
@rSourceTypeId int,
@rOrgId int, 
@rAreaId int,
@rParticipantSourceId bigint,
@rParticipantSourceTypeId int,
@rGenderId int,
@rAge int
as
begin
	declare @lConfigurationValue varchar(5)
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @rOrgId, 0, 0, 0)	
	declare @tbltmpArea table
	(
		tid int identity(1,1),t_AreaId int,t_AreaName varchar(200),t_URL varchar(2000),
		t_ImagePath varchar(2000),t_AreaTypeId int
	)
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(1,@rOrgId),'Vital','','../../Images/Icon 16x16/icon_appointmnt.gif',0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(2,@rOrgId),'Habit Hygiene','','~/Images/Icon 16x16/icon_habits.gif',4  --//Mantis:0031798 By-Shivam on 11/03/2024
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(4,@rOrgId),'Existing Disease','','~/Images/Icon 16x16/icon_ExistingDisease.gif',4
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(5,@rOrgId),'Past History','','~/Images/Icon 16x16/icon_PastHistory.gif',4
		
	insert into @tbltmpArea
	select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0
	order by TM.OrderIndex 

	insert into @tbltmpArea
	select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(23,@rOrgId),'Audiometry','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(28,@rOrgId),'Pulmonary','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(10000,@rOrgId),'Diagnosis','','../../Images/Icon 16x16/icon_diagnosis.gif',0
	
	declare @cnt int,@i int
	select @cnt = count(*),@i = 1 from @tbltmpArea
	
	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
	col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
	
	while @i <= @cnt
	begin
		declare @lAreaId int = 0
		select @lAreaId = t_AreaId from @tbltmpArea where tid = @i
		
		if @lAreaId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview		
			SELECT 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Pulse',convert(varchar,Pulse) + ' /Min','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Inhalation',convert(varchar,ChestExpansionInhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHabitHygine HH
			INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](4,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tExistingDisease E
			INNER JOIN sExamination.tExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](5,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT DM.Title + '-' + RM.Title,HD.Remark,convert(varchar,HD.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHistory H
			INNER JOIN sExamination.tHistoryDetail HD ON H.Id = HD.HistoryId AND H.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId
			INNER JOIN sCommon.tRelationshipMaster RM on RM.Id=HD.RelationshipId
			WHERE H.ParticipantSourceId = @rParticipantSourceId
			AND H.ParticipantSourceTypeId = @rParticipantSourceTypeId
			AND H.OrgId = @rOrgId AND HD.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](23,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview
			SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId
		
			insert into @tbltmpview			
			SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (28,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'FVC%',CONVERT(nvarchar(100),PerOfPredictedFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'FEV1%',CONVERT(nvarchar(100),PerOfFEV1),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'FEV1/FVc%',CONVERT(nvarchar(100),PerOfFEV1ByFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'PEFR%',CONVERT(nvarchar(100),PerPEFR),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'RESULT',(select item1 + ' ' + item2 from [sExamination].[fGetPulmonaryResults_NEW](@rSourceId)),'','',
			'Parameter','Value','','',1,@lAreaId
		end
		
		if exists (select 1 from sExamination.tGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'ServiceValue' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name,
			1,@lAreaId from sExamination.tGeneralTemplateExamination GTE
			INNER JOIN sExamination.tGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
		end
		
		if exists(select 1 from sExamination.tTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tDiagnosis WHERE SourceId = @rSourceId
		end
		
		select @i = @i + 1
	end
	
	declare @rescnt int,@j int,@res varchar(max)='',@newres varchar(max)='',@resab varchar(max)=''
	
	select @cnt = 0, @i = 0
	select @cnt = count(*),@i = 1 from @tbltmpArea
		
	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @Setup nvarchar(100);
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId

	select @res = @res + '<div class="content-wrapper">
    <h6 class="p-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>Round: </b>' + @Setup + '</h6>
    <div>'

	while @i <= @cnt
	begin
		declare @areaid int = 0,@areaname varchar(max)='',@imgpath varchar(max)='',@pagepath varchar(max)=''
		declare @testareaid int
		select @areaid = t_AreaId,@areaname = t_AreaName,@imgpath = replace(t_ImagePath,'~/','../../'),
		@pagepath = replace(t_URL,'~/','/') from @tbltmpArea where tid = @i order by tid
		
		declare @lcnt int = 0
		select @lcnt = count(*) from @tbltmpview where AreaId = @areaid
		select @lcnt = isnull(@lcnt,0)
		--<div class="fRight" style="margin-top: -3px;"> 
		--	<img src="' + @imgpath + '" alt="' + @areaname + '" style="border-width:0px;">
		--	</div>

		if @lcnt > 0
		begin
			select @res = @res + '<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header alert alert-light col-md-12 mb-0">
                <h4 class="card-title">' + @areaname + '</h4></div>'
			
			--<a href="' + @pagepath + '" target="_blank">' + @areaname + '</a>
			
			create table #tbltmpnew(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
			col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
			
			insert into #tbltmpnew
			select col1,col2,col3,col4,col1Name,col2Name,col3Name,col4Name,isNormal,AreaId
			from @tbltmpview where AreaId = @areaid
			
			select @rescnt = count(*),@j = 1 from #tbltmpnew
			
			while @j <= @rescnt
			begin
				declare @col1 varchar(max)='',@col2 varchar(max)='',@col3 varchar(max)='',@col4 varchar(max)='',@isnormal int=0,
				@col1Name varchar(max)='',@col2Name varchar(max)='',@col3Name varchar(max)='',@col4Name varchar(max)=''
				
				if @j = 1
				begin
					select top 1 @col1Name=isnull(col1Name,''),@col2Name=isnull(col2Name,''),
					@col3Name=isnull(col3Name,''),@col4Name=isnull(col4Name,'') from #tbltmpnew where AreaId = @areaid
					
					select @newres = @newres + '<div class="card-content">
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                    <div class="table-responsive" id="htmlData" #htmlData>
					<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
					<tbody>
					<tr>
					<th scope="col"> <span>' + @col1Name + '</span> </th>
					<th scope="col"> <span>' + @col2Name + '</span> </th>				
					<th scope="col"> <span>' + @col3Name + '</span> </th>				
					<th scope="col"> <span>' + @col4Name + '</span> </th>				
					</tr>'
				end
				
				select @col1=isnull(col1,''),@col2=isnull(col2,''),@col3=isnull(col3,''),@col4=isnull(col4,''),@isnormal = isnull(isnormal,0) from #tbltmpnew where tid = @j			
				
				select @resab = @resab + '<tr'+ (case when @isnormal=1 then '' else ' style="color:red"' end)+'>'+'
				<td style="width:25%;"><span title="' + @col1 + '" class="boxEllips" style="display:inline-block;">' + @col1 + '</span> </td>
				<td style="width:25%;"><span title="' + @col2 + '" class="boxEllips" style="display:inline-block;">' + @col2 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col3 + '" class="boxEllips" style="display:inline-block;">' + @col3 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col4 + '" class="boxEllips" style="display:inline-block;">' + @col4 + '</span> </td>			
				</tr>'
				
				if @j = @rescnt
				begin
					select @res = @res + @newres + @resab + '</div></div></tbody></table></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>'
					select @newres = '',@resab = ''				
				end
				
				select @j = @j + 1
			end
			drop table #tbltmpnew
		end		
		
		select @i = @i + 1
	end
		
	select @res = isnull(@res,'')	
	select @res as res
end
GO
PRINT N'Altering Procedure [sExamination].[pExportAdaniExaminations]...';


GO
CREATE OR ALTER PROCEDURE [sExamination].[pExportAdaniExaminations]  
@rOrgId int,  
@rStoreLocationId int,  
@rLocationId int,  
@rSetupGroupId int,  
@rSetupId int,  
@rMainTypeId int,  
@rSectorId int,  
@rVerticalId int,  
@rCompanyGroupId int,  
@rCompanyId int,  
@rEmployeeTypeGroupId int,  
@rEmployeeTypeId int,  
@rEmployeeSubTypeId int,  
@rFromDate varchar(50)='',  
@rTodate varchar(50)='',  
@rCode varchar(200) = null,  
@rLocation nvarchar(max)='',  
@rFromLocationid bigint=0,  
@rToLocationid bigint=0 ,
@rIsBusinessWise bit, -- mantis id - 29445, Nidhi Pandey dt - 09/01/2024 
@rStatusId int = 0,-- mantis id - 31146, Yogesh Banwe dt - 14/02/2024
@rUserId bigint = 0-- mantis id - 43716, Yogesh Banwe dt - 01/12/2025
as  
begin  
 SELECT @rFromDate = case when @rFromDate <> '' then CONVERT(varchar(10), CONVERT(date, @rFromDate, 105), 23) else '' end  
    SELECT @rToDate = case when @rToDate <> '' then CONVERT(varchar(10), CONVERT(date, @rToDate, 105), 23) else '' end  
   
 IF OBJECT_ID('tempdb..#tblExaminationAll') IS NOT NULL  
  DROP TABLE #tblExaminationAll  
    
 create table #tblExaminationAll  
 (  
  tid int identity(1,1),ExaminationId bigint,[Examination Type] varchar(max),[Round Name] varchar(max),  
  [Sub Location] varchar(max),[Examination Date] varchar(max),[Employee Code] varchar(max),[Full Name] varchar(max),  
  Department varchar(max),[Department Group] varchar(max),[Function] varchar(max),Company varchar(max),  
  [Company Group] varchar(max),Vertical varchar(max),Business varchar(max),[Employee Type] varchar(max),  
  Grade varchar(max),Designation varchar(max),BirthDate varchar(max),Age int,[Join Date] varchar(max),  
  Duration int,Gender varchar(max),MobileNo varchar(max),Email varchar(max),BloodGroup varchar(max),  
  Skill varchar(max),ProcessType varchar(max),Height varchar(10),[Weight] varchar(10),BMI varchar(max),  
  MailSend varchar(max),EntryPending varchar(max),comDiagnosis varchar(max),comRecommandEng varchar(max),  
  conFit varchar(max),comUnfit varchar(max),conUnfitDate varchar(max),comUnfitReason varchar(max),  
  comUnfitPeriod varchar(max),comRefitDate varchar(max),Agency varchar(max),Systolic varchar(max),  
  Diastilic varchar(max),Status varchar(max),ProviderName nvarchar(max),HealthIndicator nvarchar(max), 
  ProviderAppointmentStatus nvarchar(max), CentralDoctor nvarchar(max), SiteDoctor nvarchar(max),
  CentralSpoc nvarchar(max), SiteSpoc nvarchar(max))
 insert into #tblExaminationAll  
 select ED.Id,  
 MT.Title,  
 SSM.Title, 
 SLM.Title,  
 convert(varchar,ED.ExaminationDate,103),  
 EM.Code,  
 EM.FirstName + ' ' + isnull(EM.LastName,''),  
 ODM.Title,  
 DM.Title,  
 FM.Title,  
 case when @rOrgId<>3001 then isnull(CM.Title,'') else isnull(LEM.title,'') end,  
 CGM.Title,  
 VM.Title,  
 S.Title,  
 TM.Title,  
 GRD.Title,  
 DGM.Title,  
 CONVERT(VARCHAR,EP.DateOfBirth, 103),  --mantis:0032711 by shivam (05/04/2024)
 datediff(yy,EP.DateOfBirth,getdate()),  
 convert(varchar,EJD.DateOfJoining,103),  
 datediff(yy,EJD.DateOfJoining,getdate()),  
 case EP.GenderId when 1 then 'Male' when 2 then 'Female' when 3 then 'Not Known' end,  
 EC.MobileNumber,  
 EC.CompanyEmail,  
 BGM.Title,  
 SM.Title,  
 PT.Title,  
 case when isnull(V.Height,0) > 0 then V.Height else null end,  
 case when isnull(V.BodyWeight,0) > 0 then V.BodyWeight else null end,  
 case when isnull(V.BMI,0) > 0 then V.BMI else null end,  
 '',  
 '',  
 D.DiagnosisRemark,  
 D.RecommendationEnglish,  
 case when isnull(D.FitUnfitId,1) = 1 then 1 else 0 end,  
 case when isnull(D.FitUnfitId,1) = 1 then 0 else 1 end,  
 case when D.ActionDate <> '1900-01-01' then convert(varchar,D.ActionDate,103) else '' end,  
 D.Reason,  
 '',  
 '',  
 MAM.Title,  
 case when isnull(V.BloodPressureSystolic,0) > 0 then V.BloodPressureSystolic else null end,  
 case when isnull(V.BloodPressureDiastolic,0) > 0 then V.BloodPressureDiastolic else null end , 
  esm.Title, PM.Title, HI.Title, PAS.Title, 
  ISNULL(CD.FirstName, '') + ' ' + ISNULL(CD.LastName, ''), ISNULL(SD.FirstName, '') + ' ' + ISNULL(SD.LastName, ''), 
  ISNULL(CS.FirstName, '') + ' ' + ISNULL(CS.LastName, ''), ISNULL(CS.FirstName, '') + ' ' + ISNULL(CS.LastName, '')
 from sExamination.tExamination ED  
 inner join sExamination.tSetupMaster SSM on ED.SetupId = SSM.Id  
 inner join sExamination.tSubTypeMaster STM on SSM.SubTypeId = STM.Id  
 inner join sExamination.tMainTypeMaster MT on STM.MainTypeId = MT.Id  
 inner join sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id  
 inner join sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id  
 inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=ED.ParticipantSourceId  
 
 left join sExamination.tSetupEmployee SE ON SE.EmployeeId = ED.ParticipantSourceId and SE.SetupId = ED.SetupId
 left join sHrm.tEmployeeMaster CD on CD.Id = SE.CentralDoctorId
 left join sHrm.tEmployeeMaster SD on SD.Id = SE.SiteDoctorId
 left join sHrm.tEmployeeMaster CS on CS.Id = SE.CentralSpocId
 left join sHrm.tEmployeeMaster SS on SS.Id = SE.SiteSpocId
 left join sSupport.tProviderAppointment PA on PA.PatientSourceId = ED.ParticipantSourceId and PA.SetupId = ED.SetupId
 left join sSupport.tProviderMaster PM ON PM.Id = PA.ProviderId
 left join sCommon.tStatusMaster HI ON HI.Id = PA.HealthIndicatorId and HI.StatusTypeId = 122
 left join sCommon.tStatusMaster PAS ON PAS.Id = PA.StatusId and PAS.StatusTypeId = 118
 left join sCommon.tMedicalAgencyMaster MAM on ED.MedicalAgencyId = MAM.Id  
 left join sCommon.tProcessTypeMaster PT on EJD.ProcessTypeId = PT.Id  
 left join sHrm.tEmployeePersonalDetail EP on EP.EmployeeId = ED.ParticipantSourceId  
 left join sCommon.tBloodGroupMaster BGM on EP.BloodGroupId = BGM.Id  
 left join sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id  
 left join sCommon.tDepartmentGroupMaster DM on ODM.DepartmentGroupId=DM.Id  
 left join sCommon.tFunctionMaster FM on FM.Id=DM.FunctionId  
 left join sHrm.tEmployeeCompanyMaster CM on  CM.Id=(case when @rIsBusinessWise=0 then ED.EmployeeCompanyId else EJD.EmployeeCompanyId end)   -- mantis id - 0029445, Nidhi Pandey dt - 09/01/2024     
 left join sHrm.tCompanyGroupMaster CGM on CGM.Id=CM.CompanyGroupId  
 left join sHrm.tVerticalMaster VM on VM.Id=CGM.VerticalId  
 left join sHrm.tSectorMaster S on S.Id=VM.SectorId  
 left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id  
 left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId   
 left join sExamination.tVital V on V.SourceId=ED.Id  
 left join sHrm.tSkillMaster SM on SM.Id= EJD.SkillId  
 left join sExamination.tNatureOfWorkMaster NWM on NWM.Id=V.NatureOfWorkId  
 left join sHrm.tGradeMaster GRD on ED.GradeId = GRD.Id  
 left join sExamination.tDiagnosis D on D.SourceId = ED.Id  
 left join sHrm.tEmployeeDesignationMaster DGM on EJD.EmployeeDesignationId = DGM.Id  
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId  
 left join sHrm.tEmployeeLegalEntitymaster LEM on LEM.Id=ED.LegalEntityId 
 inner join sExamination.tStatusMaster ESM on esm.Id = ed.StatusId
 inner JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId
 where ED.OrgId=@rOrgId and STM.MainTypeId <> 8 and Isnull(EM.IsObsolete,0)=0  
 and ED.ParticipantSourceTypeId = 95  
 and (ED.SetupId = @rSetupId or @rSetupId = 0)  
 and (ED.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)  
 --and (SLM.LocationId = @rLocationId or @rLocationId = 0)  
 and (SSM.SetupGroupId = @rSetupGroupId or @rSetupGroupId = 0)  
 and (STM.MainTypeId = @rMainTypeId or @rMainTypeId = 0)  
 and (ED.EmployeeCompanyId = @rCompanyId or @rCompanyId = 0)  
 and (CM.CompanyGroupId = @rCompanyGroupId or @rCompanyGroupId = 0)  
 and (CGM.VerticalId = @rVerticalId or @rVerticalId = 0)  
 and (VM.SectorId = @rSectorId or @rSectorId = 0)  
 and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)  
 and (TM.Id = @rEmployeeTypeId or @rEmployeeTypeId = 0)  
 and (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId or @rEmployeeSubTypeId = 0)  
 and (datediff(day,@rFromDate,ED.ExaminationDate) >= 0 or isnull(@rFromDate,'') = '')  
 and (datediff(day,ED.ExaminationDate,@rToDate) >= 0 or isnull(@rToDate,'') = '')  
 AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@rCode, '') = ''
)  
 and (ISNULL(SLM.LocationId,0) IN(SELECT item FROM sCommon.fnsplit(@rLocation,',')) OR ISNULL(@rLocation,'')='')  
 and (ED.id>=@rFromLocationid Or @rFromLocationid=0)  
 and (ED.id<=@rToLocationid Or @rToLocationid=0)  
  AND (ED.StatusId = @rStatusId or @rStatusId=0)
   and   UL.UserId = @rUserId 
	order by ED.id asc
 IF OBJECT_ID('tempdb..#tblHabitHygine') IS NOT NULL  
  DROP TABLE #tblHabitHygine  
    
 create table #tblHabitHygine(tid int identity(1,1),h_ExaminationId bigint,h_HabitId int,  
 h_HabitName varchar(300),h_Type int)  
 insert into #tblHabitHygine  
 select ED.Id,HTM.Id,HTM.Title + 'hab',case when isnull(HTM.Title,'')<>'' then 1 else 0 end   
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tHabitHygine HH on ED.Id = HH.SourceId  
 left join sExamination.tHabitHygineDetail HHD on HH.Id = HHD.HabitHygineId  
 left join sExamination.tHabitTypeMaster HTM on HHD.HabitId = HTM.Id  
   
 declare @ExistingCols varchar(max)='',@ExistingCols1 varchar(max)='',@lQueryExisting varchar(max)=''  
 select @ExistingCols = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title + 'hab') from sExamination.tHabitTypeMaster where OrgId = @rOrgId  
  and title in ('Alcohol','Chewer','Smoker')  
        FOR XML PATH(''),TYPE  
     ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
       
    select @ExistingCols1 = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title + 'hab') + ' varchar(300)'  from sExamination.tHabitTypeMaster where OrgId = @rOrgId  
  and title in ('Alcohol','Chewer','Smoker')  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    IF OBJECT_ID('tempdb..##tblHabit') IS NOT NULL  
  DROP TABLE ##tblHabit  
      
 select @lQueryExisting = @lQueryExisting + 'create table ##tblHabit(tid int identity(1,1),t_ExamId bigint,' + @ExistingCols1 + ')'  
   
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblHabit  
 select h_ExaminationId,' + @ExistingCols + '  
 from  
 (  
  select h_ExaminationId,h_HabitName,h_type from #tblHabitHygine  
 ) src   
 pivot  
 (  
   max(h_type) for h_HabitName in (' + @ExistingCols + ')  
 ) piv;'  
    
 exec (@lQueryExisting)  
   
 IF OBJECT_ID('tempdb..#tblExistingDisease') IS NOT NULL  
  DROP TABLE #tblExistingDisease  
   
 create table #tblExistingDisease(tid int identity(1,1),d_ExaminationId bigint,d_DiseaseId int,  
 d_DiseaseName varchar(300),d_type int)  
 insert into #tblExistingDisease  
 select ED.Id,DM.Id,DM.Title,case when isnull(DM.Title,'')<>'' then 1 else 0 end  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tExistingDisease EDD on ED.Id = EDD.SourceId  
 left join sExamination.tExistingDiseaseDetail EDDD on EDD.Id = EDDD.ExistingDiseaseId  
 left join sExamination.tDiseaseMaster DM on EDDD.DiseaseId = DM.Id  
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0  
   
 declare @DiseaseCols varchar(max)='',@DiseaseCols1 varchar(max)=''  
 select @DiseaseCols = '[Disease] varchar(max),OtherDiseaseDetail varchar(max)'  
    
 IF OBJECT_ID('tempdb..##tblDisease') IS NOT NULL  
  DROP TABLE ##tblDisease  
   
 select @lQueryExisting = 'create table ##tblDisease(tid int identity(1,1),d_ExamId bigint,' + @DiseaseCols + ')'  
   
 exec(@lQueryExisting)  
   
 insert into ##tblDisease  
 select d_ExaminationId,'','' from #tblExistingDisease group by d_ExaminationId  
   
 select @DiseaseCols1 = '[Disease],OtherDiseaseDetail'  
   
 declare @dcnt int,@di int  
 select @di = 1,@dcnt = count(*) from ##tblDisease  
   
 while @di <= @dcnt  
 begin  
  declare @dis varchar(max)='',@examinationid bigint,@len int  
  select @examinationid = d_ExamId from ##tblDisease where tid = @di  
  select @dis = @dis + d_DiseaseName + '+' from #tblExistingDisease where d_ExaminationId = @examinationid  
  select @len = len(@dis)  
  select @dis = case when isnull(@dis,'') <> '' then left(@dis,@len-1) else isnull(@dis,'') end  
  update ##tblDisease set [Disease] = @dis where tid = @di    
  select @di = @di + 1  
 end  
   
 IF OBJECT_ID('tempdb..#tblPastHistory') IS NOT NULL  
  DROP TABLE #tblPastHistory  
   
 create table #tblPastHistory(tid int identity(1,1),h_ExaminationId bigint,h_DiseaseId int,  
 h_HistoryName varchar(300),d_type int,d_RelationId int,d_RelationName varchar(300),PastSurgicalHistorySelf varchar(max))  
 insert into #tblPastHistory  
 select ED.Id,DM.Id,DM.Title,case when isnull(DM.Title,'')<>'' then 1 else 0 end,  
 HD.RelationshipId,R.Title + DM.Title, HI.SurgeryRemark
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tHistory HI on ED.ParticipantSourceId = HI.ParticipantSourceId 
			AND ED.ParticipantSourceTypeId = HI.ParticipantSourceTypeId 
 left join sExamination.tHistoryDetail HD on HI.Id = HD.HistoryId  
 left join sExamination.tDiseaseMaster DM on HD.DiseaseId = DM.Id  
 left join sCommon.tRelationshipMaster R on R.Id = HD.RelationshipId  
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0  
   
 declare @HistoryCols varchar(max)='',@HistoryCols1 varchar(max)=''  
 select @HistoryCols = 'phSelf varchar(max),phFather varchar(max),phMother varchar(max),PastMedicalHistorySelf varchar(max),PastSurgicalHistorySelf varchar(max)'  
 select @HistoryCols1 = 'phSelf,phFather,phMother,PastMedicalHistorySelf,PastSurgicalHistorySelf'  
   
 IF OBJECT_ID('tempdb..##tblHistory') IS NOT NULL  
  DROP TABLE ##tblHistory  
   
 select @lQueryExisting = 'create table ##tblHistory(tid int identity(1,1),d_ExamId bigint,' + @HistoryCols + ')'  
   
 exec(@lQueryExisting)  
   
 insert into ##tblHistory  
 select h_ExaminationId,'','','','','' from #tblPastHistory group by h_ExaminationId  ,PastSurgicalHistorySelf
   
 declare @cnt int,@i int  
 select @cnt = COUNT(*),@i = 1 from ##tblHistory  
   
 while @i <= @cnt  
 begin  
  declare @self varchar(max)='',@mother varchar(max)='',@father varchar(max)='',@brother varchar(max)='',@sister varchar(max)='',  
  @ExamId bigint,@len1 int  ,@PastMedicalHistorySelf varchar(max)='' 
  select @ExamId = d_ExamId from ##tblHistory where tid = @i  
  select @self = @self + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 1 and h_ExaminationId = @ExamId 
  select @PastMedicalHistorySelf = @PastMedicalHistorySelf + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 1 and h_ExaminationId = @ExamId 
  select @mother = @mother + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 3 and h_ExaminationId = @ExamId  
  select @father = @father + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 2 and h_ExaminationId = @ExamId  
  select @brother = @brother + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 7 and h_ExaminationId = @ExamId  
  select @sister = @sister + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 8 and h_ExaminationId = @ExamId  
    
  select @len1 = len(@self)  
  select @self = case when isnull(@self,'') <> '' then left(@self,@len1-1) else isnull(@self,'') end  
    select @PastMedicalHistorySelf = case when isnull(@PastMedicalHistorySelf,'') <> '' then left(@PastMedicalHistorySelf,@len1-1) else isnull(@PastMedicalHistorySelf,'') end  
    
  select @len1 = len(@mother)  
  select @mother = case when isnull(@mother,'') <> '' then left(@mother,@len1-1) else isnull(@mother,'') end  
    
  select @len1 = len(@father)  
  select @father = case when isnull(@father,'') <> '' then left(@father,@len1-1) else isnull(@father,'') end  
     
    
  update ##tblHistory set phSelf = @self,phMother = @mother,phFather = @father where tid = @i    
  select @i = @i + 1  
 end  
   
 create table #tblExaminationTests(tid int identity(1,1),g_ExaminationId bigint,  
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))  
 insert into #tblExaminationTests  
 select ED.Id,GED.ServiceValue,GED.Remark,GP.Title  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId   
 left join sExamination.tTestRequest GE on ED.Id = GE.SourceId  
 left join sExamination.tTestRequestDetail GED on GE.Id = GED.TestRequestId  
 left join sOrderEntry.tTestDetail TD on TD.Id = GED.TestDetailId  
 left join sOrderEntry.tTestParameterMaster GP on GP.Id = TD.TestParameterId  
 where GP.IsObsolete = 0  
   
 declare @tblExaminationT table(tid int identity(1,1),t_Exid bigint)  
 insert into @tblExaminationT  
 select distinct g_ExaminationId from #tblExaminationTests  
   
 declare @tIncr int,@tCnt int  
 select @tIncr = 1,@tCnt = count(*) from @tblExaminationT  

--------------------------------------- OLD --------------------------------------   
 --while @tIncr <= @tCnt  
 --begin  
 -- declare @tExamId bigint,@tRem varchar(200)=''  
 -- select @tExamId = t_Exid from @tblExaminationT where tid = @tIncr  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SMEAR STUDY'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','SMEAR STUDY_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'XRAY'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','XRAY_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SONOGRAPHY'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','SONOGRAPHY_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECG'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','ECG_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECHO'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','ECHO_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'TMT'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','TMT_Remark'  
    
 -- select @tIncr = @tIncr + 1  
 --end 
 --------------------------------------- OLD END--------------------------------------

 --------------------------------------- NEW OPtimized (Added by NP; Dt - 09/04/2025 mantis - 0041715)--------------------------------------
 insert into #tblExaminationTests
select 
    t.t_Exid as g_ExaminationId,
    -- Use CASE to get the remarks based on title
    CASE 
        WHEN tt.g_Title = 'SMEAR STUDY' THEN tt.g_Remark
        WHEN tt.g_Title = 'XRAY' THEN tt.g_Remark
        WHEN tt.g_Title = 'SONOGRAPHY' THEN tt.g_Remark
        WHEN tt.g_Title = 'ECG' THEN tt.g_Remark
        WHEN tt.g_Title = 'ECHO' THEN tt.g_Remark
        WHEN tt.g_Title = 'TMT' THEN tt.g_Remark
        ELSE '' -- Default empty remark if no title matches
    END as g_Remark,
	'',
    -- Set custom title for the remarks
    CASE 
        WHEN tt.g_Title = 'SMEAR STUDY' THEN 'SMEAR STUDY_Remark'
        WHEN tt.g_Title = 'XRAY' THEN 'XRAY_Remark'
        WHEN tt.g_Title = 'SONOGRAPHY' THEN 'SONOGRAPHY_Remark'
        WHEN tt.g_Title = 'ECG' THEN 'ECG_Remark'
        WHEN tt.g_Title = 'ECHO' THEN 'ECHO_Remark'
        WHEN tt.g_Title = 'TMT' THEN 'TMT_Remark'
        ELSE ''
    END as g_Title
from 
    @tblExaminationT t
join 
    #tblExaminationTests tt on t.t_Exid = tt.g_ExaminationId
where 
    tt.g_Title in ('SMEAR STUDY', 'XRAY', 'SONOGRAPHY', 'ECG', 'ECHO', 'TMT');

--------------------------------------- NEW OPtimized END (Added by NP; Dt - 09/04/2025 mantis - 0041715) --------------------------------------
   
 declare @TestCols varchar(max)='',@TestCols1 varchar(max)=''  
 select @TestCols = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   19,20,21,22,23,24  
  )  
  and IsObsolete = 0  
   FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   19,20,21,22,23,24  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   31,32,33,34,38,43,49  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   31,32,33,34,38,43,49  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
          
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   26,27  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   26,27  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   2,8,17  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   2,8,17  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   9,10,11,12,13  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   9,10,11,12,13  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   3,15  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   3,15  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT CASE StaticTestParameterId WHEN 16 THEN ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark')  
  ELSE ',' + QUOTENAME(Title) END  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   5,16,58,64,65,69,72,73  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT CASE StaticTestParameterId WHEN 16 THEN ',' + QUOTENAME(Title) + ' varchar(400)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(400)'  
  ELSE ',' + QUOTENAME(Title) + ' varchar(400)' END  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   5,16,58,64,65,69,72,73  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   71  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   71  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   67,68,70,113  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   67,68,70,113  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   56,57,94  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   56,57,94  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark') from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   107,108,109  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(400)'  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   107,108,109  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
 ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark') from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   104,105  
  )  
  and IsObsolete = 0 order by Id  
  FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(400)'  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   104,105  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
 declare @TestColsNew varchar(max)='',@TestColsNew1 varchar(max)=''  
 select @TestColsNew = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   25,54,126,127   
  )  
  and IsObsolete = 0  
   FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestColsNew1 = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   25,54,126,127  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
 ---new Tests  
 select @TestColsNew = @TestColsNew + ',' + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   39,40,41,42,44,48,52,53,148,158,159  
  )  
  and IsObsolete = 0  
   FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestColsNew1 = @TestColsNew1 + ',' + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   39,40,41,42,44,48,52,53,148,158,159  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
 --  
   
 IF OBJECT_ID('tempdb..##tblTests') IS NOT NULL  
  DROP TABLE ##tblTests  
   
 select @lQueryExisting = 'create table ##tblTests(tid int identity(1,1),d_ExamId bigint,' + @TestCols1 + ',' + @TestColsNew1 + ')'  
 print @lQueryExisting  
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblTests  
 select g_ExaminationId,' + @TestCols + ',' + @TestColsNew + '  
 from  
 (  
  select g_ExaminationId,g_Value,g_Title from #tblExaminationTests group by g_ExaminationId,g_Value,g_Remark,g_Title  
 ) src   
 pivot  
 (  
   max(g_Value) for g_Title in (' + @TestCols  + ',' + @TestColsNew + ')  
 ) piv;'  
 print @lQueryExisting  
 exec (@lQueryExisting)  
   
 IF OBJECT_ID('tempdb..#tblExaminationGeneralTemplates') IS NOT NULL  
  DROP TABLE #tblExaminationGeneralTemplates  
   
 create table #tblExaminationGeneralTemplates(tid int identity(1,1),g_ExaminationId bigint,  
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))  
 insert into #tblExaminationGeneralTemplates  
 select ED.Id,GED.ParameterValue,GED.Remark,GP.Title  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId   
 left join sExamination.tGeneralTemplateExamination GE on ED.Id = GE.SourceId  
 left join sExamination.tGeneralTemplateExaminationDetail GED on GE.Id = GED.GeneralTemplateExaminationId  
 left join sExamination.tGeneralTemplateParameter GP on GP.Id = GED.GeneralTEmplateParameterId  
 where GP.IsObsolete = 0 and GP.StaticGeneralTemplateParameterId = 328  
   
 declare @GeneralCols varchar(max)='',@GeneralCols1 varchar(max)=''  
 select @GeneralCols = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title)  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0  
  and StaticGeneralTemplateParameterId in (328)  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
       
    select @GeneralCols1 = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title) + ' varchar(300)'  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0  
  and StaticGeneralTemplateParameterId in (328)  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    IF OBJECT_ID('tempdb..##tblGeneral') IS NOT NULL  
  DROP TABLE ##tblGeneral  
      
 select @lQueryExisting = 'create table ##tblGeneral(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'  
   
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblGeneral  
 select g_ExaminationId,' + @GeneralCols + '  
 from  
 (  
  select g_ExaminationId,g_Value,g_Title from #tblExaminationGeneralTemplates group by g_ExaminationId,g_Value,g_Remark,g_Title  
 ) src   
 pivot  
 (  
   max(g_Value) for g_Title in (' + @GeneralCols + ')  
 ) piv;'  
   
 exec (@lQueryExisting)  
   
 IF OBJECT_ID('tempdb..#tblExaminationAudiometrys') IS NOT NULL  
  DROP TABLE #tblExaminationAudiometrys  
   
 create table #tblExaminationAudiometrys(tid int identity(1,1),AudiometryId bigint,ExaminationId bigint,IsDoneLeft bit,  
 IsDoneRight bit,AcValueLeft int,AcValueRight int,FrequencyId int,AudiometryAcResultLeftId int,AudiometryAcResultRightId int,  
 AudiometryResultRemarkLeftId nvarchar(200),AudiometryResultRemarkRightId nvarchar(200))  
 insert into #tblExaminationAudiometrys  
 select ISNULL(A.Id,0) AS AudiometryId,ED.Id,  
 ISNULL(A.IsDoneLeft,0) AS IsDoneLeft,  
 ISNULL(A.IsDoneRight,0) AS IsDoneRight,  
 AD.AcValueLeft AS AcValueLeft,  
 AD.AcValueRight AS AcValueRight,  
 ISNULL(AD.FrequencyId,0) AS FrequencyId,  
 ISnull(A.AudiometryAcResultLeftId,0) AS AudiometryAcResultLeftId,  
 ISnull(A.AudiometryAcResultRightId,0) AS AudiometryAcResultRightId,  
 ISnull(A.AudiometryResultRemarkLeftId,0) AS AudiometryResultRemarkLeftId,  
 ISnull(A.AudiometryResultRemarkRightId,0) AS AudiometryResultRemarkRightId  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll AA on ED.Id = AA.ExaminationId  
 left join sExamination.tAudiometry A on A.SourceId = ED.Id  
 left join sExamination.tAudiometryDetail AD on AD.AudiomentryId = A.Id  
 left join sExamination.tAudiometryResultMaster RM on A.AudiometryAcResultLeftId = RM.Id  
 left join sExamination.tAudiometryResultMaster RM1 on A.AudiometryBcResultLeftId = RM.Id  
 left join sExamination.tAudiometryResultMaster RM2 on A.AudiometryAcResultRightId = RM.Id  
 left join sExamination.tAudiometryResultMaster RM3 on A.AudiometryBcResultRightId = RM.Id   
   
 IF OBJECT_ID('tempdb..##tblAudiometry') IS NOT NULL  
  DROP TABLE ##tblAudiometry  
   
 select @lQueryExisting = 'create table ##tblAudiometry(a_ExamId bigint,IsDoneLeft bit,  
 AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),  
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),  
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),  
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200))'  
   
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblAudiometry(a_ExamId,IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,  
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,R250,R500,R1000,R2000,R4000,R6000,R8000)  
 Select LeftPivot.ExaminationId,CASE WHEN LeftPivot.IsDoneLeft = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneLeft,  
 ISNULL(LeftPivot.AudiometryAcResultLeft,'''') as AudiometryAcResultLeft,  
 ISNULL(LeftPivot.AudiometryResultRemarkLeft,'''') as AudiometryResultRemarkLeft,  
 LeftPivot.[250] as L250,LeftPivot.[500] as L500,LeftPivot.[1000] as L1000,LeftPivot.[2000] as L2000,  
 LeftPivot.[4000] as L4000,LeftPivot.[6000] as L6000,LeftPivot.[8000] as L8000,  
 CASE WHEN RightPivot.IsDoneRight = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneRight,  
 RightPivot.AudiometryAcResultRight as AudiometryAcResultRight,  
 RightPivot.AudiometryResultRemarkRight as AudiometryResultRemarkRight,  
 RightPivot.[250] as R250,RightPivot.[500] as R500,RightPivot.[1000] as R1000,RightPivot.[2000] as R2000,  
 RightPivot.[4000] as R4000,RightPivot.[6000] as R6000,RightPivot.[8000] as R8000  
 From  
 (  
  select pvt.AudiometryId AS AudiometryId,  
  ISNULL(pvt.AudiometryLeftResult,'''') AS AudiometryAcResultLeft,  
  ISNULL(pvt.AudiometryLeftRemark,'''') AS AudiometryResultRemarkLeft,  
  pvt.IsDoneLeft,pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]  
  from  
  (  
   Select AudiometryId,TC.ExaminationId,IsDoneLeft,AcValueLeft,  
   FrequencyId,RS.Title AS AudiometryLeftResult,  
   RM.Title AS AudiometryLeftRemark  
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultLeftId  
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkLeftId  
  )t   
  PIVOT (MIN(AcValueLeft) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])) AS pvt  
 ) LeftPivot  
 INNER JOIN  
 (  
  select pvt.AudiometryId AS AudiometryId,  
  ISNULL(pvt.AudiometryRightResult,'''') AS AudiometryAcResultRight,  
  ISNULL(pvt.AudiometryRightRemark,'''') AS AudiometryResultRemarkRight, pvt.IsDoneRight,  
  pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]  
  from  
  (  
   Select AudiometryId,TC.ExaminationId,IsDoneRight,AcValueRight,  
   FrequencyId,RS.Title AS AudiometryRightResult,  
   RM.Title AS AudiometryRightRemark  
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultRightId  
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkRightId  
  )t  
  PIVOT (MIN(AcValueRight) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])  
 ) AS pvt ) RightPivot ON LeftPivot.ExaminationId = RightPivot.ExaminationId'  
   
 exec (@lQueryExisting)  
   
 declare @lMainQuery varchar(max)=''  
   
 IF OBJECT_ID('tempdb..##tblMainExamination1') IS NOT NULL  
  DROP TABLE ##tblMainExamination1  
   
 select @lMainQuery = 'create table ##tblMainExamination1(ExaminationId bigint,[Examination Type] varchar(max),[Round Name] varchar(max),
 [Sub Location] varchar(max),[Examination Date] varchar(max),[Employee Code] varchar(max),[Full Name] varchar(max),  
 Department varchar(max),[Department Group] varchar(max),[Function] varchar(max),Company varchar(max),  
 [Company Group] varchar(max),Vertical varchar(max),Business varchar(max),[Employee Type] varchar(max),  
 Grade varchar(max),Designation varchar(max),BirthDate varchar(max),Age int,[Join Date] varchar(max),  
 Duration int,Gender varchar(max),MobileNo varchar(max),Email varchar(max),BloodGroup varchar(max),  
 Skill varchar(max),ProcessType varchar(max),Height varchar(max),[Weight] varchar(max),BMI varchar(max),  
 ' + case when @ExistingCols1 is not null then isnull(@ExistingCols1,'') + ',' else '' end + '  
 ' + case when @DiseaseCols is not null then isnull(@DiseaseCols,'') + ',' else '' end + '  
 ' + case when @HistoryCols is not null then isnull(@HistoryCols,'') + ',' else '' end + 'Systolic varchar(max),Diastilic varchar(max),  Status varchar(max) ,
 ' + case when @TestCols1 is not null then isnull(@TestCols1,'') + ',' else '' end +'  
 ' + case when @GeneralCols1 is not null then isnull(@GeneralCols1,'') + ',' else '' end + '  
 FVCPredicted varchar(200),FVCObserved varchar(200),PerOfPredictedFVC varchar(200),FEV1Predicted varchar(200),FEV1Observed varchar(200),  
 PerOfFEV1 varchar(200),PerOfFEV1ByFVC varchar(200),FEV5Observed varchar(200),PerOfFEV1ByFEV5 varchar(200),  
 MVVObserved varchar(200),MVVPredicted varchar(200),PerOfMVV varchar(200),PEFRPredicted varchar(200),  
 PEFRObserved varchar(200),PerPEFR varchar(200),PulmonaryResult varchar(200),NotDoneReason varchar(50),  
 IsDoneLeft bit,AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),  
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),  
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),  
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200),  
 MailSend varchar(50),EntryPending varchar(50),comDiagnosis varchar(max),comRecommandEng varchar(max),  
 conFit varchar(10),comUnfit varchar(10),conUnfitDate varchar(50),comUnfitReason varchar(max),  
 comUnfitPeriod varchar(10),comRefitDate varchar(50),Agency varchar(300),  
 ' + case when @TestColsNew1 is not null then isnull(@TestColsNew1,'') + '' else '' end + ',ProviderName nvarchar(max),
 HealthIndicator nvarchar(max),ProviderAppointmentStatus nvarchar(max),CentralDoctor nvarchar(max), SiteDoctor nvarchar(max),
 CentralSpoc nvarchar(max), SiteSpoc nvarchar(max)' + ')'
   
 select @lMainQuery = replace(@lMainQuery,'OVA','Stool for ova and cyst')  
 print @lMainQuery  
 exec(@lMainQuery)  
   
 declare @lMainExecuteQuery varchar(max)=''   
   
 select @lMainExecuteQuery = 'insert into ##tblMainExamination1 select ExaminationId,[Examination Type],[Round Name], 
 [Sub Location],[Examination Date],[Employee Code],[Full Name],Department,[Department Group],[Function],Company,  
 [Company Group],Vertical,Business,[Employee Type],Grade,Designation,BirthDate,Age,[Join Date],  
 Duration,Gender,MobileNo,Email,BloodGroup,Skill,ProcessType,Height,[Weight],BMI,  
 ' + @ExistingCols + ',' + @DiseaseCols1 + ',' + @HistoryCols1 + ',Systolic,Diastilic,Status,' + @TestCols + ',' + @GeneralCols + ',  
 FVCPredicted,FVCObserved,PerOfPredictedFVC,FEV1Predicted,FEV1Observed,PerOfFEV1,PerOfFEV1ByFVC,FEV5Observed,PerOfFEV1ByFEV5,  
 MVVObserved,MVVPredicted,PerOfMVV,PEFRPredicted,PEFRObserved,PerPEFR,  
 PulmonaryResult = P.PulmonaryResulIntensity + '' '' + P.PulmonaryResult,'''',  
 IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,L1000,L2000,L4000,L6000,L8000,  
 IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,R250,R500,R1000,R2000,R4000,R6000,R8000,  
 MailSend,EntryPending,comDiagnosis,comRecommandEng,conFit,comUnfit,conUnfitDate,comUnfitReason,  
 comUnfitPeriod,comRefitDate,Agency,' + @TestColsNew + ',ProviderName,HealthIndicator,ProviderAppointmentStatus,
 CentralDoctor,SiteDoctor,CentralSpoc,SiteSpoc' + '
 from #tblExaminationAll EA  
 left join tempdb.##tblHabit EE on EA.ExaminationId = EE.t_ExamId  
 left join tempdb.##tblDisease ED on EA.ExaminationId = ED.d_ExamId  
 left join tempdb.##tblHistory HE on EA.ExaminationId = HE.d_ExamId  
 left join tempdb.##tblGeneral GE on EA.ExaminationId = GE.d_ExamId  
 left join tempdb.##tblTests TE on EA.ExaminationId = TE.d_ExamId  
 left join tempdb.##tblAudiometry AA on EA.ExaminationId = AA.a_ExamId  
 left join sExamination.tPulmonary P on EA.ExaminationId = P.SourceId'  
   
 print @lMainExecuteQuery  
 exec (@lMainExecuteQuery)  
   
 update ##tblMainExamination1 set OtherDiseaseDetail = Remark from sExamination.tExistingDisease where ExaminationId = SourceId  
   
 select * from  ##tblMainExamination1  
end
GO
PRINT N'Altering Procedure [sExamination].[pExportAllExaminations]...';


GO
CREATE OR ALTER PROCEDURE [sExamination].[pExportAllExaminations]
@rOrgId int,     
@rStoreLocationId int,    
@rLocationId int,    
@rSetupGroupId int,    
@rSetupId int,    
@rMainTypeId int,    
@rSectorId int,    
@rVerticalId int,    
@rCompanyGroupId int,    
@rCompanyId int,    
@rEmployeeTypeGroupId int,    
@rEmployeeTypeId int,    
@rEmployeeSubTypeId int,    
@rFromDate datetime='',    
@rTodate datetime='',    
@rCode varchar(200) = null,    
@rLocation nvarchar(max)='',    
@rContractorId int = 0,    
@rIsBusinessWise bit, -- mantis id - 29445, Nidhi Pandey dt - 09/01/2024     
@rStatusId int = 0, -- mantis id - 31146, Yogesh Banwe dt - 14/02/2024    
@rTargetGroupId int = 0,-- mantis id - 32870, Yogesh Banwe dt - 12/04/2024   
@rColumnName nvarchar(max)='',-- mantis id - 43716, Yogesh Banwe dt - 08/08/2025
@rUserId bigint -- mantis id - 43716, Yogesh Banwe dt - 24/11/2025
as    
begin    
 IF OBJECT_ID('tempdb..##tblExaminationAll') IS NOT NULL    
 DROP TABLE #tblExaminationAll    
     
 create table #tblExaminationAll(tid int identity(1,1),ExaminationId bigint,ParticipantSourceId bigint,RoundName varchar(200),    
 StorelocationName varchar(500),LocationName varchar(500),FunctionName varchar(500),DepartmentGroup varchar(500),Department varchar(500),    
 Company varchar(500),ExaminationType varchar(500),EmployeeType varchar(500),EmpNo varchar(500),FullName varchar(500),BirthDate varchar(500),    
 DateOfJoining varchar(500),Gender varchar(500),Mobilenumber varchar(500),Companyemail varchar(500),ExaminationDate varchar(500),    
 RoungNumber int,Age int,EmployeeDesignation varchar(500),Skill varchar(500),NatureOfWork varchar(500),Height int,Weight float,    
 BMI float,Grade varchar(300),BPSys varchar(200),BPDia varchar(200),Diagnosis varchar(max),Recommendation varchar(max),    
 comUnfit int,comUnfitDate varchar(500),comUnfitReason varchar(500),comUnfitPeriod varchar(300),comRefitDate varchar(500),Contractor varchar(500),Status varchar(500),TargetGroup varchar(500),ProcessType varchar(100))    
     
 IF OBJECT_ID('tempdb..##tblExisiting') IS NOT NULL    
 DROP TABLE ##tblExisiting    
     
 IF OBJECT_ID('tempdb..#tblExaminationExisiting') IS NOT NULL    
 DROP TABLE #tblExaminationExisiting    
      
 IF OBJECT_ID('tempdb..#tblExaminationDisease') IS NOT NULL    
 DROP TABLE #tblExaminationDisease    
     
 IF OBJECT_ID('tempdb..##tblDisease') IS NOT NULL    
 DROP TABLE ##tblDisease    
     
 IF OBJECT_ID('tempdb..#tblExaminationHistory') IS NOT NULL    
 DROP TABLE #tblExaminationHistory    
     
 IF OBJECT_ID('tempdb..##tblHistory') IS NOT NULL    
 DROP TABLE ##tblHistory    
     
 IF OBJECT_ID('tempdb..#tblExaminationGeneralTemplates') IS NOT NULL    
 DROP TABLE #tblExaminationGeneralTemplates    
     
 IF OBJECT_ID('tempdb..##tblGeneral') IS NOT NULL    
 DROP TABLE ##tblGeneral    
     
 IF OBJECT_ID('tempdb..#tblExaminationTests') IS NOT NULL    
 DROP TABLE #tblExaminationTests    
     
 IF OBJECT_ID('tempdb..##tblTests') IS NOT NULL    
 DROP TABLE ##tblTests    
     
 IF OBJECT_ID('tempdb..##tblMainTable1') IS NOT NULL    
 DROP TABLE ##tblMainTable1    
     
 IF OBJECT_ID('tempdb..#tblExaminationAudiometrys') IS NOT NULL    
 DROP TABLE #tblExaminationAudiometrys    
     
 IF OBJECT_ID('tempdb..##tblAudiometrys') IS NOT NULL    
 DROP TABLE ##tblAudiometrys    
     
 IF OBJECT_ID('tempdb..##tblAudiometry') IS NOT NULL    
 DROP TABLE ##tblAudiometry    
     
 insert into #tblExaminationAll    
 select ED.Id,    
 ED.ParticipantSourceId,    
 SSM.Title,    
 SLM.Title,    
 LM.Title,    
 FM.Title as FunctionName,    
 DM.Title as DepartmentGroup,    
 ODM.Title,    
 case when @rOrgId<>9999 then isnull(CM.Title,'') else isnull(LEM.title,'') end as Company,    
 MT.Title as ExaminationType,    
 ETM.Title as EmployeeType,    
 EM.Code as EmpNo,    
 EM.FirstName + ' ' + isnull(EM.LastName,'') as FullName,    
 CONVERT(VARCHAR, EP.DateOfBirth, 103) as BirthDate, --mantis:0032711 by shivam (05/04/2024)    
 CONVERT(VARCHAR, EJD.DateOfJoining, 103) as DateOfJoining, --mantis:0032711 by shivam (05/04/2024)    
 case EP.GenderId when 1 then 'Male' when 2 then 'Female' when 3 then 'Not Known' end,    
 EC.MobileNumber,    
 EC.CompanyEmail,    
 CONVERT(VARCHAR,ED.ExaminationDate, 103) as ExaminationDate, --mantis:0032711 by shivam (05/04/2024)    
 ED.RoundNumber,    
 datediff(yy,EP.DateOfBirth,getdate()),    
 DGM.Title,    
 SM.Title as Skill,    
 NWM.Title as NatureOfWork,    
 case when isnull(V.Height,0) > 0 then V.Height else null end,    
 case when isnull(V.BodyWeight,0) > 0 then V.BodyWeight else null end,    
 case when isnull(V.BMI,0) > 0 then V.BMI else null end,    
 GRD.Title,    
 case when isnull(V.BloodPressureSystolic,0) > 0 then V.BloodPressureSystolic else null end,    
 case when isnull(V.BloodPressureDiastolic,0) > 0 then V.BloodPressureDiastolic else null end,    
 D.DiagnosisRemark,D.RecommendationEnglish,    
 case when isnull(D.FitUnfitId,1) = 1 then 0 else 1 end,case when D.ActionDate <> '1900-01-01' then D.ActionDate else null end,    
 D.Reason,    
 '',    
 '',    
 VMR.Id,    
 esm.Title,    
 TGM.Title,
 ISNULL(PTM.Title,'') as ProcessType
 from sExamination.tExamination ED    
 inner join sExamination.tSetupMaster SSM on ED.SetupId = SSM.Id    
 inner join sExamination.tSubTypeMaster STM on SSM.SubTypeId = STM.Id    
 inner join sExamination.tMainTypeMaster MT on STM.MainTypeId = MT.Id    
 inner join sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id    
 inner join sCommon.tLocationMaster LM on SLM.LocationId = LM.Id    
 inner join sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id    
 inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=ED.ParticipantSourceId    
     
 left join sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id    
 left join sCommon.tDepartmentGroupMaster DM on ODM.DepartmentGroupId=DM.Id    
 left join sCommon.tFunctionMaster FM on FM.Id=DM.FunctionId    
 left join sHrm.tEmployeeCompanyMaster CM on  CM.Id=(case when @rIsBusinessWise=0 then ED.EmployeeCompanyId else EJD.EmployeeCompanyId end)   -- mantis id - 0029445, Nidhi Pandey dt - 09/01/2024         
 left join sHrm.tCompanyGroupMaster CGM on CGM.Id=CM.CompanyGroupId    
 left join sHrm.tVerticalMaster VM on VM.Id=CGM.VerticalId    
 left join sHrm.tSectorMaster S on S.Id=VM.SectorId    
 left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id    
 left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId    
 left join sExamination.tVital V on V.SourceId=ED.Id    
 left join sHrm.tSkillMaster SM on SM.Id= EJD.SkillId    
 left join sExamination.tNatureOfWorkMaster NWM on NWM.Id=V.NatureOfWorkId    
 left join sHrm.tGradeMaster GRD on ED.GradeId = GRD.Id    
 left join sExamination.tDiagnosis D on D.SourceId = ED.Id    
 left join sHrm.tEmployeePersonalDetail EP on EP.EmployeeId = ED.ParticipantSourceId    
 left join sHrm.tEmployeeDesignationMaster DGM on EJD.EmployeeDesignationId = DGM.Id    
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId    
 left join sHrm.tEmployeeLegalEntitymaster LEM on LEM.Id=ED.LegalEntityId    
 LEFT JOIN sProcurement.tVendorMaster VMR ON VMR.Id=EJD.ContractorId     
 inner join sExamination.tStatusMaster ESM on esm.Id = ed.StatusId    
 left join sHrm.tTargetGroupMaster TGM on TGM.Id = ED.Targetgroupid    
  LEFT join sCommon.tProcessTypeMaster PTM ON PTM.Id=ED.ProcessTypeId --mantis id : 45202 ,dev : Yogesh Banwe,date : 26/06/2025
	inner JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId 
 where ED.OrgId=@rOrgId and STM.MainTypeId <> 8    
 and (SetupId = @rSetupId or @rSetupId = 0)    
 and (ED.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)    
 --and (SLM.LocationId = @rLocationId or @rLocationId = 0)    
 and (SSM.SetupGroupId = @rSetupGroupId or @rSetupGroupId = 0)    
 and (STM.MainTypeId = @rMainTypeId or @rMainTypeId = 0)    
 and (ED.EmployeeCompanyId = @rCompanyId or @rCompanyId = 0)    
 and (CM.CompanyGroupId = @rCompanyGroupId or @rCompanyGroupId = 0)    
 and (CGM.VerticalId = @rVerticalId or @rVerticalId = 0)    
 and (VM.SectorId = @rSectorId or @rSectorId = 0)    
 and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)    
 and (TM.Id = @rEmployeeTypeId or @rEmployeeTypeId = 0)    
 and (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId or @rEmployeeSubTypeId = 0)    
 and (datediff(day,@rFromDate,ED.ExaminationDate) >= 0 or isnull(@rFromDate,'') = '')    
 and (datediff(day,ED.ExaminationDate,@rToDate) >= 0 or isnull(@rToDate,'') = '')    
 AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@rCode, '') = ''
)    
 and (ISNULL(SLM.LocationId,0) IN(SELECT item FROM sCommon.fnsplit(@rLocation,',')) OR ISNULL(@rLocation,'')='')    
 AND (VMR.Id = @rContractorId or @rContractorId=0)     
 AND (ED.StatusId = @rStatusId or @rStatusId=0)     
 AND (ED.TargetGroupId = @rTargetGroupId or @rTargetGroupId=0)
 and   UL.UserId = @rUserId 
 order by ED.id asc    
    
 create table #tblExaminationExisiting(tid int identity(1,1),e_ExaminationId bigint,e_HabitId int,    
 DurationId int,e_HabitName varchar(300),e_type int)    
 insert into #tblExaminationExisiting    
 select ED.Id,HTM.Id,HHD.DurationUnitId,HTM.Title,case when isnull(HTM.Title,'')<>'' then 1 else 0 end     
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId    
 left join sExamination.tHabitHygine HH on ED.Id = HH.SourceId    
 left join sExamination.tHabitHygineDetail HHD on HH.Id = HHD.HabitHygineId    
 left join sExamination.tHabitTypeMaster HTM on HHD.HabitId = HTM.Id    
     
 declare @ExistingCols varchar(max)='',@ExistingCols1 varchar(max)='',@lQueryExisting varchar(max)=''    
 select @ExistingCols = STUFF(    
 (    
  SELECT Distinct ',' + QUOTENAME(Title)  from sExamination.tHabitTypeMaster where OrgId = @rOrgId    
  and title in ('Alcohol','Chewer','Smoker')    
        FOR XML PATH(''),TYPE    
     ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
         
     select @ExistingCols1 = STUFF(    
 (    
  SELECT Distinct ',' + QUOTENAME(Title) + ' varchar(300)'  from sExamination.tHabitTypeMaster where OrgId = @rOrgId    
  and title in ('Alcohol','Chewer','Smoker')    
        FOR XML PATH(''),TYPE    
     ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
 select @lQueryExisting = @lQueryExisting + 'create table ##tblExisiting(tid int identity(1,1),t_ExamId bigint,' + @ExistingCols1 + ')'    
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '    
 insert into ##tblExisiting    
 select e_ExaminationId,' + @ExistingCols + '    
 from    
 (    
  select e_ExaminationId,e_HabitName,e_type from #tblExaminationExisiting      
 ) src     
 pivot    
 (    
   max(e_type) for e_HabitName in (' + @ExistingCols + ')    
 ) piv;'    
      
 exec (@lQueryExisting)    
     
 create table #tblExaminationDisease(tid int identity(1,1),d_ExaminationId bigint,d_DiseaseId int,    
 d_DiseaseName varchar(300),d_type int)    
 insert into #tblExaminationDisease    
 select ED.Id,DM.Id,DM.Title,case when isnull(DM.Title,'')<>'' then 1 else 0 end    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId    
 left join sExamination.tExistingDisease EDD on ED.Id = EDD.SourceId    
 left join sExamination.tExistingDiseaseDetail EDDD on EDD.Id = EDDD.ExistingDiseaseId    
 left join sExamination.tDiseaseMaster DM on EDDD.DiseaseId = DM.Id    
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0    
     
 declare @DiseaseCols varchar(max)='',@DiseaseCols1 varchar(max)=''    
 select @DiseaseCols = '[Disease Self] varchar(max)'    
     
 select @lQueryExisting = 'create table ##tblDisease(tid int identity(1,1),d_ExamId bigint,' + @DiseaseCols + ')'    
 exec(@lQueryExisting)    
     
 insert into ##tblDisease    
 select d_ExaminationId,'' from #tblExaminationDisease group by d_ExaminationId    
     
 select @DiseaseCols1 = '[Disease Self]'    
     
 declare @dcnt int,@di int    
 select @di = 1,@dcnt = count(*) from ##tblDisease    
     
 while @di <= @dcnt    
 begin    
  declare @dis varchar(max)='',@examinationid bigint,@len int    
  select @examinationid = d_ExamId from ##tblDisease where tid = @di    
  select @dis = @dis + d_DiseaseName + '+' from #tblExaminationDisease where d_ExaminationId = @examinationid    
  select @len = len(@dis)    
  select @dis = case when isnull(@dis,'') <> '' then left(@dis,@len-1) else isnull(@dis,'') end    
  update ##tblDisease set [Disease Self] = @dis where tid = @di    
      
  select @di = @di + 1    
 end     
      
 create table #tblExaminationHistory(tid int identity(1,1),h_ExaminationId bigint,h_DiseaseId int,    
 h_HistoryName varchar(300),d_type int,d_RelationId int,d_RelationName varchar(300),PastSurgicalHistorySelf varchar(max),PastMedicalHistorySelf varchar(max))     --added by shiv thapa mantis id:0041632
 insert into #tblExaminationHistory    
 select ED.Id,DM.Id,DM.Title,case when isnull(DM.Title,'')<>'' then 1 else 0 end,    
 HD.RelationshipId,R.Title + DM.Title , HI.SurgeryRemark,ED.PastHistorySelf    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId    
 left join sExamination.tHistory HI on ED.ParticipantSourceId = HI.ParticipantSourceId
			AND ED.ParticipantSourceTypeId = HI.ParticipantSourceTypeId
 left join sExamination.tHistoryDetail HD on HI.Id = HD.HistoryId    
 left join sExamination.tDiseaseMaster DM on HD.DiseaseId = DM.Id    
 left join sCommon.tRelationshipMaster R on R.Id = HD.RelationshipId    
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0    
     
 declare @HistoryCols varchar(max)='',@HistoryCols1 varchar(max)=''    
 select @HistoryCols = 'PastHistorySelf varchar(max),PastHistoryMother varchar(max),PastHistoryFather varchar(max),    
 PastHistoryBrother varchar(max),PastHistorySister varchar(max),PastMedicalHistorySelf varchar(max),PastSurgicalHistorySelf varchar(max)'    
 select @HistoryCols1 = 'PastHistorySelf,PastHistoryMother,PastHistoryFather,PastHistoryBrother,PastHistorySister,PastMedicalHistorySelf,PastSurgicalHistorySelf'    
       
 select @lQueryExisting = 'create table ##tblHistory(tid int identity(1,1),d_ExamId bigint,' + @HistoryCols + ')'    
 exec(@lQueryExisting)    
     
 insert into ##tblHistory    
 select h_ExaminationId,'','','','','',PastMedicalHistorySelf,PastSurgicalHistorySelf from #tblExaminationHistory group by h_ExaminationId ,PastSurgicalHistorySelf,PastMedicalHistorySelf
     
 declare @cnt int,@i int    
 select @cnt = COUNT(*),@i = 1 from ##tblHistory    
     
 while @i <= @cnt    
 begin    
  declare @self varchar(max)='',@mother varchar(max)='',@father varchar(max)='',@brother varchar(max)='',@sister varchar(max)='',    
  @ExamId bigint,@len1 int , @PastMedicalHistorySelf varchar(max)=''   
  select @ExamId = d_ExamId from ##tblHistory where tid = @i    
  select @self = @self + h_HistoryName + '+' from #tblExaminationHistory where d_RelationId = 1 and h_ExaminationId = @ExamId    
    select @PastMedicalHistorySelf = @PastMedicalHistorySelf + h_HistoryName + '+' from #tblExaminationHistory where d_RelationId = 1 and h_ExaminationId = @ExamId    
  select @mother = @mother + h_HistoryName + '+' from #tblExaminationHistory where d_RelationId = 3 and h_ExaminationId = @ExamId    
  select @father = @father + h_HistoryName + '+' from #tblExaminationHistory where d_RelationId = 2 and h_ExaminationId = @ExamId    
  select @brother = @brother + h_HistoryName + '+' from #tblExaminationHistory where d_RelationId = 7 and h_ExaminationId = @ExamId    
  select @sister = @sister + h_HistoryName + '+' from #tblExaminationHistory where d_RelationId = 8 and h_ExaminationId = @ExamId    
      
  select @len1 = len(@self)    
  select @self = case when isnull(@self,'') <> '' then left(@self,@len1-1) else isnull(@self,'') end   
    select @PastMedicalHistorySelf = case when isnull(@PastMedicalHistorySelf,'') <> '' then left(@PastMedicalHistorySelf,@len1-1) else isnull(@PastMedicalHistorySelf,'') end 
      
  select @len1 = len(@mother)    
  select @mother = case when isnull(@mother,'') <> '' then left(@mother,@len1-1) else isnull(@mother,'') end    
      
  select @len1 = len(@father)    
  select @father = case when isnull(@father,'') <> '' then left(@father,@len1-1) else isnull(@father,'') end    
      
  select @len1 = len(@brother)    
  select @brother = case when isnull(@brother,'') <> '' then left(@brother,@len1-1) else isnull(@brother,'') end    
      
  select @len1 = len(@sister)    
  select @sister = case when isnull(@sister,'') <> '' then left(@sister,@len1-1) else isnull(@sister,'') end    
      
  update ##tblHistory set PastHistorySelf = @self,PastHistoryMother = @mother,PastHistoryFather = @father,    
  PastHistoryBrother = @brother,PastHistorySister = @sister  
  where tid = @i    
      
  select @i = @i + 1    
 end    
        
 create table #tblExaminationGeneralTemplates(tid int identity(1,1),g_ExaminationId bigint,    
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))    
 insert into #tblExaminationGeneralTemplates    
 select ED.Id,GED.ParameterValue,GED.Remark,GP.Title    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId     
 left join sExamination.tGeneralTemplateExamination GE on ED.Id = GE.SourceId    
 left join sExamination.tGeneralTemplateExaminationDetail GED on GE.Id = GED.GeneralTemplateExaminationId    
 left join sExamination.tGeneralTemplateParameter  GP on GP.Id = GED.GeneralTEmplateParameterId     
 where GP.IsObsolete = 0    
    
DECLARE @tblExaminationGT TABLE(tid INT IDENTITY(1,1), t_Exid BIGINT);

-- Insert distinct Examination IDs from #tblExaminationGeneralTemplates
INSERT INTO @tblExaminationGT
SELECT DISTINCT g_ExaminationId
FROM #tblExaminationGeneralTemplates;

-- Insert remarks into #tblExaminationGeneralTemplates
INSERT INTO #tblExaminationGeneralTemplates
SELECT
    t_Exid,  -- Examination ID
    CASE
        WHEN g_Title = 'Near Vision' THEN g_Remark
        WHEN g_Title = 'Distant Vision' THEN g_Remark
       
        ELSE ''
    END AS g_Remark,
    '', -- g_Value
    CASE
        WHEN g_Title = 'Near Vision' THEN 'Near Vision_Remark'
        WHEN g_Title = 'Distant Vision' THEN 'Distant Vision_Remark'
       
        ELSE ''
    END AS g_Title
FROM
    #tblExaminationGeneralTemplates et
    JOIN @tblExaminationGT t ON et.g_ExaminationId = t.t_Exid
WHERE
    g_Title IN ('Near Vision','Distant Vision')
    AND g_Remark IS NOT NULL;	

 declare @GeneralCols varchar(max)='',@GeneralCols1 varchar(max)=''    
 select @GeneralCols = STUFF(    
 (    
  SELECT Distinct ',' + QUOTENAME(Title)  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0    
  and StaticGeneralTemplateParameterId in (328,336,339)    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')       
-- Append remark columns after their main columns in proper order
SET @GeneralCols = REPLACE(@GeneralCols, '[Near Vision]', '[Near Vision],[Near Vision_Remark]');
SET @GeneralCols = REPLACE(@GeneralCols, '[Distant Vision]', '[Distant Vision],[Distant Vision_Remark]');

    select @GeneralCols1 = STUFF(    
 (    
  SELECT Distinct ',' + QUOTENAME(Title) + ' varchar(300)'  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0    
  and StaticGeneralTemplateParameterId in (328,336,339)    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
-- Insert remark columns after their main columns in proper order
SET @GeneralCols1 = REPLACE(@GeneralCols1, '[Near Vision] varchar(300)', '[Near Vision] varchar(300),[Near Vision_Remark] varchar(300)');
SET @GeneralCols1 = REPLACE(@GeneralCols1, '[Distant Vision] varchar(300)', '[Distant Vision] varchar(300),[Distant Vision_Remark] varchar(300)');
         
 select @lQueryExisting = 'create table ##tblGeneral(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'    
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '    
 insert into ##tblGeneral    
 select g_ExaminationId,' + @GeneralCols + '    
 from    
 (    
  select g_ExaminationId,g_Value,g_Title from #tblExaminationGeneralTemplates group by g_ExaminationId,g_Value,g_Remark,g_Title    
 ) src     
 pivot    
 (    
   max(g_Value) for g_Title in (' + @GeneralCols + ')    
 ) piv;'    
     
 exec (@lQueryExisting)    
     
 create table #tblExaminationTests(tid int identity(1,1),g_ExaminationId bigint,    
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))    
 insert into #tblExaminationTests    
 select ED.Id,GED.ServiceValue,GED.Remark,GP.Title    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId     
 left join sExamination.tTestRequest GE on ED.Id = GE.SourceId    
 left join sExamination.tTestRequestDetail GED on GE.Id = GED.TestRequestId    
 left join sOrderEntry.tTestDetail TD on TD.Id = GED.TestDetailId    
 left join sOrderEntry.tTestParameterMaster GP on GP.Id = TD.TestParameterId    
 where GP.IsObsolete = 0    
  -- Commented due to long run time: by NP; Dt - 19/03/2025   
 --declare @tblExaminationT table(tid int identity(1,1),t_Exid bigint)    
 --insert into @tblExaminationT    
 --select distinct g_ExaminationId from #tblExaminationTests    
     
 --declare @tIncr int,@tCnt int    
 --select @tIncr = 1,@tCnt = count(*) from @tblExaminationT    
     
 --while @tIncr <= @tCnt    
 --begin    
 -- declare @tExamId bigint,@tRem varchar(200)=''    
 -- select @tExamId = t_Exid from @tblExaminationT where tid = @tIncr    
      
 -- select @tRem = ''    
      
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SMEAR STUDY'    
 -- insert into #tblExaminationTests    
 -- select @tExamId,@tRem,'','SMEAR STUDY_Remark'    
      
 -- select @tRem = ''    
      
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'XRAY'    
 -- insert into #tblExaminationTests    
 -- select @tExamId,@tRem,'','XRAY_Remark'    
      
 -- select @tRem = ''    
      
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SONOGRAPHY'    
 -- insert into #tblExaminationTests    
 -- select @tExamId,@tRem,'','SONOGRAPHY_Remark'    
      
 -- select @tRem = ''    
      
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECG'    
 -- insert into #tblExaminationTests    
 -- select @tExamId,@tRem,'','ECG_Remark'    
      
 -- select @tRem = ''    
      
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECHO'    
 -- insert into #tblExaminationTests    
 -- select @tExamId,@tRem,'','ECHO_Remark'    
      
 -- select @tRem = ''    
      
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'TMT'    
 -- insert into #tblExaminationTests    
 -- select @tExamId,@tRem,'','TMT_Remark'    
      
 -- select @tIncr = @tIncr + 1    
 --end  
 -- Comment end : by NP; Dt - 19/03/2025   
  
-- Added by NP; Dt - 19/03/2025 mantis - 41024  
 -- Create temporary table to hold distinct examination IDs  
declare @tblExaminationT table(tid int identity(1,1), t_Exid bigint);  
  
-- Insert distinct g_ExaminationId values into the temporary table  
insert into @tblExaminationT    
select distinct g_ExaminationId from #tblExaminationTests;  
  
-- Insert remarks for different examination titles using a single INSERT statement  
insert into #tblExaminationTests  
select   
    t_Exid,  -- Examination ID  
    -- Using CASE to fetch remarks based on title  
    CASE   
        WHEN g_Title = 'SMEAR STUDY' THEN g_Remark  
        WHEN g_Title = 'XRAY' THEN g_Remark  
        WHEN g_Title = 'SONOGRAPHY' THEN g_Remark  
        WHEN g_Title = 'ECG' THEN g_Remark  
        WHEN g_Title = 'ECHO' THEN g_Remark  
        WHEN g_Title = 'TMT' THEN g_Remark  
        WHEN g_Title = 'USG' THEN g_Remark  
        WHEN g_Title = 'SONOMAMMOGRAM' THEN g_Remark  
        WHEN g_Title = 'PAP SMEAR' THEN g_Remark  
        ELSE ''  -- Default to empty if title does not match  
    END as g_Remark,  
    -- Empty g_Value, as per your original query  
    '',    
    -- Construct the title + _Remark based on the title  
    CASE   
        WHEN g_Title = 'SMEAR STUDY' THEN 'SMEAR STUDY_Remark'  
        WHEN g_Title = 'XRAY' THEN 'XRAY_Remark'  
        WHEN g_Title = 'SONOGRAPHY' THEN 'SONOGRAPHY_Remark'  
        WHEN g_Title = 'ECG' THEN 'ECG_Remark'  
        WHEN g_Title = 'ECHO' THEN 'ECHO_Remark'  
        WHEN g_Title = 'TMT' THEN 'TMT_Remark'  
        WHEN g_Title = 'USG' THEN 'USG_Remark'  
        WHEN g_Title = 'SONOMAMMOGRAM' THEN 'SONOMAMOGRAM_Remark'  
        WHEN g_Title = 'PAP SMEAR' THEN 'PAP SMEAR_Remark'  
        ELSE ''  -- Default if title doesn't match  
    END as g_Title  
from   
    #tblExaminationTests et  
join   
    @tblExaminationT t on et.g_ExaminationId = t.t_Exid  
where   
    g_Title IN ('SMEAR STUDY', 'XRAY', 'SONOGRAPHY', 'ECG', 'ECHO', 'TMT','USG','SONOMAMMOGRAM','PAP SMEAR')  -- Filter to these titles  
    and g_Remark IS NOT NULL;   

   -- Added by NP; Dt - 19/03/2025 mantis - 41024  
 declare @TestCols varchar(max)='',@TestCols1 varchar(max)=''    
 select @TestCols = STUFF(    
 (    
  SELECT CASE WHEN StaticTestParameterId in (16,107,108,109,104,105,214,215,111) THEN ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark')    
  ELSE ',' + QUOTENAME(Title) END from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId not in    
  (    
   14,--PREMETURED CELL    
   18,--E.S.R 2ND HOUR    
  -- 25,--HBA1C    //0041095 commented by shiv thapa  
   28,--SERUM ELECTROLYTES SODIUM    
   29,--SERUM ELECTROLYTES POTASSIUM    
   30,--SERUM ELECTROLYTES CHLORIDES    
   35,--VLDL    
   36,--LDL/HDL RATIO    
   37,--CHOLESTEROLE/HDL RATIO    
   39,--SGOT    
   55,--HIV    
   40,--TOTAL BILLIRUBIN    
   41,--DIRECT BILLIRUBIN(CONJUGATED)    
   42,--INDIRECT BILLIRUBIN(UNCONJUGATED)    
   43,--ALKALINE PHOSPHATASE    
   44,--TOTAL PROTEIN    
   45,--ALBUMIN HEPATIC    
   46,--GLOBULINE(CALCULATION)    
   47,--A/G RATIO    
   48,--GGT    
   --49,--SERUM URIC ACID    
   50,--RA TEST    
   51,--CRP    
   52,--T3    
   53,--T4    
   54, --TSH    
   ---Urine    
   59,--COLOUR    
   60,--ODOUR    
   61,--REACTION URINE    
   62,--APPEARANCE    
   63,--SP GRAVITY    
   66,--KETONE BODIES    
   74,--BACTERIA    
   75,--TRICHONOMAS    
   76,--AMORPHOUS MATERIAL    
   77,--MICROALBUMINURIA    
   114,--Acetone    
   115,--Microscopy    
   78,--COLOR    
   79,--CONSISTANCY    
   80,--REACTION STOOL    
   81,--MUCOUS    
   82,--BLOOD    
   83,--PARASITES    
   84,--OCCULT BLOOD    
   85,--REDUCING SUBSTANCE    
   86,--PUS CELLS STOOL    
   87,--RED BLOOD CELLS STOOL    
   88,--EPITHELIAL CELLS STOOL    
   89,--MACROPHAGE    
   90,--FAT DROPLETS    
   91,--VEGETABLES    
   92,--TROPHOZOITES    
   93,--CYST       
   112,--STOOL    
   104,--XRAY    
   105,--SONOGRAPHY    
   106,--MAMMOGRAPHY    
   107,--ECG    
   108,--ECHO    
   109,--TMT    
   110,--ANGIOGRAPHY    
   111,--PEPS SMEAR    
   113,--MANTOUX    
   116,--STRESS    
   117,--SPUTUM    
   118,--MCHC    
   119,--Trop T    
   120,--LDH    
   121,--CPK MB    
   122,--Pregnancy Test    
   123,--HBsAg,
   214,
   215,
   111
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ',[ECG],[ECG_Remark],[ECHO],[ECHO_Remark],[TMT],[TMT_Remark],[SONOGRAPHY],[SONOGRAPHY_Remark],[XRAY],[XRAY_Remark],[USG_Remark],[SONOMAMOGRAM_Remark],[PAP SMEAR_Remark]'    
        
    select @TestCols1 = STUFF(    
 (    
  SELECT CASE WHEN StaticTestParameterId in (16,107,108,109,104,105,214,215,111) THEN ',' + QUOTENAME(Title) + ' varchar(300)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(300)'    
  ELSE ',' + QUOTENAME(Title) + ' varchar(1000)' END    
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId not in    
  (    
    14,--PREMETURED CELL    
   18,--E.S.R 2ND HOUR    
  -- 25,--HBA1C    //0041095 commented by shiv thapa  
   28,--SERUM ELECTROLYTES SODIUM    
   29,--SERUM ELECTROLYTES POTASSIUM    
   30,--SERUM ELECTROLYTES CHLORIDES    
   35,--VLDL    
   36,--LDL/HDL RATIO    
   37,--CHOLESTEROLE/HDL RATIO    
   39,--SGOT    
   55,--HIV    
   40,--TOTAL BILLIRUBIN    
   41,--DIRECT BILLIRUBIN(CONJUGATED)    
   42,--INDIRECT BILLIRUBIN(UNCONJUGATED)    
   43,--ALKALINE PHOSPHATASE    
   44,--TOTAL PROTEIN    
   45,--ALBUMIN HEPATIC    
   46,--GLOBULINE(CALCULATION)    
   47,--A/G RATIO    
   48,--GGT    
   --49,--SERUM URIC ACID    
   50,--RA TEST    
   51,--CRP    
   52,--T3    
   53,--T4    
   54, --TSH    
   ---Urine    
   59,--COLOUR    
   60,--ODOUR    
   61,--REACTION URINE    
   62,--APPEARANCE    
   63,--SP GRAVITY    
   66,--KETONE BODIES    
   74,--BACTERIA    
   75,--TRICHONOMAS    
   76,--AMORPHOUS MATERIAL    
   77,--MICROALBUMINURIA    
   114,--Acetone    
   115,--Microscopy    
   78,--COLOR    
   79,--CONSISTANCY    
   80,--REACTION STOOL    
   81,--MUCOUS    
   82,--BLOOD    
   83,--PARASITES    
   84,--OCCULT BLOOD    
   85,--REDUCING SUBSTANCE    
   86,--PUS CELLS STOOL    
   87,--RED BLOOD CELLS STOOL    
   88,--EPITHELIAL CELLS STOOL    
   89,--MACROPHAGE    
   90,--FAT DROPLETS    
   91,--VEGETABLES    
   92,--TROPHOZOITES    
   93,--CYST       
   112,--STOOL    
   104,--XRAY    
   105,--SONOGRAPHY    
   106,--MAMMOGRAPHY    
   107,--ECG    
   108,--ECHO    
   109,--TMT    
   110,--ANGIOGRAPHY    
   111,--PEPS SMEAR    
   113,--MANTOUX    
   116,--STRESS    
   117,--SPUTUM    
   118,--MCHC    
   119,--Trop T    
   120,--LDH    
   121,--CPK MB    
   122,--Pregnancy Test    
   123,--HBsAg    
   214,
   215,
   111
  )  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols1 = @TestCols1 + ',[ECG] varchar(1000),[ECG_Remark] varchar(1000),[ECHO] varchar(1000),    
    [ECHO_Remark] varchar(1000),[TMT] varchar(1000),[TMT_Remark] varchar(1000),[SONOGRAPHY] varchar(1000),[SONOGRAPHY_Remark] varchar(1000),    
    [XRAY] varchar(1000),[XRAY_Remark] varchar(1000),[USG_Remark] varchar(1000),[SONOMAMOGRAM_Remark] varchar(1000),[PAP SMEAR_Remark] varchar(1000)'    
        
 select @lQueryExisting = 'create table ##tblTests(tid int identity(1,1),d_ExamId bigint,' + @TestCols1 + ')'    
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '    
 insert into ##tblTests    
 select g_ExaminationId,' + @TestCols + '    
 from    
 (    
  select g_ExaminationId,g_Value,g_Title from #tblExaminationTests group by g_ExaminationId,g_Value,g_Remark,g_Title    
 ) src     
 pivot    
 (    
   max(g_Value) for g_Title in (' + @TestCols + ')    
 ) piv;'    
     
 exec (@lQueryExisting)    
     
 create table #tblExaminationAudiometrys(tid int identity(1,1),AudiometryId bigint,ExaminationId bigint,IsDoneLeft bit,    
 IsDoneRight bit,AcValueLeft int,AcValueRight int,FrequencyId int,AudiometryAcResultLeftId int,AudiometryAcResultRightId int,    
 AudiometryResultRemarkLeftId nvarchar(200),AudiometryResultRemarkRightId nvarchar(200))    
 insert into #tblExaminationAudiometrys    
 select ISNULL(A.Id,0) AS AudiometryId,ED.Id,    
 ISNULL(A.IsDoneLeft,0) AS IsDoneLeft,    
 ISNULL(A.IsDoneRight,0) AS IsDoneRight,    
 ISNULL(AD.AcValueLeft,0) AS AcValueLeft,    
 ISNULL(AD.AcValueRight,0) AS AcValueRight,    
 ISNULL(AD.FrequencyId,0) AS FrequencyId,    
 ISnull(A.AudiometryAcResultLeftId,0) AS AudiometryAcResultLeftId,    
 ISnull(A.AudiometryAcResultRightId,0) AS AudiometryAcResultRightId,    
 ISnull(A.AudiometryResultRemarkLeftId,0) AS AudiometryResultRemarkLeftId,    
 ISnull(A.AudiometryResultRemarkRightId,0) AS AudiometryResultRemarkRightId    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll AA on ED.Id = AA.ExaminationId    
 left join sExamination.tAudiometry A on A.SourceId = ED.Id    
 left join sExamination.tAudiometryDetail AD on AD.AudiomentryId = A.Id    
 left join sExamination.tAudiometryResultMaster RM on A.AudiometryAcResultLeftId = RM.Id    
 left join sExamination.tAudiometryResultMaster RM1 on A.AudiometryBcResultLeftId = RM.Id    
 left join sExamination.tAudiometryResultMaster RM2 on A.AudiometryAcResultRightId = RM.Id    
 left join sExamination.tAudiometryResultMaster RM3 on A.AudiometryBcResultRightId = RM.Id     
     
 select @lQueryExisting = 'create table ##tblAudiometry(a_ExamId bigint,IsDoneLeft bit,    
 AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),    
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),    
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),    
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200))'    
     
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '    
 insert into ##tblAudiometry(a_ExamId,IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,    
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,R250,R500,R1000,R2000,R4000,R6000,R8000)    
 Select LeftPivot.ExaminationId,CASE WHEN LeftPivot.IsDoneLeft = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneLeft,    
 ISNULL(LeftPivot.AudiometryAcResultLeft,'''') as AudiometryAcResultLeft,    
 ISNULL(LeftPivot.AudiometryResultRemarkLeft,'''') as AudiometryResultRemarkLeft,    
 LeftPivot.[250] as L250,LeftPivot.[500] as L500,LeftPivot.[1000] as L1000,LeftPivot.[2000] as L2000,    
 LeftPivot.[4000] as L4000,LeftPivot.[6000] as L6000,LeftPivot.[8000] as L8000,    
 CASE WHEN RightPivot.IsDoneRight = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneRight,    
 RightPivot.AudiometryAcResultRight as AudiometryAcResultRight,    
 RightPivot.AudiometryResultRemarkRight as AudiometryResultRemarkRight,    
 RightPivot.[250] as R250,RightPivot.[500] as R500,RightPivot.[1000] as R1000,RightPivot.[2000] as R2000,    
 RightPivot.[4000] as R4000,RightPivot.[6000] as R6000,RightPivot.[8000] as R8000    
 From    
 (    
  select pvt.AudiometryId AS AudiometryId,    
  ISNULL(pvt.AudiometryLeftResult,'''') AS AudiometryAcResultLeft,    
  ISNULL(pvt.AudiometryLeftRemark,'''') AS AudiometryResultRemarkLeft,    
  pvt.IsDoneLeft,pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]    
  from    
  (    
   Select AudiometryId,TC.ExaminationId,IsDoneLeft,AcValueLeft,    
   FrequencyId,RS.Title AS AudiometryLeftResult,    
   RM.Title AS AudiometryLeftRemark    
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultLeftId    
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkLeftId    
  )t     
  PIVOT (MIN(AcValueLeft) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])) AS pvt    
 ) LeftPivot    
 INNER JOIN    
 (    
  select pvt.AudiometryId AS AudiometryId,    
  ISNULL(pvt.AudiometryRightResult,'''') AS AudiometryAcResultRight,    
  ISNULL(pvt.AudiometryRightRemark,'''') AS AudiometryResultRemarkRight, pvt.IsDoneRight,    
  pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]    
  from    
  (    
   Select AudiometryId,TC.ExaminationId,IsDoneRight,AcValueRight,    
   FrequencyId,RS.Title AS AudiometryRightResult,    
   RM.Title AS AudiometryRightRemark    
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultRightId    
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkRightId    
  )t    
  PIVOT (MIN(AcValueRight) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])    
 ) AS pvt ) RightPivot ON LeftPivot.ExaminationId = RightPivot.ExaminationId'    
     
 exec (@lQueryExisting)    
     
 declare @lMainQuery varchar(max)=''    
 select @lMainQuery = 'create table ##tblMainTable1(ExaminationId bigint,ExaminationType varchar(500),RoundName varchar(200),    
 SubLocationName varchar(500),EmpNo varchar(500),FullName varchar(500),EmployeeType varchar(500),FunctionName varchar(500),    
 Department varchar(500),Grade varchar(300),Company varchar(500),BirthDate varchar(500),DateOfJoining varchar(500),    
 Gender varchar(500),Mobilenumber varchar(500),Companyemail varchar(500),ExaminationDate varchar(500),Age int,    
 EmployeeDesignation varchar(500),Skill varchar(500),NatureOfWork varchar(500),Height int,Weight float,    
 BMI float,BPSys varchar(200),BPDia varchar(200),    
 ' + case when @ExistingCols1 is not null then isnull(@ExistingCols1,'') + ',' else '' end + '    
 ' + case when @DiseaseCols is not null then isnull(@DiseaseCols,'') + ',' else '' end + '    
 ' + case when @HistoryCols is not null then isnull(@HistoryCols,'') + ',' else '' end + '    
 ' + case when @TestCols1 is not null then isnull(@TestCols1,'') + ',' else '' end +'    
 ' + case when @GeneralCols1 is not null then isnull(@GeneralCols1,'') + ',' else '' end + '    
 FVCPredicted varchar(200),FVCObserved varchar(200),PerOfPredictedFVC varchar(200),FEV1Predicted varchar(200),FEV1Observed varchar(200),    
 PerOfFEV1 varchar(200),PerOfFEV1ByFVC varchar(200),PulmonaryResult varchar(200),NotDoneReason varchar(50),    
 IsDoneLeft bit,AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),    
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),    
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),    
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200),    
 Diagnosis varchar(max),Recommendation varchar(max),comUnfit int,comUnfitDate varchar(500),comUnfitReason varchar(500),    
 comUnfitPeriod varchar(300),comRefitDate varchar(500),Status varchar(500),TargetGroup varchar(500),ProcessType varchar(500))'    
     
 --select @lMainQuery = replace(@lMainQuery,'OVA','Stool for ova and cyst')    
     
 exec (@lMainQuery)      
     
 declare @lMainExecuteQuery varchar(max)=''     
 select @lMainExecuteQuery = 'insert into ##tblMainTable1 select ExaminationId,ExaminationType,RoundName,StorelocationName,EmpNo,FullName,EmployeeType,    
 FunctionName,Department,Grade,Company,BirthDate,DateOfJoining,Gender,Mobilenumber,Companyemail,ExaminationDate,Age,EmployeeDesignation,    
 Skill,NatureOfWork,Height,Weight,BMI,BPSys,BPDia,    
 ' + @ExistingCols + ',' + @DiseaseCols1 + ',' + @HistoryCols1 + ',' + @TestCols+ ',' + @GeneralCols  + ',    
 FVCPredicted,FVCObserved,PerOfPredictedFVC,FEV1Predicted,FEV1Observed,PerOfFEV1,PerOfFEV1ByFVC,    
 PulmonaryResult = P.PulmonaryResulIntensity + '' '' + P.PulmonaryResult,'''',    
 IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,    
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,    
 R250,R500,R1000,R2000,R4000,R6000,R8000,Diagnosis,Recommendation,comUnfit,comUnfitDate,comUnfitReason ,    
 comUnfitPeriod,comRefitDate,Status,TargetGroup,ProcessType    
 from #tblExaminationAll EA    
 left join tempdb.##tblExisiting EE on EA.ExaminationId = EE.t_ExamId    
 left join tempdb.##tblDisease ED on EA.ExaminationId = ED.d_ExamId    
 left join tempdb.##tblHistory HE on EA.ExaminationId = HE.d_ExamId    
 left join tempdb.##tblGeneral GE on EA.ExaminationId = GE.d_ExamId    
 left join tempdb.##tblTests TE on EA.ExaminationId = TE.d_ExamId    
 left join tempdb.##tblAudiometry AA on EA.ExaminationId = AA.a_ExamId    
 left join sExamination.tPulmonary P on EA.ExaminationId = P.SourceId'     
     
  
 exec (@lMainExecuteQuery)    
 if(@rColumnName != '')
 begin 
 
 Declare @rColumsSelected nvarchar(max)='';
 DECLARE @sql NVARCHAR(MAX);
 set @rColumsSelected = 'ExaminationId,ExaminationType,RoundName,SubLocationName,EmpNo,FullName,EmployeeType,    
 FunctionName,Department,Grade,Company,BirthDate,DateOfJoining,Gender,Mobilenumber,Companyemail,ExaminationDate,EmployeeDesignation,    
 Skill,NatureOfWork,TargetGroup,ProcessType'
     
 --select * from  ##tblMainTable1  
      set @rColumnName = Replace(@rColumnName, 'Audiometry', 'IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,    
									 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,    
									 R250,R500,R1000,R2000,R4000,R6000,R8000');
	  SET @rColumnName = REPLACE(@rColumnName, 'Pulmonary', 
    'FVCPredicted,FVCObserved,PerOfPredictedFVC,FEV1Predicted,FEV1Observed,PerOfFEV1,PerOfFEV1ByFVC,PulmonaryResult');
	set @rColumnName = REPLACE(@rColumnName, 'BloodPressureSystolic','BPSys');
	set @rColumnName = REPLACE(@rColumnName, 'BloodPressureDiastolic','BPDia');
DECLARE @validColumns NVARCHAR(MAX) = '';

DECLARE @Pos INT, @Col NVARCHAR(128);

-- Add trailing comma for parsing
SET @rColumnName = @rColumnName + ',';
SET @Pos = CHARINDEX(',', @rColumnName);

WHILE @Pos > 0
BEGIN
    SET @Col = LTRIM(RTRIM(LEFT(@rColumnName, @Pos - 1)));

    -- check column exists in ##tblMainTable1
    IF EXISTS (
    SELECT 1
    FROM tempdb.sys.columns c
    JOIN tempdb.sys.objects o ON c.object_id = o.object_id
    WHERE o.name = '##tblMainTable1'
      AND c.name = @Col
)
BEGIN
    -- wrap with [] to handle spaces/special characters
    SET @validColumns = @validColumns + CASE WHEN @validColumns = '' THEN '' ELSE ',' END + QUOTENAME(@Col);
END

    SET @rColumnName = SUBSTRING(@rColumnName, @Pos + 1, LEN(@rColumnName));
    SET @Pos = CHARINDEX(',', @rColumnName);
END;

-- Build final SQL
SET @sql = '
    SELECT ' + @rColumsSelected +
    CASE WHEN LEN(@validColumns) > 0 THEN ',' + @validColumns ELSE '' END + '
    FROM ##tblMainTable1;
';

 EXEC sp_executesql @sql; -- uncomment to execute
 end
 else
 begin
 select * from ##tblMainTable1
 end
  
end
GO
PRINT N'Altering Procedure [sExamination].[pServiceListingResultAllGet]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pServiceListingResultAllGet]
@rSourceId [bigint],
@rOrgId [smallint],	
@rSourceTypeId [smallint],
@rTestId int = 0,
@rGenderId int = 1,
@rAge int = 0,	 
@rParameterId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	declare @ParticipantSourceTypeId int,@EmployeeId bigint,@setupID int,@TargetGroup int,@rMainTypeId int,@lConfValue varchar(10)
	select @rGenderId = CASE when E.ParticipantSourceTypeId=95 then EM.GenderId when (E.ParticipantSourceTypeId=1009 and o.genderid is null) then BM.GenderId when (E.ParticipantSourceTypeId=1009 and ISNULL(o.GenderId,0)<>0)  then o.GenderId when E.ParticipantSourceTypeId=1001 then EFD.GenderId END,
	@rAge = CASE when E.ParticipantSourceTypeId=95 then datediff(yy,ISNULL(EM.DateOfBirth,''),sCommon.fGetDate())
	when (E.ParticipantSourceTypeId=1009 and Isnull(o.Age,'')='') then datediff(yy,ISNULL(BM.DateOfBirth,''),sCommon.fGetDate()) when (E.ParticipantSourceTypeId=1009 and Isnull(o.Age,'')<>'') then o.Age when E.ParticipantSourceTypeId=1001 then datediff(yy,ISNULL(EFD.DateOfBirth,''),sCommon.fGetDate()) end,
	@ParticipantSourceTypeId = ParticipantSourceTypeId,
	@EmployeeId = ParticipantSourceId,
	@setupID = E.SetupId,@TargetGroup = E.TargetGroupId,@rMainTypeId = sT.MainTypeId
	from sExamination.tExamination E
	inner join sExamination.tSetupMaster sM on E.SetupId = sM.Id
	inner join sExamination.tSubTypeMaster sT on sM.SubTypeId = sT.Id
	left join sExamination.tOpd o on o.ExaminationId=E.Id
	left join sHrm.tEmployeePersonalDetail EM on E.ParticipantSourceId = EM.EmployeeId and E.ParticipantSourceTypeId = 95
	left join sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
	left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
	where E.Id = @rSourceId
	
	if @ParticipantSourceTypeId = 1009
	begin
		select @rAge = isnull(Age,0),@rGenderId = Isnull(GenderId,0) from sExamination.tOPD where ExaminationId = @rSourceId				
		if (@rAge = 0)
		begin
			select @rAge = datediff(yy,ISNULL(DateOfBirth,''),sCommon.fGetDate()) from sHrm.tCSRBenefiterMaster where Id = @EmployeeId
			select @rAge = isnull(@rAge,0)
		end
		if (@rGenderId=0)
		begin
			select @rGenderId = GenderId from sHrm.tCSRBenefiterMaster where Id = @EmployeeId			
		end
		select @TargetGroup = 0
	end
	else if @ParticipantSourceTypeId = 1001
	begin
		select @rGenderId = GenderId, @rAge = datediff(yy,ISNULL(DateOfBirth,''),sCommon.fGetDate()) from sHrm.tEmployeeFamilyDetails where Id = @EmployeeId
		select @TargetGroup = 0
	end
	if @rMainTypeId = 7
	begin
		select @TargetGroup = 0
	end
print @rAge		
print @rGenderId

		select @lConfValue = Isnull(CS.ItemValue,CM.ItemValue) 
		from sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id 
		where CM.ItemKey = 'Examination.IsTestAutoSaveinVital'

		if((@lConfValue='True') and (@setupID<>[sCommon].[fGetIntIdForOrg](8,@rOrgId)))
		begin
			exec [sExamination].[pSaveTestResultsFirst] @rSourceId,@rMainTypeId,@setupID,1,@TargetGroup
		end

		print @setupID

if(@setupID=[sCommon].[fGetIntIdForOrg](8,@rOrgId))
begin
	SELECT Distinct TRD.Id as TestRequestDetailId,
	PVTM.Id as ParameterValueTypeId,
	ISNULL(TPM.ListValueTypeId,0) as ListValueTypeId,
	TPM.Title as ParmeterName,
	TPM.Code,TPM.Id AS TestParameterId,
	PVTM.Title as ParaMeterType,
	RTRIM(Ltrim(ISNULL(TRD.ServiceValue,''))) as ServiceValue,
	ISNULL(TRD.ServiceResult,'') as ServiceResult,
	ISNULL(TPR.AgeFrom,0) as AgeFrom,
	ISNULL(TPR.AgeTo,0) as AgeTo,
	TPR.Minimum as Minimum,
	TPR.Maximum as Maximum,
	ISNULL(TRD.Remark,'') AS Remark,
	ISNULL(TR.Remark,'') AS RemarkMain,
	SM.Title AS TestName,
	SM.Id AS TestId,
	ISNULL(TPR.IsNormal,0) AS IsNormal,
	ISNULL(TPM.ClinicalUOM,'') AS ClinicalUOM,
	1 AS IsDone,
	CASE WHEN TR.SourceId IS NULL THEN 0 ELSE 1 END AS IsExist,
	TPM.NormalRange,
	[sExamination].[fGetParameterRange](TPM.Id,@rAge,@rGenderId) as [Range],
	--[sExamination].[fGetNormalTestParameterRange](TPM.Id,@rAge,@rGenderId) as [Range],
	CASE WHEN ROW_NUMBER() OVER(PARTITION BY SM.Title order by TD.OrderIndex) = 1 
    THEN isnull(TR.RequestRemark,'') else '' end as RequestRemark,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY SM.Title order by TD.OrderIndex) = 1 
    THEN isnull(TR.TestSpecificationId,0) else 0 end as TestSpecificationId,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY SM.Title order by TD.OrderIndex) = 1 
    THEN isnull(TS.Specification,'') else '' end as Specification,
    TPM.StaticTestParameterId,
	isnull(TPM.OrderIndex,0) OrderIndex
	FROM sExamination.tTestRequest TR
	INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id	
	INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id AND isnull(TR.IsObsolete,0) = 0
	INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id and TR.TestId = TD.TestId
	INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
	--left JOIN sExamination.tTargetGroupExaminationTemplate TGT on TGT.SourceParameterId = TPM.Id AND TGT.SourceTemplateId = 118 and TGT.TargetGroupId = isnull(@TargetGroup,0) 
	LEFT JOIN sOrderEntry.tParameterValueTypeMaster PVTM ON PVTM.Id=TPM.ParameterValueTypeId
	LEFT JOIN sOrderEntry.tTestSpecification TS on TS.Id = TR.TestSpecificationId
	LEFT JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TPM.ListValueTypeId AND TPM.Id = TD.TestParameterId and LVTM.OrgId = @rOrgId
	LEFT JOIN
	(
		SELECT top 1 R.TestParameterId,R.AgeFrom,R.AgeTo,R.Minimum,R.Maximum,R.IsNormal AS IsNormal
		FROM sOrderEntry.tTestParameterDetail R WHERE R.AgeFrom <= @rAge AND R.AgeTo >= @rAge AND R.GenderId = @rGenderId AND IsNormal = 1
	) TPR ON TPM.Id = TPR.TestParameterId AND TPM.ParameterValueTypeId = 1			  				
	WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId AND TR.SourceId = @rSourceId And ((TR.TestId = @rTestId) OR (@rTestId = 0)) 
	AND ((TPM.Id = @rParameterId) OR (@rParameterId = 0)) and SM.IsObsolete = 0
	and SM.StaticTestId <> case when @rGenderId = 1 then 1032 else 1013 end -- for mentis issue no:8803 (2019-05-22)
	and SM.StaticTestId <> case when @rGenderId = 1 then 1027 else 1013 end -- for mentis issue no:8803 (2019-05-22)	
	--and (1=(case when @setupID=[sCommon].[fGetIntIdForOrg](8,@rOrgId) then 1 else 0 end) or (TGT.MainTypeId = @setupID))
	ORDER BY SM.Title,isnull(TPM.OrderIndex,0)
END
Else
Begin
		SELECT Distinct TRD.Id as TestRequestDetailId,
	PVTM.Id as ParameterValueTypeId,
	ISNULL(TPM.ListValueTypeId,0) as ListValueTypeId,
	TPM.Title as ParmeterName,
	TPM.Code,TPM.Id AS TestParameterId,
	PVTM.Title as ParaMeterType,
	RTRIM(Ltrim(ISNULL(TRD.ServiceValue,''))) as ServiceValue,
	ISNULL(TRD.ServiceResult,'') as ServiceResult,
	ISNULL(TPR.AgeFrom,0) as AgeFrom,
	ISNULL(TPR.AgeTo,0) as AgeTo,
	TPR.Minimum as Minimum,
	TPR.Maximum as Maximum,
	ISNULL(TRD.Remark,'') AS Remark,
	SM.Title AS TestName,
	SM.Id AS TestId,
	ISNULL(TPR.IsNormal,0) AS IsNormal,
	ISNULL(TPM.ClinicalUOM,'') AS ClinicalUOM,
	1 AS IsDone,
	CASE WHEN TR.SourceId IS NULL THEN 0 ELSE 1 END AS IsExist,
	TPM.NormalRange,
	[sExamination].[fGetParameterRange](TPM.Id,@rAge,@rGenderId) as [Range],
	--[sExamination].[fGetNormalTestParameterRange](TPM.Id,@rAge,@rGenderId) as [Range],
	CASE WHEN ROW_NUMBER() OVER(PARTITION BY SM.Title order by TD.OrderIndex) = 1 
    THEN isnull(TR.RequestRemark,'') else '' end as RequestRemark,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY SM.Title order by TD.OrderIndex) = 1 
    THEN isnull(TR.TestSpecificationId,0) else 0 end as TestSpecificationId,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY SM.Title order by TD.OrderIndex) = 1 
    THEN isnull(TS.Specification,'') else '' end as Specification,
    TPM.StaticTestParameterId,
	isnull(TPM.OrderIndex,0) OrderIndex
	FROM sExamination.tTestRequest TR
	INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id	
	INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id AND isnull(TR.IsObsolete,0) = 0
	INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id and TR.TestId = TD.TestId
	INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
	left JOIN sExamination.tTargetGroupExaminationTemplate TGT on TGT.SourceParameterId = TPM.Id AND TGT.SourceTemplateId = 118 and TGT.TargetGroupId = isnull(@TargetGroup,0) 
	LEFT JOIN sOrderEntry.tParameterValueTypeMaster PVTM ON PVTM.Id=TPM.ParameterValueTypeId
	LEFT JOIN sOrderEntry.tTestSpecification TS on TS.Id = TR.TestSpecificationId
	LEFT JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TPM.ListValueTypeId AND TPM.Id = TD.TestParameterId and LVTM.OrgId = @rOrgId
	LEFT JOIN
	(
		SELECT top 1 R.TestParameterId,R.AgeFrom,R.AgeTo,R.Minimum,R.Maximum,R.IsNormal AS IsNormal
		FROM sOrderEntry.tTestParameterDetail R WHERE R.AgeFrom <= @rAge AND R.AgeTo >= @rAge AND R.GenderId = @rGenderId AND IsNormal = 1
	) TPR ON TPM.Id = TPR.TestParameterId AND TPM.ParameterValueTypeId = 1			  				
	WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId AND TR.SourceId = @rSourceId And ((TR.TestId = @rTestId) OR (@rTestId = 0)) 
	AND ((TPM.Id = @rParameterId) OR (@rParameterId = 0)) and SM.IsObsolete = 0
	and SM.StaticTestId <> case when @rGenderId = 1 then 1032 else 1013 end -- for mentis issue no:8803 (2019-05-22)
	and SM.StaticTestId <> case when @rGenderId = 1 then 1027 else 1013 end -- for mentis issue no:8803 (2019-05-22)	
	and TGT.MainTypeId = @setupID
	ORDER BY SM.Title,isnull(TPM.OrderIndex,0)
END
END
GO
PRINT N'Altering Procedure [sExamination].[pGetTestResultsExaminationAllNg]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetTestResultsExaminationAllNg]
@rExaminationId bigint,
@rOrgId int,
@rSetupId int,
@rSourceTypeId int,
@rProcessId int,
@rFlag int,
@rFlagDefault int = null,
@rTargetGroupId int = null,
@rAge int = 0,
@rGenderId int = 0
AS 
BEGIN 

declare @rPatientId bigint,@lMainTypeId int, @rConfigBloodGroup int = 0,@rEMPId bigint, @TitleBloodGroup NVARCHAR(20), @IdBloodGroup int; 
	select @rConfigBloodGroup = 
		CASE
			WHEN sConfig.fConfigurationValueGet('Examination.BloodGroupCarryForwardFromHR',@rOrgId,0,0,0) = 'True' 
			THEN 1 ELSE 0 
		END
	select @lMainTypeId = ST.MainTypeId from sExamination.tExamination E inner join sExamination.tSetupMaster SM
	on E.SetupId = SM.Id inner join sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
	where E.Id = @rExaminationId

	select @rEMPId = ParticipantSourceId from sExamination.tExamination where Id = @rExaminationId	
	
	SET @TitleBloodGroup = (select top 1 BGM.Title from sHrm.tEmployeePersonalDetail EPD 
	Inner Join sExamination.tExamination E2 on E2.ParticipantSourceId = EPD.EmployeeId
	Inner Join sCommon.tBloodGroupMaster BGM on BGM.Id = EPD.BloodGroupId
	where E2.Id = @rExaminationId)

	SET @IdBloodGroup = (select top 1 Id from sOrderEntry.tListValueMaster 
	where Title = @TitleBloodGroup and ListValueTypeId = sCommon.fGetIntIdForOrg(4,@rOrgId))

	if(@rAge = 0 AND @rGenderId = 0)
	BEGIN
		if @rExaminationId > 0
		begin
			select @rPatientId = ParticipantSourceId from sExamination.tExamination where Id = @rExaminationId	
			select @rAge = DATEDIFF(yy,DateOfBirth,GETDATE()),@rGenderId = GenderId from sHrm.vEmployeeCommonDetail where EmployeeId = @rPatientId
		end
		else
		begin
			select @rAge = DATEDIFF(yy,DateOfBirth,GETDATE()),@rGenderId = GenderId from sHrm.vEmployeeCommonDetail where EmployeeId = @rPatientId
		end	
	END
select 
 ISNULL(TM.Id,0) as TestId,
 ISNULL(TP.Id,0) as TestParameterId,
 isnull(TRR.TestRequestId,0) as TestRequestId,
isnull(TRR.Id,0) as TestRequestDetailId,
isnull(PVTM.Id,0) as ParameterValueTypeId,
CASE WHEN ROW_NUMBER() OVER(PARTITION BY TM.Title order by TP.OrderIndex) = 1 THEN TM.Title ELSE '' END as AllergyType,
isnull(TP.Title,'') as Parameter,
case when PVTM.Id = 1 then 
	case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end  
	when PVTM.Id = 2 then isnull(sExamination.fGetTestResultsDropDownsNg(TP.ListValueTypeId,case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end,@rOrgId),0)
	when PVTM.Id = 3 then 
	case when @rExaminationId = 0 then '' else
	case when isnull(TRR.ServiceValue,'') = '' then '' else isnull(TRR.ServiceValue,'') end end 
	else '' end 
	as NumericResult,
	case when PVTM.Id = 1 then 
	case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end  
	when PVTM.Id = 2 then (Case When TRRC.BloodCount > 0 and @rConfigBloodGroup = 1  
	and isnull(sExamination.fGetSelectedTestResultsDropDownsNg(TP.ListValueTypeId,case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end,@rOrgId),0) = 0
	Then Cast(isnull(@IdBloodGroup, 0) as nvarchar(10)) ELSE
	isnull(sExamination.fGetSelectedTestResultsDropDownsNg(TP.ListValueTypeId,case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end,@rOrgId),0) END)
	when PVTM.Id = 3 then
	case when @rExaminationId = 0 then '' else
	case when isnull(TRR.ServiceValue,'') = '' then '' else isnull(TRR.ServiceValue,'') end end 
	else '' end 
	as NumericResultSelectedValue,
	case when PVTM.Id = 1 then 
	case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end  
	when PVTM.Id = 2 then (Case When TRRC.BloodCount > 0 and @rConfigBloodGroup = 1 
	and isnull(sExamination.fGetSelectedTestResultsDropDownsNg(TP.ListValueTypeId,case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end,@rOrgId),0) = 0
	Then isnull(@TitleBloodGroup, '') ELSE
	isnull(sExamination.fGetTestResultsDropDownSelectedTextNg(TP.ListValueTypeId,case when @rExaminationId = 0 then '' else isnull(TRR.ServiceValue,'') end,@rOrgId),0) END)
	when PVTM.Id = 3 then 
	case when @rExaminationId = 0 then '' else
	case when isnull(TRR.ServiceValue,'') = '' then '' else isnull(TRR.ServiceValue,'') end end 
	else '' end 
	as NumericResultSelectedText,
PVTM.Title  as ParmeterType,
case when @rExaminationId = 0 then '' else isnull(TRR.Remark,'') end as TemplateResultRemark,

case when TP.StaticTestParameterId <> 57 then
	case when TP.ParameterValueTypeId = 1 then [sExamination].[fGetParameterRange](TP.Id,@rAge,@rGenderId) else '' end
	else '' end as openDilution,
	
	LVTM.Id,
	@rAge as age,
	@rGenderId as gender,
	ISNULL(TP.StaticTestParameterId,0) as StaticTestParameterId
from sOrderEntry.tTestMaster TM
	inner join sOrderEntry.tTestDetail TD on TD.TestId = TM.Id
	inner join sOrderEntry.tTestParameterMaster TP on TP.Id = TD.TestParameterId	
	inner join sExamination.tTargetGroupExaminationTemplate SA on TP.Id = SA.SourceParameterId
	--left join sOrderEntry.tTestParameterDetail TPD on TPD.TestParameterId=TP.Id and TPD.GenderId=@rGenderId and TPD.IsNormal=1
	left join sOrderEntry.tParameterValueTypeMaster PVTM on PVTM.Id = TP.ParameterValueTypeId
	left join sOrderEntry.tListValueTypeMaster LVTM on (LVTM.Id = TP.ListValueTypeId) AND TP.Id = TD.TestParameterId	
	left join
	(
		select TR.Id as TestRequestId,TR.TestId,TRD.Id,
		TRD.TestDetailId,TRD.ServiceValue,TRD.ServiceResult,TRD.Remark		
		from sExamination.tTestRequest TR
		inner join sExamination.tTestRequestDetail TRD
		on TR.Id = TRD.TestRequestId
		where TR.SourceId = @rExaminationId
		and TR.SourceTypeId = @rSourceTypeId
		and TR.OrgId = @rOrgId and TRD.OrgId = @rOrgId
	) TRR on TRR.TestDetailId = TD.Id and TRR.TestId = TD.TestId
	left join
	(
		select TD.Id, TD.TestId, COUNT(TD.Id) as BloodCount from sOrderEntry.tTestDetail TD
		LEFT Join sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		where TPM.StaticTestParameterId = 1
		Group By TD.Id, TD.TestId
	) TRRC on TRRC.Id = TD.Id and TRRC.TestId = TD.TestId
	
	where TM.OrgId = @rOrgId
	and isnull(SA.TargetGroupId,0) = @rTargetGroupId -- Mantis- 0038727 by- Shivam on  19/12/2024
	--and isnull(SA.TargetGroupId,0) = case when @lMainTypeId = 7 then 0 else @rTargetGroupId end
	and SA.MainTypeId = @rSetupId
	and SA.SourceTemplateId = 118 
	and ISNULL(TP.StaticTestParameterId,0) <> case when @rGenderId = 1 then 111 else 58 end -- for mentis issue no:8803 (2019-05-22)
	and ISNULL(TP.StaticTestParameterId,0) <> case when @rGenderId = 1 then 122 else 58 end -- for mentis issue no:8803 (2019-05-22)
	and ISNULL(TP.StaticTestParameterId,0) <> case when @rGenderId = 1 then 241 else 58 end -- for mantis 0049101
	order by TM.Title,isnull(TP.OrderIndex,0)	
	
END
GO
PRINT N'Altering Procedure [sHrm].[PEmpDashboardDetailGet]...';


GO
CREATE OR ALTER PROCEDURE [sHrm].[PEmpDashboardDetailGet]
@rEmpId bigint,
@rOrgId int = 0
as
begin

declare @lLatestVitalDisplayConfigVal varchar(5) = 'False';
      
IF (@rOrgId > 0)
BEGIN
	select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);
END

Declare @lHealthIndexScore decimal(10,2),@lOpdCount int,@lHeight int,@lWeight decimal(8,2),@lBMI decimal(8,2),@lBloodPressureSystolic int
,@lBloodPressureDiastolic int,@lFBS nvarchar(10),@lHB nvarchar(10),@lchol nvarchar(10),@lTreatment nvarchar(500),@lPreviousOPDVisit nvarchar(max)
,@lInjuryDate nvarchar(20),@lInjuryTime nvarchar(20),@lInjuryTreatment nvarchar(500),@lInjuryDiagnisis nvarchar(500),@lsurgery nvarchar(500)
,@lLastExaminationId bigint,@lLastDiagnosis nvarchar(500),@lLastRecomendation nvarchar(500),@lLastExaminationdate nvarchar(20),
@labnoramltest nvarchar(MAX),@lHealthAnalysis nvarchar(1000),@lRBS nvarchar(10),@lHBA1C nvarchar(10), @lHealthScoreDate nvarchar(20),
@lBMIDate nvarchar(20), @lBPDate nvarchar(20), @lBloodSugarDate nvarchar(20), @lCholesterolDate nvarchar(20), @lHBDate nvarchar(20),
@lMetabolicSyndrome bit, @lCVDMajorRisk bit, @lCVDMinorRisk bit, @lNCDsRisk bit,@lLDL nvarchar(10);

Select @lHealthIndexScore = (select top 1 Convert(decimal(10,2),Round(Isnull(D.HealthIndex,0),2)) 
from sExamination.tExamination E 
inner join sExamination.tDiagnosis D on D.SourceId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
Order by E.ExaminationDate desc)

Select @lHealthScoreDate = (select top 1 convert(varchar(20),ExaminationDate,103)
from sExamination.tExamination E
inner join sExamination.tDiagnosis D on D.SourceId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
Order by E.ExaminationDate desc)

Select @lOpdCount = Count(E.id)
from sExamination.tExamination E 
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
and STM.MainTypeId=8

Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103) -- mantis 27146, dt - 10/10/2023, Nidhi Pandey (remove Round() from weight)
from sExamination.tExamination E 
inner join sExamination.tVital V on V.SourceId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
Order by E.ExaminationDate desc

Select Top 1 @lBloodPressureSystolic=BloodPressureSystolic,@lBloodPressureDiastolic=BloodPressureDiastolic,
@lBPDate=convert(varchar(20),ExaminationDate,103)
from sExamination.tExamination E 
inner join sExamination.tVital V on V.SourceId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and Isnull(V.BloodPressureSystolic,0)>0 and Isnull(V.BloodPressureDiastolic,0)>0 
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
Order by E.ExaminationDate desc

Select Top 1 @lFBS=TRD.ServiceValue, @lBloodSugarDate=convert(varchar(20),ExaminationDate,103)
from sExamination.tTestRequestDetail TRD
		inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
		inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
		inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
		inner join sExamination.tExamination E on TR.SourceId = E.Id
		inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
		inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and TP.StaticTestParameterId = 19 and  Isnull(TRD.ServiceValue,'')<>'' 
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
Order By E.ExaminationDate desc

Select Top 1 @lRBS=TRD.ServiceValue
from sExamination.tTestRequestDetail TRD
		inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
		inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
		inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
		inner join sExamination.tExamination E on TR.SourceId = E.Id
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and TP.StaticTestParameterId = 21 and  Isnull(TRD.ServiceValue,'')<>''
Order By E.ExaminationDate desc

Select Top 1 @lHBA1C=TRD.ServiceValue
from sExamination.tTestRequestDetail TRD
		inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
		inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
		inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
		inner join sExamination.tExamination E on TR.SourceId = E.Id
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and TP.StaticTestParameterId = 25 and  Isnull(TRD.ServiceValue,'')<>''
Order By E.ExaminationDate desc

---LDL-----
Select Top 1 @lLDL=TRD.ServiceValue
from sExamination.tTestRequestDetail TRD
		inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
		inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
		inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
		inner join sExamination.tExamination E on TR.SourceId = E.Id
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and TP.StaticTestParameterId = 34 and  Isnull(TRD.ServiceValue,'')<>''
Order By E.ExaminationDate desc


Select Top 1 @lHB=TRD.ServiceValue, @lHBDate=convert(varchar(20),ExaminationDate,103)
from sExamination.tTestRequestDetail TRD
		inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id
		inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
		inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
		inner join sExamination.tExamination E on TR.SourceId = E.Id
		inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
		inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and TP.StaticTestParameterId = 2 and  Isnull(TRD.ServiceValue,'')<>'' 
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
Order By E.ExaminationDate desc

Select Top 1 @lchol=TRD.ServiceValue, @lCholesterolDate=convert(varchar(20),ExaminationDate,103)
from sExamination.tTestRequestDetail TRD
		inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
		inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
		inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
		inner join sExamination.tExamination E on TR.SourceId = E.Id
		inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
		inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and TP.StaticTestParameterId = 31 and  Isnull(TRD.ServiceValue,'')<>'' 
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
Order By E.ExaminationDate desc

Select  @lTreatment = COALESCE(@lTreatment,'') + Isnull(SIM.Title,'') + ','
From sExamination.tExamination E
LEFt join sExamination.tPrescription P on P.SourceId=E.id
LEFt join sExamination.tPrescriptionDetail PD on PD.PrescriptionId=p.id
Left join sIp.tStockItemMaster SIM on SIM.id=PD.StockItemId
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=8
and E.id in(Select Top 1 E.ID from sExamination.tExamination E inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95 and STM.MainTypeId=8
AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
Order By E.ExaminationDate desc)
Order By E.ExaminationDate desc

print @lTreatment
SET @lTreatment = Replace(LEFT(@lTreatment, LEN(@lTreatment) - 1),',','</br>')
print @lTreatment

select Top 1 @lPreviousOPDVisit = '<p class="color_black" style=""><span class="inner_content_left" style="">Date & Time :</span><span class="inner_content_right" style="">
'+convert(varchar(20),E.ExaminationDate,103)+' '+replace(replace(Right(convert(varchar(20),E.CreatedDateTime,100),7),'AM',' AM'),'PM',' PM')+'</span></p>
<p class="color_black" style=""><span class="inner_content_left" style="">Visit Purpose :</span><span class="inner_content_right" style="">'+ CM.Title +'</span></p>
<p class="color_black" style=""><span class="inner_content_left" style="">Diagnosis :</span><span class="inner_content_right" style="color: #7b6f10; font-weight: bold;">'+([sExamination].[fExistingDiseaseGet](E.ID))+'
</span></p><p class="color_black" style=""><span class="inner_content_left" style="">Treatment :</span><span class="inner_content_right" style="">'+ @lTreatment +'</span></p>'
from sExamination.tExamination E 
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
inner join sExamination.tCauseMaster CM on CM.Id=E.CauseId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=8
AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
Order By E.ExaminationDate desc

select Top 1 @lInjuryDate=Convert(varchar(20),IA.IncidentDate,104),@lInjuryTime=IncidentTime,@lInjuryDiagnisis=Isnull(IncidentRemark,''),@lInjuryTreatment=Isnull(TreatmentRemark,'')
From sIncident.tAccident IA
Inner JOIN sExamination.tExamination EE ON IA.ExaminationId=EE.Id 
Where EE.ParticipantSourceId=@rEmpId and EE.ParticipantSourceTypeId=95
Order by EE.ExaminationDate Desc

select @lsurgery= case when Isnull(IsSurgeryDone,0)= 1 then 'Yes' else 'No' end + '-' + Isnull(H.SurgeryRemark,'')
from sExamination.tHistory H
where H.ParticipantSourceId =@rEmpId and H.Isobsolete=0

select Top 1 @lLastExaminationId=E.Id,@lLastExaminationdate=convert(varchar(20),ExaminationDate,104),@lLastDiagnosis=Isnull(DiagnosisRemark,'')
,@lLastRecomendation=Isnull(RecommendationEnglish,'')
from sExamination.tExamination E 
inner join sExamination.tDiagnosis D on D.SourceId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=1
Order by E.ExaminationDate desc

select @labnoramltest = COALESCE(@labnoramltest,'') + TPM.Title + '- ' + TRD.ServiceValue + ' ,'
FROM sExamination.tTestRequest TR	
	INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id AND isnull(TR.IsObsolete,0) = 0
	INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id and TR.TestId = TD.TestId
	INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
where TR.SourceId=@lLastExaminationId and Isnull(TRD.IsAbnormal,0)<>0

SET @labnoramltest = Replace(LEFT(@labnoramltest, LEN(@labnoramltest) - 1),',','</br>')
print @lLastExaminationId

DECLARE @HabitName VARCHAR(1000)
(SELECT @HabitName = COALESCE(@HabitName,'') + ISNULL(H.Title,'')
+ '-' + Convert(varchar(10),ISNULL(HHD.Duration,'')) + ' ' + ISNULL(DUM.Title,'') + ', ' 
FROM sExamination.tHabitHygineDetail HHD 
INNER JOIN sExamination.tHabitHygine HH ON HH.Id = HHD.HabitHygineId 
INNER JOIN sExamination.tHabitTypeMaster H ON HHD.HabitId = H.Id
LEft Join sCommon.tDurationUnitMaster DUM on DUM.id=HHD.DurationUnitId
WHERE HH.SourceId = @lLastExaminationId AND HH.Isobsolete=0
)
  SET @HabitName = Replace(Replace(LEFT(@HabitName, LEN(@HabitName) - 1),',','</br>'),'0','')

declare @lConfValue int
		select @lConfValue = ISNULL(CS.ItemValue,CM.ItemValue)
		from sConfig.tConfigurationMaster as CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
		where CM.ItemKey = 'FirstAid.SetTrainingRenewal'

SELECT @lHealthAnalysis = COALESCE(@lHealthAnalysis,'') + HIM.Title + ' - '		
		+ Convert(varchar(100),CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints))))) + ' - '
		+ (SELECT (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints)))) AND CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI

.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints))))>RangeFrom)
		+ ' ,'
	FROM sExamination.tExamination AS EXM
	INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID=EXM.SetupId
	INNER JOIN sExamination.tSubTypeMaster SSM ON SSM.Id = STM.SubTypeId 
	INNER JOIN sExamination.tHealthIndex AS  HI ON HI.ExaminationId=EXM.Id  
	INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIM ON HIM.ID=HI.HealthIndexParameterId
WHERE EXM.ParticipantSourceTypeId=95 
	AND  HI.TotalPoints > 0
	AND EXM.Id=@lLastExaminationId
	AND  SSM.MainTypeId=1 
GROUP BY HI.HealthIndexParameterId,HIM.Title
	ORDER BY HI.HealthIndexParameterId

SET @lHealthAnalysis = Replace(LEFT(@lHealthAnalysis, LEN(@lHealthAnalysis) - 1),',','</br>')

DECLARE @HealthHeader varchar(max) = '',@HealthDetail varchar(max) = ''
SELECT @HealthHeader = '<tbody><tr><th>Date</th><th>HealthScore</th><tr>'

Select @HealthDetail = @HealthDetail + '<tr><td>'+ convert(varchar(20),E.ExaminationDate,104)+ '</td><td>' + Convert(varchar(10),Convert(decimal(10,2),Round((Isnull(D.HealthIndex,0)),2))) + '</td></tr>'
from sExamination.tExamination E 
inner join sExamination.tDiagnosis D on D.SourceId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0

--select @HealthHeader + @HealthDetail
print @HealthHeader + @HealthDetail + '</tbody>'

Select TOP 1 @lMetabolicSyndrome = ISNULL(DTE.MetabolicSyndrome, 0), @lCVDMajorRisk = ISNULL(DTE.CVDMajorRisk, 0), 
			 @lCVDMinorRisk = ISNULL(DTE.CVDMinorRisk, 0), @lNCDsRisk = ISNULL(DTE.NCDsRisk, 0)
from sExamination.tExamination E
inner join sExamination.tDiagnosisTrackerEmployee DTE on DTE.ExaminationId=E.Id
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
and STM.MainTypeId=1
Order by E.ExaminationDate desc

Select EM.Id AS EmployeeId,
	'Emp ID : ' + EM.Code as Code,	
	ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
	convert(varchar(20),(DATEDIFF(yy,EPD.DateOfBirth,GETDATE()))) + ' Years ' + ' ' + Isnull(GM.Title,'') AS Years,
	Isnull(BGM.Title,'') as BloodGroup,
	'Working Since Last ' + Convert(varchar(20),(DATEDIFF(yy,EJD.DateOfJoining,GETDATE()))) + ' Years ' as WorkingSince,
	'Dept: ' + ISNULL(ODM.Title,'') AS DepartmentName,
	'Emp Type : ' + Isnull(ETM.Title,'') as EmployeeType,
	'' as allergies,
	'Reporting Mgr : ' + ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') ReportingMangerName,
	ISNULL(EC.CompanyEmail,'') AS EmailId,
	ISNULL(EC.MobileNumber,'') AS MobileNumber,
	isnull(EC.PresentStreetOne,'') as Add1,
	isnull(EC.PresentStreetTwo,'') as Add2,
	isnull(EC.PresentStreetThree,'') + ','+isnull(EC.PresentCity,'')+','+isnull(EC.PresentState,'') as Add3,
	ISNULL(EC.MobileNumber,'') AS MobileNumber,
	--isnull(EI.EmployeePhoto,0) as EmployeePhoto
	(SELECT TOP 1 CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) as EmployeePhoto,
	Isnull(@lHealthIndexScore,0) as HEALTHSCORE,
	Isnull(@lOpdCount,0) as OpdCount,
	'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,
	'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,
	Isnull(@lHeight,0) as Height1,
	Isnull(@lWeight,0) as Weight1,
	Isnull(@lBMI,0) as BMI,
	convert(varchar(10),@lBloodPressureSystolic) + '/' + Convert(varchar(10),@lBloodPressureDiastolic) as BP,
	Isnull(@lFBS,'0') as BloodSugar,
	Isnull(@lHB,'0') + ' g/dl' as Haemoglobin,
	Isnull(@lchol,'0') as Cholesterol,
	@lPreviousOPDVisit as PreviousOPDVisit,
	Replace([sExamination].[fFamilyHistoryWithRelationGet](@rEmpId),'-','- ') as FamilyHistory,
	Replace([sExamination].[fHistoryGet_new](@rEmpId),'-',' ') as History,
	@lInjuryDate as InjuryDate,
	@lInjuryTime as InjuryTime,
	@lInjuryDiagnisis as InjuryDiagnisis,
	@lInjuryTreatment as InjuryTreatment,
	@lsurgery as surgery,
	@lLastExaminationdate as LastExaminationdate,
	@lLastDiagnosis as LastDiagnosis,
	@lLastRecomendation as LastRecomendation,
	[sExamination].[fExistingDiseaseWithDurationUnitGet](@lLastExaminationId) as ExistingDisease,
	@labnoramltest as AbnormalTest,
	@HabitName as Habits,
	Isnull(P.Remark,'') as Allergy,
	convert(varchar(20),isnull(EPD.FirstAidTrainingDate,''),104) as FirstAidTrainingDate,
	convert(varchar(20),DATEADD(d,@lConfValue, EPD.FirstAidTrainingDate),104) as NextTraningDate,
	LM.Title as Location,
	@lHealthAnalysis as HealthAnalysis,
	@HealthHeader + @HealthDetail + '</tbody>' as healthdata,
	Isnull(@lRBS,'0') as RBS,
	Isnull(@lHBA1C,'0') as HBA1C,
	Isnull(@lLDL,'0') as LDL,
	@lHealthScoreDate as HealthScoreDate,
	@lBMIDate as BMIDate,
	@lBPDate as BPDate,
	@lBloodSugarDate as BloodSugarDate,
	@lCholesterolDate as CholesterolDate,
	@lHBDate as HBDate,
	@lMetabolicSyndrome as MetabolicSyndrome, @lCVDMajorRisk as CVDMajorRisk, 
	@lCVDMinorRisk as CVDMinorRisk, @lNCDsRisk as NCDsRisk
FROM sHrm.tEmployeeMaster EM
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	INNER JOIN sCommon.tLocationMaster LM on LM.ID = EJD.EmployeeLocationId
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
	LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id = EJD.EmployeeJobTitleId
	Left JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
	Left JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EPD.BloodGroupId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM	ON EJD.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id=EJD.EmployeeTypeId
	LEFT JOIN Shrm.temployeemaster EM1 on EM1.Id=EJD.ReportingMangerEmployeeId
	left join sHrm.tEmployeeImages EI on EI.EmployeeId=EM.id
	left join sExamination.tPrompt P on P.ParticipantId	=EM.id and P.ParticipantSourceTypeId=95
Where EM.Id=@rEmpId
end
GO
PRINT N'Altering Procedure [sExamination].[pGetEmployeeExaminationViewDatas]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetEmployeeExaminationViewDatas]
@rExaminationId bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @lConfigurationValue varchar(5), @lOrgId int
	declare @lVitalRes varchar(max)='',@lDiagnosisRes varchar(max)='',@lTestRes varchar(max)='',@lPrescriptionRes varchar(max)=''
	declare @lVitalHead varchar(max)='',@lDiagnosisHead varchar(max)='',@lTestHead varchar(max)='',@lPrescriptionHead varchar(max)=''
	declare @lComplaintRes varchar(max)='',@lComplaintHead varchar(max)='',@lReferralRes varchar(max)='',@lReferralHead varchar(max)=''
	
	select @lOrgId = OrgId from sExamination.tExamination where Id = @rExaminationId
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @lOrgId, 0, 0, 0)	

	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpview
	select 'Height',Convert(varchar(50),Height) + ' Cm'	
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Height',Convert(varchar(50),Height) + ' Cm'	
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'Weight',convert(varchar,BodyWeight)+ ' Kg'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Weight',convert(varchar,BodyWeight)+ ' Kg'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview		
	select 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'Pulse',convert(varchar,Pulse) + ' /Min'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Pulse',convert(varchar,Pulse) + ' /Min'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @ExaminationNumber nvarchar(100);
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @ExaminationNumber = E.ExaminationNumber
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rExaminationId

	Declare @res nvarchar(max) = '';
	select @res = @res + '<div class="">
    <h6 class="py-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>OPD Number: </b>' + @ExaminationNumber + '</h6>
    </div>'

	select @lVitalHead = @lVitalHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Vital</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Vital" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Parameter</span></th><th scope="col"><span>Value</span></th></tr>'
	OPTION (RECOMPILE)

	select @lVitalRes = @lVitalRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col2,'') + '</span> </td>			
	</tr>' from @tbltmpview
	OPTION (RECOMPILE)

	select @lVitalRes = @lVitalRes + '</tbody></table></div></div></div>'
	select @lVitalRes = @res + @lVitalHead + @lVitalRes
	OPTION (RECOMPILE)

	declare @tbltmpComplaint table(tid int identity(1,1),col1 varchar(max))	
	insert into @tbltmpComplaint
	SELECT Remark from sExamination.tComplaint where SourceId = @rExaminationId and IsObsolete = 0
	union
	SELECT Remark from sExamination.tArchieveComplaint where SourceId = @rExaminationId and IsObsolete = 0
	OPTION (RECOMPILE)

	select @lComplaintHead = @lComplaintHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Complaint</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Prescription" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Complain</span></th></tr>'
	OPTION (RECOMPILE)

	select @lComplaintRes = @lComplaintRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>	
	</tr>' from @tbltmpComplaint
	OPTION (RECOMPILE)

	select @lComplaintRes = @lComplaintRes + '</tbody></table></div></div></div>'
	select @lComplaintRes = @lComplaintHead + @lComplaintRes
	OPTION (RECOMPILE)

	declare @tbltmpReferral table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max))
	insert into @tbltmpReferral
	SELECT C.Title,R.ContactPerson,o.FurtherActionRemark from sExamination.tReferral R inner join sCommon.tClinicMaster C on R.ReferToClinicId = C.Id
	left join sExamination.topd o on o.examinationid = R.SourceId
	where SourceId = @rExaminationId and IsObsolete = 0
	union
	SELECT C.Title,R.ContactPerson,o.FurtherActionRemark from sExamination.tArchieveReferral R inner join sCommon.tClinicMaster C on R.ReferToClinicId = C.Id
	left join sExamination.tArchieveopd o on o.examinationid = R.SourceId
	where SourceId = @rExaminationId and IsObsolete = 0
	OPTION (RECOMPILE)

	select @lReferralHead = @lReferralHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Referral</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Prescription" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Hospital</span></th><th scope="col"> <span>Contact Person</span></th><th scope="col"> <span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lReferralRes = @lReferralRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>	
	<td><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>	
	<td><span title="' + isnull(col3,'') + '" class="boxEllips">' + isnull(col3,'') + '</span> </td>	
	</tr>' from @tbltmpReferral
	OPTION (RECOMPILE)

	select @lReferralRes = @lReferralRes + '</tbody></table></div></div></div>'
	select @lReferralRes = @lReferralHead + @lReferralRes
	OPTION (RECOMPILE)

	declare @tbltmpdisese table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpdisese
	SELECT DM.Title,ED.Remark
	FROM sExamination.tExaminDisease E
	INNER JOIN sExamination.tExaminDiseaseDetail ED
	ON E.Id = ED.ExaminDiseaseId AND E.IsObsolete = 0	
	INNER JOIN sExamination.tDiseaseMaster DM
	ON DM.Id = ED.DiseaseId
	WHERE E.SourceId = @rExaminationId AND ED.IsObsolete = 0
	union
	SELECT DM.Title,ED.Remark
	FROM sExamination.tArchieveExaminDisease E
	INNER JOIN sExamination.tArchieveExaminDiseaseDetail ED
	ON E.Id = ED.ExaminDiseaseId AND E.IsObsolete = 0	
	INNER JOIN sExamination.tDiseaseMaster DM
	ON DM.Id = ED.DiseaseId
	WHERE E.SourceId = @rExaminationId AND ED.IsObsolete = 0
	OPTION (RECOMPILE)

	select @lDiagnosisHead = @lDiagnosisHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Diagnosis</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Vital" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Disease</span></th><th scope="col"><span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lDiagnosisRes = @lDiagnosisRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col2,'') + '</span> </td>			
	</tr>' from @tbltmpdisese
	OPTION (RECOMPILE)

	select @lDiagnosisRes = @lDiagnosisRes + '</tbody></table></div></div></div>'
	select @lDiagnosisRes = @lDiagnosisHead + @lDiagnosisRes
	OPTION (RECOMPILE)

	declare @tbltmptest table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max))	
	insert into @tbltmptest
	SELECT TP.Title,TRD.ServiceValue,TRD.Remark
	FROM sExamination.tTestRequestDetail TRD
	INNER JOIN sExamination.tTestRequest TR	ON TRD.TestRequestId = TR.Id
	INNER JOIN sOrderEntry.tTestDetail TD on TD.Id = TRD.TestDetailId
	INNER JOIN sOrderEntry.tTestParameterMaster TP	on TD.TestParameterId = TP.Id
	WHERE TR.SourceId = @rExaminationId AND TP.IsObsolete = 0 and TRD.ServiceValue <> '-- Select --'
	union
	SELECT TP.Title,TRD.ServiceValue,TRD.Remark
	FROM sExamination.tArchieveTestRequestDetail TRD
	INNER JOIN sExamination.tArchieveTestRequest TR
	ON TRD.TestRequestId = TR.Id
	INNER JOIN sOrderEntry.tTestDetail TD
	on TD.Id = TRD.TestDetailId
	INNER JOIN sOrderEntry.tTestParameterMaster TP
	on TD.TestParameterId = TP.Id
	WHERE TR.SourceId = @rExaminationId AND TP.IsObsolete = 0 and TRD.ServiceValue <> '-- Select --'
	OPTION (RECOMPILE)

	select @lTestHead = @lTestHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Test</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Prescription" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Parameter</span></th><th scope="col"><span>Result</span></th><th scope="col"><span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col2,'') + '</span> </td>
	<td><span title="' + isnull(col3,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col3,'') + '</span> </td>			
	</tr>' from @tbltmptest
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '</tbody></table></div></div></div>'
	select @lTestRes = @lTestHead + @lTestRes
	
	declare @tbltmpPres table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),
	col4 varchar(max),col5 varchar(max),col6 varchar(max))
	insert into @tbltmpPres
	SELECT SM.Title,PD.Dosage,FM.Title,S.Title,PD.Duration,PD.PrescribedQuantity
	from sExamination.tPrescriptionDetail PD
	inner join sExamination.tPrescription P on PD.PrescriptionId = P.Id
	inner join sIp.tStockItemMaster SM on SM.Id = PD.StockItemId
	LEFT JOin sIp.tDrugDosageFrequencyMaster FM on PD.DrugDosageFrequencyId = FM.Id
	LEFT JOin sIp.tDrugScheduleMaster S on PD.DrugDosageScheduleId = S.Id
	where PD.IsObsolete = 0 and P.IsObsolete = 0
	and P.SourceId = @rExaminationId
	union
	SELECT SM.Title,PD.Dosage,FM.Title,S.Title,PD.Duration,PD.PrescribedQuantity
	from sExamination.tArchievePrescriptionDetail PD
	inner join sExamination.tArchievePrescription P on PD.PrescriptionId = P.Id
	inner join sIp.tStockItemMaster SM on SM.Id = PD.StockItemId
	LEFT JOin sIp.tDrugDosageFrequencyMaster FM on PD.DrugDosageFrequencyId = FM.Id
	LEFT JOin sIp.tDrugScheduleMaster S on PD.DrugDosageScheduleId = S.Id
	where PD.IsObsolete = 0 and P.IsObsolete = 0
	and P.SourceId = @rExaminationId
	OPTION (RECOMPILE)

	select @lPrescriptionHead = @lPrescriptionHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Prescription</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Vital" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Name</span></th><th scope="col"><span>Dose</span></th>
	<th scope="col"><span>Frequency</span></th><th scope="col"><span>Schedule</span></th>
	<th scope="col"><span>Days</span></th><th scope="col"><span>Quantity</span></th></tr>'
	OPTION (RECOMPILE)

	select @lPrescriptionRes = @lPrescriptionRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>			
	<td><span title="' + isnull(col3,'') + '" class="boxEllips">' + isnull(col3,'') + '</span> </td>			
	<td><span title="' + isnull(col4,'') + '" class="boxEllips">' + isnull(col4,'') + '</span> </td>			
	<td><span title="' + isnull(col5,'') + '" class="boxEllips">' + isnull(col5,'') + '</span> </td>			
	<td><span title="' + isnull(col6,'') + '" class="boxEllips">' + isnull(col6,'') + '</span> </td>			
	</tr>' from @tbltmpPres
	OPTION (RECOMPILE)

	select @lPrescriptionRes = @lPrescriptionRes + '</tbody></table></div></div></div>'
	select @lPrescriptionRes = @lPrescriptionHead + @lPrescriptionRes
	OPTION (RECOMPILE)

	select isnull(@lVitalRes,'') as Vital,isnull(@lDiagnosisRes,'') as Diagnos,isnull(@lTestRes,'') as Test,
	isnull(@lPrescriptionRes,'') as Pres,isnull(@lComplaintRes,'') as Comp,isnull(@lReferralRes,'') as Ref
	OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off
end
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsListReviewGetExport]...';


GO
  
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGetExport]    
(    
    @rOrgId SMALLINT,    
    @rFromDate NVARCHAR(50) = NULL,    
    @rToDate NVARCHAR(50) = NULL,    
    @rDoctorId BIGINT = 0,    
    @rStatusId VARCHAR(50) = 0,    
    @rCodeLike NVARCHAR(MAX) = ''    
)    
AS    
BEGIN    
    SET NOCOUNT ON;    
    SET DATEFORMAT dmy;        -- ✅ FORCE DD/MM/YYYY parsing    
    
    DECLARE     
        @FromDate DATETIME = NULL,    
        @ToDate DATETIME = NULL;    
    
    
DECLARE @StatusIds TABLE (Id INT);    
    
INSERT INTO @StatusIds (Id)    
SELECT T.X.value('.', 'INT')    
FROM (    
    SELECT CAST(    
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'    
        AS XML    
    ) AS XmlData    
) A    
CROSS APPLY XmlData.nodes('/x') AS T(X);    
    
    -- Map rStatusId to text    
    --DECLARE @StatusText NVARCHAR(20) = NULL;    
    --IF @rStatusId = 1 SET @StatusText = 'New';    
    --IF @rStatusId = 2 SET @StatusText = 'Open';    
    --IF @rStatusId = 3 SET @StatusText = 'Close';    
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';    
    
    -----------------------------------------    
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION    
    -----------------------------------------    
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')    
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY    
    
    IF (@rToDate IS NOT NULL AND @rToDate <> '')    
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day    
    
    -----------------------------------------    
    -- If no code, make it empty    
    -----------------------------------------    
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';    
    
    BEGIN TRY    
        SELECT     
         --   TD.Id AS IntimationId,    
              TD.EmpCode AS [Employee Code],    
         CASE     
              WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')    
              THEN TD.ProposerName    
              ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')    
              END AS EmployeeName,        
      VEMDS.Designation as Designation,    
      SCT.Title AS Business,    
      LM.Title AS [Hr Location],    
               CASE     
                            WHEN TD.TicketStatus != 'New'     
                                THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')    
                            ELSE 'System'    
                        END AS [Assigned By],    
      ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS [Assigned To],    
        TD.BeneficiaryName,    
      TD.Relation,    
      TD.Age,    
  TD.HospitalName as [Hospital Name],    
         TD.State,    
      TD.NetworkCity as [Network City],    
      ISNULL(ECD.MobileNumber, '') AS [Mobile (Oracle)],    
      TD.Mobile1 as [Mobile (PHS)],    
      TD.NatureOfIllness as [Nature Of Illness],    
                        STUFF((    
                           SELECT     
                               CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)     
                               + ': ' + R.Remark    
                           FROM sHospitalization.tIntimationRemark R    
                           WHERE R.HospitalizationIntimationDetailId = Td.Id    
                           ORDER BY R.CreatedDateTime DESC    
                           FOR XML PATH(''), TYPE    
                        ).value('.', 'nvarchar(max)'), 1, 1, '') AS [Remarks],    
      TD.TicketStatus as [Status]  ,  
      Isnull(TD.TreatingDoctor,'NA') as TreatingDoctor  
    
        FROM [sHospitalization].[tIntimationDetails] TD    
     --   INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD     
         --   ON  TD.IntimationAssignedDoctorId = AD.Id    
        LEFT JOIN [sHrm].[tEmployeeMaster] EMD     
            ON EMD.Id = TD.AssignedDoctorId    
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP     
            ON EMP.Id = TD.ParticipantSourceId    
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD     
            ON ECD.EmployeeId = EMP.Id    
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD     
            ON EJD.EmployeeId = EMP.Id    
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM     
            ON ETM.Id = EJD.EmployeeTypeId    
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM     
            ON ECM.Id = EJD.EmployeeCompanyId    
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM     
            ON CGM.Id = ECM.CompanyGroupId    
        LEFT JOIN [sHrm].[tVerticalMaster] VTM     
            ON VTM.Id = CGM.VerticalId    
        LEFT JOIN [sHrm].[tSectorMaster] SCT     
            ON SCT.Id = VTM.SectorId    
        LEFT JOIN [sCommon].[tLocationMaster] LM     
            ON LM.Id = EJD.EmployeeLocationId    
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM     
            ON DGM.Id = EJD.OrganizationDepartmentId    
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM     
            ON ODM.Id = EJD.OrganizationDepartmentId    
        LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS     
            ON VEMDS.EmployeeId = TD.ParticipantSourceId    
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1     
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId    
     LEFT JOIN [sHrm].[vExtEmployeeMaster]   VEMDS2    
            ON VEMDS2.UserId = TD.UpdatedUserId    
   LEFT JOIN [sHrm].[tGradeMaster] GRD     
            ON GRD.Id = VEMDS.GradeId    
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS     
            ON EMDS.Id = EJD.EmployeeDesignationId    
    
        WHERE     
            TD.OrgId = @rOrgId    
            AND (TD.AssignedDoctorId = @rDoctorId OR @rDoctorId = 0)    
    
            -----------------------------------------    
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)    
            -----------------------------------------    
            AND (    
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)    
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)    
            )    
    
            AND (    
                EXISTS (    
                    SELECT 1    
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues    
                    WHERE     
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')    
                        OR    
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)    
                )    
                OR @rCodeLike = ''    
            )    
            AND (    
                --TD.TicketStatus = @StatusText    
               @rStatusId = '0'    
                   OR TD.TicketStatus IN (    
                       SELECT    
                           CASE Id    
                               WHEN 1 THEN 'New'    
                               WHEN 2 THEN 'Open'    
                               WHEN 3 THEN 'Close'    
                           END    
                       FROM @StatusIds    
                   )    
    
            )    
    
        ORDER BY TD.CreatedDateTime DESC;    
    END TRY    
    
    BEGIN CATCH    
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSAGE();    
        INSERT INTO [sHospitalization].[tErrorLog]    
        (    
            ErrorMessage,     
            StoredProcedure,     
            ErrorDateTime,     
            UserId,     
            OrgId    
        )    
        VALUES    
        (    
            @ErrMsg,     
            'pIntimationDetailsListReviewGet',     
            GETUTCDATE(),     
            NULL,     
            @rOrgId    
        );    
    END CATCH    
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsListReviewGet]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGet]    
(                
    @rOrgId SMALLINT,                
    @rFromDate NVARCHAR(50) = NULL,                
    @rToDate NVARCHAR(50) = NULL,                
    @rDoctorId BIGINT = 0,                
    @rStatusId VARCHAR(50) = 0,                
    @rCodeLike NVARCHAR(MAX) = ''                
)                
AS                
BEGIN                
    SET NOCOUNT ON;                
    SET DATEFORMAT dmy;                
                
    DECLARE                 
        @FromDate DATETIME = NULL,                
        @ToDate DATETIME = NULL;                
                
DECLARE @StatusIds TABLE (Id INT);          
    
                
INSERT INTO @StatusIds (Id)                
SELECT T.X.value('.', 'INT')                
FROM (                
    SELECT CAST(                
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'                
        AS XML                
    ) AS XmlData                
) A                
CROSS APPLY XmlData.nodes('/x') AS T(X);                
                
   ---------------------------------------------------    
    -- Date handling    
    ---------------------------------------------------    
    IF (ISNULL(@rFromDate, '') <> '')    
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);    
    
    IF (ISNULL(@rToDate, '') <> '')    
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));    
    
   ---------------------------------------------------    
    -- Cache EventTemplate (IMPORTANT)    
    ---------------------------------------------------    
    DECLARE    
        @MailSubject NVARCHAR(MAX),    
        @MailTemplate NVARCHAR(MAX);    
    
    SELECT TOP 1    
        @MailSubject = MailSubject,    
        @MailTemplate = Template    
    FROM sAlert.tEventTemplate    
    WHERE OrgId = 1002    
      AND EventId = 108    
      AND IsAutoSend = 1;    
                
     IF OBJECT_ID('tempdb..#AlertLogLatest') IS NOT NULL  
    DROP TABLE #AlertLogLatest;  
  
SELECT  
    ClaimIntimationDetailId,  
    MAX(CreatedDateTime) AS CreatedDate  
INTO #AlertLogLatest  
FROM sAlert.tAlertLog WITH (NOLOCK)  
GROUP BY ClaimIntimationDetailId;  
  
    -----------------------------------------                
    -- If no code, make it empty                
    -----------------------------------------                
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';                
                
    BEGIN TRY                
        SELECT                 
            TD.Id AS IntimationId, TD.EmpCode AS EmployeeCode, TD.BeneficiaryName, TD.Relation,              
                          
   CASE    
                WHEN UPPER(ISNULL(TD.Relation, '')) = 'SELF'    
                     AND VEMDS.EmployeeId = TD.ParticipantSourceId    
                THEN ISNULL(VEMDS.Age, TD.Age)    
                ELSE TD.Age    
            END AS Age,    
       
            TD.HospitalName, TD.NetworkCity,TD.State,TD.StatusOfIntimation,                
            TD.TypeOfIntimation,                
            TD.FIRNo,                
            TD.CreatedDateTime,                
            TD.TicketStatus AS StatusName,                
            TD.Grade AS Grade,                
            TD.NatureOfIllness,                
            TD.IntimationNumber,                
            TD.ClaimType,                
            TD.DateOfIntimation,                
            TD.DateOfAdmission,                
            TD.DateOfDischarge,                
            TD.TicketNumber,                
            TD.Remarks,                
                
            ISNULL(VEMDS1.FirstName,'') + ' ' + ISNULL(VEMDS1.LastName,'') AS AssignedDoctor,    
            EMDS.Id AS DesignationId,            
   CASE    
                WHEN ISNULL(VEMDS.FirstName,'') = '' AND ISNULL(VEMDS.LastName,'') = ''    
                THEN TD.ProposerName    
                ELSE ISNULL(VEMDS.FirstName,'') + ' ' + ISNULL(VEMDS.LastName,'')    
          END AS EmployeeName,    
               
                
            ISNULL(ECD.CompanyEmail,'') AS CompanyEmail,    
            ISNULL(VEMDS.MobileNumber,'') AS OracleMobile,    
            ISNULL(TD.Mobile1,'') AS ApiMobile,               
            
            SCT.Title AS Business,                
            VTM.Title AS Vertical,                
            CGM.Title AS CompanyGroup,                
            ECM.Title AS Company,                
  LM.Title AS Location,                
            DGM.Title AS DepartmentGroup,                
            ODM.Title AS Department,                
            ETM.Title AS EmployeeType,                
            GRD.Title AS GradeTitle,                
   VEMDS.Designation as DesignationName,                
                
            TD.UpdatedDateTime AS LastActionDate,                
            TD.AssignedDoctorId AS DoctorEmployeeId,                
   TD.ParticipantSourceId as EmployeeId,                
                
ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignDoctor,                
ISNULL(VEMDS1.ExtensionNo,'') DoctorExtensionNo,                
ISNULL(VEMDS1.MobileNumber,'') DoctorMobileNumber,                
CASE      
      
    WHEN TDLog.PreviousDoctorEmployeeId IS NOT NULL      
        THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')      
    ELSE 'System'      
END AS AssignBYDoctor      
,            AL.CreatedDate,    
            
                
                
            STUFF((SELECT ', ' + R.Remark                
                FROM sHospitalization.tIntimationRemark R                
                WHERE R.HospitalizationIntimationDetailId = TD.Id                
                ORDER BY R.CreatedDateTime DESC                
                FOR XML PATH(''), TYPE                
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,                
                
            (                
                SELECT                 
                    R.Id,                
                    R.Remark,                
                    R.CreatedDateTime,                
                    R.CreatedUserId                
                FROM sHospitalization.tIntimationRemark R                
                WHERE R.HospitalizationIntimationDetailId = TD.Id                
                ORDER BY R.CreatedDateTime DESC                
                FOR JSON PATH                
            ) AS RemarkHistoryJSON,    
   Isnull(TD.TreatingDoctor,'NA') as TreatingDoctor,    
     CASE     
        WHEN TD.Flag = 1    
             AND YEAR(TD.CreatedDateTime) = YEAR(GETDATE())    
        THEN 'Repeat Case'    
        ELSE ''    
    END AS RepeatCaseTitle,    
 ECD1.CompanyEmail as Reportingmanagermail,    
  @MailSubject AS MailSubject, @MailTemplate AS MailTemplate    
                
        FROM [sHospitalization].[tIntimationDetails] TD                
        --INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD                 
         --   ON  TD.IntimationAssignedDoctorId = AD.Id                
        Left JOIN [sHrm].[tEmployeeMaster] EMD                 
            ON EMD.Id = TD.AssignedDoctorId                
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP                 
            ON EMP.Id = TD.ParticipantSourceId                
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD                 
            ON ECD.EmployeeId = EMP.Id                
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD                 
            ON EJD.EmployeeId = EMP.Id                
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM                 
            ON ETM.Id = EJD.EmployeeTypeId                
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM                 
            ON ECM.Id = EJD.EmployeeCompanyId                
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM                 
            ON CGM.Id = ECM.CompanyGroupId                
        LEFT JOIN [sHrm].[tVerticalMaster] VTM                 
            ON VTM.Id = CGM.VerticalId                
        LEFT JOIN [sHrm].[tSectorMaster] SCT                 
            ON SCT.Id = VTM.SectorId                
        Left JOIN [sCommon].[tLocationMaster] LM                 
            ON LM.Id = EJD.EmployeeLocationId                
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM                 
            ON DGM.Id = EJD.OrganizationDepartmentId                
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM                 
            ON ODM.Id = EJD.OrganizationDepartmentId                
                
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS                 
            ON EMDS.Id = EJD.EmployeeDesignationId                
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS                 
            ON VEMDS.EmployeeId = TD.ParticipantSourceId                
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1                 
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId                
     LEFT JOIN [sHrm].[vExtEmployeeMaster]    VEMDS2                
            ON VEMDS2.UserId = TD.UpdatedUserId                
     LEFT JOIN [sHrm].[tGradeMaster] GRD                 
            ON GRD.Id = VEMDS.GradeId           
 LEFT JOIN [sHrm].[tEmployeeCommunications] ECD1                 
            ON ECD1.EmployeeId = EJD.ReportingMangerEmployeeId    
OUTER APPLY      
(      
    SELECT TOP 1 PreviousDoctorEmployeeId      
    FROM sHospitalization.tIntimationDoctorAssignmentLog L      
    WHERE L.HospitalizationIntimationDetailId = TD.Id      
    ORDER BY L.AssignedDate DESC      
) TDLog      
  LEFT JOIN #AlertLogLatest AL  
    ON AL.ClaimIntimationDetailId = TD.Id   
    
                
        WHERE                 
            TD.OrgId = @rOrgId                
            AND (TD.AssignedDoctorId = @rDoctorId OR @rDoctorId = 0)                
            -----------------------------------------                
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)                
            -----------------------------------------                
            AND (                
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)                
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)                
            )                
                
            AND (                      EXISTS (                
                    SELECT 1                
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues                
                    WHERE                 
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')                
                        OR                
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)                
                )                
                OR @rCodeLike = ''                
            )                
            AND (                
                        
                
                   @rStatusId = '0'                
                   OR TD.TicketStatus IN (                
             SELECT                
                           CASE Id                
                               WHEN 1 THEN 'New'                
                               WHEN 2 THEN 'Open'                
                               WHEN 3 THEN 'Close'                
                           END                
                       FROM @StatusIds                
                   )                
            )                
                
        ORDER BY TD.CreatedDateTime DESC         
   OPTION (RECOMPILE);    
    END TRY                
                
    BEGIN CATCH                
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSage();                
        INSERT INTO [sHospitalization].[tErrorLog]                
        (                
            ErrorMessage,                 
            StoredProcedure,                 
            ErrorDateTime,                 
            UserId,                 
            OrgId                
        )                
        VALUES                
        (                
            @ErrMsg,                 
            'pIntimationDetailsListReviewGet',                 
            GETUTCDATE(),                 
            NULL,                 
            @rOrgId                
        );                
    END CATCH                
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pDashboardClosedDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardClosedDetailsGetAll]        
    @rFromDate NVARCHAR(50) = NULL,              
    @rToDate NVARCHAR(50) = NULL,              
    @rDoctorId NVARCHAR(50) = NULL,              
    @rStatus NVARCHAR(50) = NULL,              
    @rState NVARCHAR(50) = NULL,            
 @rBussnessid NVARCHAR(1000) = NULL,             
    @rOrgId BIGINT = NULL              
AS              
BEGIN                      
    SET NOCOUNT ON;                    
                    
                
    IF @rFromDate = '' SET @rFromDate = NULL;                    
    IF @rToDate = '' SET @rToDate = NULL;                    
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;                    
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;                    
    IF @rBussnessid = '' OR @rBussnessid = '0' SET @rBussnessid = NULL;                
    DECLARE @FromDateConverted DATE = NULL;                    
    DECLARE @ToDateConverted DATE = NULL;                    
                
    IF @rFromDate IS NOT NULL                    
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);            
                    
    IF @rToDate IS NOT NULL                    
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);            
                 
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)                    
    BEGIN                    
        DECLARE @tmp DATE;                    
        SET @tmp = @FromDateConverted;                    
        SET @FromDateConverted = @ToDateConverted;                    
        SET @ToDateConverted = @tmp;                    
    END                    
                    
                
    DECLARE @DoctorIdConverted BIGINT = NULL;                    
    IF ISNUMERIC(@rDoctorId) = 1                    
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);                    
                    
                
     SELECT ROW_NUMBER() OVER (ORDER BY TicketNumber) AS [Sr.No.] ,          
  [Employee Code],         
  [Employee Name],        
  [Business],         
  [Hr Location],        
  [Beneficiary Name],         
  [Relation],          
    [Treating Doctor],        
    [Age],        
    [Nature Of Illness],         
    [Assigned Doctor],         
    [Status], [Remarks],         
    [Hospital Name],          
       [Network City],        
    [State],         
    [Claim Type],        
    [Date Of Intimation]         
 from          
 (           
 SELECT distinct  PAL.TicketNumber,         
 PAL.EmpCode AS [Employee Code],        
 PAL.ProposerName AS [Employee Name],        
 SCT.Title as Business,          
 LM.Title AS [Hr Location],        
 PAL.BeneficiaryName as [Beneficiary Name],        
 PAL.Relation,        
 Isnull(PAL.TreatingDoctor,'NA') as [Treating Doctor],        
 --  PAL.TreatingDoctor,        
 PAL.Age,            
 PAL.NatureOfIllness as [Nature Of Illness],        
   CUR.EmployeeName AS [Assigned Doctor],        
   PAL.TicketStatus AS [Status],              
      STUFF(( SELECT CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103) + ': ' + R.Remark            
        FROM sHospitalization.tIntimationRemark R            
        WHERE R.HospitalizationIntimationDetailId = pal.Id            
        ORDER BY R.CreatedDateTime DESC            
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,          
      Pal.HospitalName as [Hospital Name],        
   PAL.NetworkCity as [Network City],PAL.State as [State],PAL.ClaimType as [Claim Type],            
      CASE             
      WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)            
      THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)            
      ELSE             
      CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103) + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)            
      END AS [Date Of Intimation],PAL.CreatedDateTime                     
                    
    FROM [sHospitalization].[tIntimationDetails] PAL                 
 --INNER JOIN sHospitalization.tIntimationAssignedDoctor ASID On ASID.DoctorEmployeeId =PAL.AssignedDoctorId                 
-- LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM ON SM.Id = PAL.IntimationAssignedDoctorId                  
    LEFT JOIN [sSecurity].[tUser] UR ON UR.Id = PAL.CreatedUserId AND UR.IsObsolete = 0 AND UR.OrgId = PAL.OrgId                    
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR ON CUR.EmployeeId = PAL.AssignedDoctorId          
   -- LEFT JOIN [sHrm].[tSectorMaster] HosB ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId          
    LEFT JOIN [sHrm].[tEmployeeMaster] EMD ON EMD.Id = PAL.AssignedDoctorId                      
    LEFT JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.Id = PAL.ParticipantSourceId                      
    LEFT JOIN [sHrm].[tEmployeeCommunications] ECD ON ECD.EmployeeId = EMP.Id                      
    LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EMP.Id                      
    LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM ON ETM.Id = EJD.EmployeeTypeId                      
    LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM ON ECM.Id = EJD.EmployeeCompanyId                      
    LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM ON CGM.Id = ECM.CompanyGroupId                      
    LEFT JOIN [sHrm].[tVerticalMaster] VTM ON VTM.Id = CGM.VerticalId                      
    LEFT JOIN [sHrm].[tSectorMaster] SCT ON SCT.Id = VTM.SectorId                      
    LEFT JOIN [sCommon].[tLocationMaster] LM ON LM.Id = EJD.EmployeeLocationId                      
    LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM ON DGM.Id = EJD.OrganizationDepartmentId                      
    LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM ON ODM.Id = EJD.OrganizationDepartmentId          
    LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS ON EMDS.Id = EJD.EmployeeDesignationId                      
    LEFT JOIN [sHrm].[vExtEmployeeMaster] VEMDS ON VEMDS.EmployeeId = PAL.ParticipantSourceId                      
    LEFT JOIN [sHrm].[vEmployeeCommonDetail] VEMDS1 ON VEMDS1.EmployeeId = PAL.AssignedDoctorId                      
    LEFT JOIN [sHrm].[vEmployeeCommonDetail] VEMDS2 ON VEMDS2.EmployeeId = PAL.UpdatedUserId                      
    LEFT JOIN [sHrm].[tGradeMaster] GRD ON GRD.Id = VEMDS.GradeId                      
                      
    WHERE                     
       PAL.OrgId = @rOrgId AND PAL.IsObsolete = 0                
    --and PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId             
       AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)                    
       AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))                    
       AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)                    
       AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)            
    AND PAL.TicketStatus ='Close'          
    AND (@rState IS NULL OR @rState = '' OR @rState = '0' OR @rState = '- All -' OR PAL.State = @rState)         
 AND (@rBussnessid IS NULL OR @rBussnessid = '' OR @rBussnessid = '0' OR @rBussnessid = '- All -' OR SCT.id = @rBussnessid)        
 )tmp          
 ORDER BY tmp.CreatedDateTime ASC;                 
END
GO
PRINT N'Altering Procedure [sHospitalization].[pDashboardDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardDetailsGetAll]            
    @rFromDate NVARCHAR(50) = NULL,            
    @rToDate NVARCHAR(50) = NULL,            
    @rDoctorId NVARCHAR(50) = NULL,            
    @rStatus NVARCHAR(50) = NULL,            
    @rState NVARCHAR(50) = NULL,            
   @rBussnessid NVARCHAR(1000) = NULL,             
    @rOrgId BIGINT = NULL            
AS            
BEGIN              
    SET NOCOUNT ON;            
          
    IF @rFromDate = '' SET @rFromDate = NULL;            
    IF @rToDate = '' SET @rToDate = NULL;            
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;            
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;            
   IF @rBussnessid = '' SET @rBussnessid = NULL;          
            
    DECLARE @FromDateConverted DATE = NULL;            
    DECLARE @ToDateConverted DATE = NULL;            
            
          
    IF @rFromDate IS NOT NULL            
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103)      
            
    IF @rToDate IS NOT NULL            
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);      
            
             
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)            
    BEGIN            
        DECLARE @tmp DATE;            
        SET @tmp = @FromDateConverted;            
        SET @FromDateConverted = @ToDateConverted;            
        SET @ToDateConverted = @tmp;            
    END            
            
    -- DoctorID conversion            
    DECLARE @DoctorIdConverted BIGINT = NULL;            
    IF ISNUMERIC(@rDoctorId) = 1            
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);            
            
          
            
    SELECT              
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],            
    PAL.EmpCode AS [Employee Code],            
     PAL.ProposerName AS [Employee Name],              
     --HosB.Title as Business,          
 SCT.Title as Business,         
 --  ISNULL(SCT.Title, 'Unknown') AS Business,      
    SCT.id as BusinessId,          
    LM.Title AS   [Hr Location],             
  PAL.BeneficiaryName as [Beneficiary Name],            
  PAL.Relation,          
 Isnull(PAL.TreatingDoctor,'NA') as TreatingDoctor,        
   PAL.Age,            
           PAL.NatureOfIllness as [Nature Of Illness]  ,           
       CUR.EmployeeName AS [Assigned Doctor],            
      PAL.TicketStatus AS [Status],              
      STUFF((            
    SELECT             
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)             
        + ': ' + R.Remark            
    FROM sHospitalization.tIntimationRemark R            
    WHERE R.HospitalizationIntimationDetailId = pal.Id            
    ORDER BY R.CreatedDateTime DESC            
    FOR XML PATH(''), TYPE            
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,          
  Pal.HospitalName as [Hospital Name],            
    PAL.NetworkCity as [Network City],            
      PAL.State as [State],              
  PAL.ClaimType as [Claim Type],            
      CASE             
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)            
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)            
          ELSE             
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)            
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)            
      END AS [Date Of Intimation]          
                 
          
    FROM [sHospitalization].[tIntimationDetails] PAL              
  --  INNER JOIN sHospitalization.tClaimIntimationAssignedDoctor SM              
      --  ON SM.DoctorEmployeeId = PAL.AssignedDoctorId            
    LEFT JOIN [sSecurity].[tUser] UR              
        ON UR.Id = PAL.CreatedUserId              
        AND UR.IsObsolete = 0             
        AND UR.OrgId = PAL.OrgId            
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR              
        ON CUR.EmployeeId = PAL.AssignedDoctorId             
    Left JOIN [sHrm].[tEmployeeMaster] EMD               
            ON EMD.Id = PAL.AssignedDoctorId
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP               
            ON EMP.Id = PAL.ParticipantSourceId               
    LEFT JOIN [sHrm].[tEmployeeCommunications] ECD               
            ON ECD.EmployeeId = EMP.Id              
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD               
            ON EJD.EmployeeId = EMP.Id              
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM               
            ON ETM.Id = EJD.EmployeeTypeId              
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM                   
  ON ECM.Id = EJD.EmployeeCompanyId              
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM               
            ON CGM.Id = ECM.CompanyGroupId              
        LEFT JOIN [sHrm].[tVerticalMaster] VTM               
            ON VTM.Id = CGM.VerticalId              
        LEFT JOIN [sHrm].[tSectorMaster] SCT               
            ON SCT.Id = VTM.SectorId              
        Left JOIN [sCommon].[tLocationMaster] LM               
            ON LM.Id = EJD.EmployeeLocationId              
             
          
      
              
    WHERE             
        PAL.OrgId = @rOrgId            
        AND PAL.IsObsolete = 0            
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)            
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))            
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)            
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)            
   AND (            
       @rState IS NULL            
       OR @rState = ''            
       OR @rState = '0'            
       OR @rState = '- All -'            
       OR PAL.State = @rState            
    )            
  AND (        
    @rBussnessid IS NULL       
    OR @rBussnessid = '0'      
    OR SCT.id = @rBussnessid      
)        
            
    ORDER BY PAL.CreatedDateTime ASC;            
END
GO
PRINT N'Altering Procedure [sHospitalization].[pDashboardDoctorDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardDoctorDetailsGetAll]            
    @rFromDate NVARCHAR(50) = NULL,            
    @rToDate NVARCHAR(50) = NULL,            
    @rDoctorId NVARCHAR(50) = NULL,            
    @rStatus NVARCHAR(50) = NULL,            
 @rState NVARCHAR(50) = NULL,            
    @rBussnessid NVARCHAR(1000) = NULL,  
    @rOrgId BIGINT = NULL            
AS            
BEGIN              
    SET NOCOUNT ON;            
            
        
    IF @rFromDate = '' SET @rFromDate = NULL;            
    IF @rToDate = '' SET @rToDate = NULL;            
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;            
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;            
                 IF @rBussnessid = '' SET @rBussnessid = NULL;     
    DECLARE @FromDateConverted DATE = NULL;            
    DECLARE @ToDateConverted DATE = NULL;            
        
    IF @rFromDate IS NOT NULL            
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);    
            
    IF @rToDate IS NOT NULL            
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);    
         
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)            
    BEGIN            
        DECLARE @tmp DATE;            
        SET @tmp = @FromDateConverted;            
        SET @FromDateConverted = @ToDateConverted;            
        SET @ToDateConverted = @tmp;            
    END            
            
        
    DECLARE @DoctorIdConverted BIGINT = NULL;            
    IF ISNUMERIC(@rDoctorId) = 1            
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);            
            
        
    SELECT      
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],    
    PAL.EmpCode AS [Employee Code],    
     PAL.ProposerName AS [Employee Name],      
     --HosB.Title as Business,    
	 	 SCT.Title as Business,
    LM.Title AS   [Hr Location],     
  PAL.BeneficiaryName as [Beneficiary Name],    
   PAL.Age,    
           PAL.NatureOfIllness as [Nature Of Illness]  ,   
       CUR.EmployeeName AS [Assigned Doctor],    
      PAL.TicketStatus AS [Status],      
      STUFF((    
    SELECT     
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)     
        + ': ' + R.Remark    
    FROM sHospitalization.tIntimationRemark R    
    WHERE R.HospitalizationIntimationDetailId = pal.Id    
    ORDER BY R.CreatedDateTime DESC    
    FOR XML PATH(''), TYPE    
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,  
  Pal.HospitalName as [Hospital Name],    
    PAL.NetworkCity as [Network City],    
      PAL.State as [State],      
  PAL.ClaimType as [Claim Type],    
      CASE     
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)    
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)    
          ELSE     
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)    
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)    
      END AS [Date Of Intimation]       
            
    FROM [sHospitalization].[tIntimationDetails] PAL         
 Inner Join sHospitalization.tIntimationAssignedDoctor ASID        
  On ASID.DoctorEmployeeId =PAL.AssignedDoctorId         
    LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM              
        ON SM.Id = PAL.IntimationAssignedDoctorId            
    LEFT JOIN [sSecurity].[tUser] UR              
        ON UR.Id = PAL.CreatedUserId              
        AND UR.IsObsolete = 0             
        AND UR.OrgId = PAL.OrgId            
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR              
        ON CUR.EmployeeId = PAL.AssignedDoctorId              
            
    Left JOIN [sHrm].[tSectorMaster] HosB              
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId            
            
    Left JOIN [sHrm].[tEmployeeMaster] EMD               
       ON EMD.Id = SM.DoctorEmployeeId              
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP               
   ON EMP.Id = PAL.ParticipantSourceId              
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD               
            ON ECD.EmployeeId = EMP.Id              
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD               
        ON EJD.EmployeeId = EMP.Id              
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM               
            ON ETM.Id = EJD.EmployeeTypeId              
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM               
            ON ECM.Id = EJD.EmployeeCompanyId              
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM               
            ON CGM.Id = ECM.CompanyGroupId              
        LEFT JOIN [sHrm].[tVerticalMaster] VTM               
            ON VTM.Id = CGM.VerticalId              
        LEFT JOIN [sHrm].[tSectorMaster] SCT               
            ON SCT.Id = VTM.SectorId              
        Left JOIN [sCommon].[tLocationMaster] LM               
            ON LM.Id = EJD.EmployeeLocationId              
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM               
            ON DGM.Id = EJD.OrganizationDepartmentId              
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM               
            ON ODM.Id = EJD.OrganizationDepartmentId              
              
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS               
            ON EMDS.Id = EJD.EmployeeDesignationId              
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS               
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId              
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1               
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId              
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2              
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId              
        LEFT JOIN [sHrm].[tGradeMaster] GRD               
            ON GRD.Id = VEMDS.GradeId              
              
    WHERE             
        PAL.OrgId = @rOrgId            
        AND PAL.IsObsolete = 0      
  AND PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId     
  and    PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId    
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)            
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))            
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)            
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)            
   AND (            
       @rState IS NULL            
       OR @rState = ''            
       OR @rState = '0'            
       OR @rState = '- All -'            
       OR PAL.State = @rState            
    )            
            			 AND (
    @rBussnessid IS NULL           -- When parameter is NULL, include all
    OR @rBussnessid = '0'          -- When '0', include all (for backward compatibility)
    OR SCT.id = @rBussnessid       -- Filter by specific business
)       
    ORDER BY PAL.CreatedDateTime ASC;            
END
GO
PRINT N'Altering Procedure [sHospitalization].[pDashboardNewticketDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardNewticketDetailsGetAll]                      
    @rFromDate NVARCHAR(50) = NULL,                      
    @rToDate NVARCHAR(50) = NULL,                      
    @rDoctorId NVARCHAR(50) = NULL,                      
    @rStatus NVARCHAR(50) = NULL,                      
   @rState NVARCHAR(50) = NULL,                    
   @rBussnessid NVARCHAR(1000) = NULL,                
   @rOrgId BIGINT = NULL                      
   AS                      
   BEGIN                            
    SET NOCOUNT ON;                          
                          
                      
    IF @rFromDate = '' SET @rFromDate = NULL;                          
    IF @rToDate = '' SET @rToDate = NULL;                          
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;                          
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;             
    IF @rBussnessid = '' OR @rBussnessid = '0' SET @rBussnessid = NULL;               
                      
    DECLARE @FromDateConverted DATE = NULL;                          
    DECLARE @ToDateConverted DATE = NULL;                          
                      
    IF @rFromDate IS NOT NULL                          
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);                  
                          
    IF @rToDate IS NOT NULL                          
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);                  
                       
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)                          
    BEGIN                          
        DECLARE @tmp DATE;                          
        SET @tmp = @FromDateConverted;                          
        SET @FromDateConverted = @ToDateConverted;                          
        SET @ToDateConverted = @tmp;                          
    END                          
                          
                      
    DECLARE @DoctorIdConverted BIGINT = NULL;                          
    IF ISNUMERIC(@rDoctorId) = 1                          
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);                          
                          
                      
       SELECT ROW_NUMBER() OVER (ORDER BY TicketNumber) AS [Sr.No.] ,            
       [Employee Code],         
      [Employee Name],        
      [Business],         
      [Hr Location],         
      [Beneficiary Name],        
      [Relation],            
      [TreatingDoctor],        
      [Age],        
      [Nature Of Illness],        
      [Assigned Doctor],         
      [Status], [Remarks],         
      [Hospital Name],            
         [Network City],         
      [State],         
      [Claim Type],         
      [Date Of Intimation]         
 from            
 (             
    SELECT distinct         
     PAL.TicketNumber,        
     PAL.EmpCode AS [Employee Code],        
     PAL.ProposerName AS [Employee Name],        
     SCT.Title as Business,            
     LM.Title AS [Hr Location],        
     PAL.BeneficiaryName as [Beneficiary Name],          
     PAL.Relation,          
     Isnull(PAL.TreatingDoctor,'NA') as TreatingDoctor,          
     PAL.Age,              
     PAL.NatureOfIllness as [Nature Of Illness],        
     CUR.EmployeeName AS [Assigned Doctor],        
     PAL.TicketStatus AS [Status],                
     STUFF(( SELECT CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103) + ': ' + R.Remark              
        FROM sHospitalization.tIntimationRemark R              
        WHERE R.HospitalizationIntimationDetailId = pal.Id              
        ORDER BY R.CreatedDateTime DESC              
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,            
     Pal.HospitalName as [Hospital Name],PAL.NetworkCity as [Network City],PAL.State as [State],PAL.ClaimType as [Claim Type],              
      CASE               
      WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)              
      THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)              
      ELSE               
      CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103) + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)              
    END AS [Date Of Intimation],PAL.CreatedDateTime                       
                      
    FROM [sHospitalization].[tIntimationDetails] PAL                   
   -- INNER JOIN sHospitalization.tIntimationAssignedDoctor ASID On ASID.DoctorEmployeeId =PAL.AssignedDoctorId                   
  --  LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM ON SM.Id = PAL.IntimationAssignedDoctorId                      
    LEFT JOIN [sSecurity].[tUser] UR ON UR.Id = PAL.CreatedUserId AND UR.IsObsolete = 0 AND UR.OrgId = PAL.OrgId                      
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR ON CUR.EmployeeId = PAL.AssignedDoctorId            
  --  LEFT JOIN [sHrm].[tSectorMaster] HosB ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId            
    LEFT JOIN [sHrm].[tEmployeeMaster] EMD ON EMD.Id = PAL.AssignedDoctorId                          
    LEFT JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.Id = PAL.ParticipantSourceId                        
    LEFT JOIN [sHrm].[tEmployeeCommunications] ECD ON ECD.EmployeeId = EMP.Id                        
    LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EMP.Id                        
    LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM ON ETM.Id = EJD.EmployeeTypeId                        
    LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM ON ECM.Id = EJD.EmployeeCompanyId                        
    LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM ON CGM.Id = ECM.CompanyGroupId                        
    LEFT JOIN [sHrm].[tVerticalMaster] VTM ON VTM.Id = CGM.VerticalId                        
    LEFT JOIN [sHrm].[tSectorMaster] SCT ON SCT.Id = VTM.SectorId                        
    LEFT JOIN [sCommon].[tLocationMaster] LM ON LM.Id = EJD.EmployeeLocationId                        
    LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM ON DGM.Id = EJD.OrganizationDepartmentId                        
    LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM ON ODM.Id = EJD.OrganizationDepartmentId            
    LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS ON EMDS.Id = EJD.EmployeeDesignationId                        
    LEFT JOIN [sHrm].[vExtEmployeeMaster] VEMDS ON VEMDS.EmployeeId = PAL.ParticipantSourceId                        
    LEFT JOIN [sHrm].[vEmployeeCommonDetail] VEMDS1 ON VEMDS1.EmployeeId = PAL.AssignedDoctorId                        
    LEFT JOIN [sHrm].[vEmployeeCommonDetail] VEMDS2 ON VEMDS2.EmployeeId = PAL.UpdatedUserId                        
    LEFT JOIN [sHrm].[tGradeMaster] GRD ON GRD.Id = VEMDS.GradeId                        
                        
    WHERE                       
       PAL.OrgId = @rOrgId AND PAL.IsObsolete = 0                  
       AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)                      
       AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))                      
       AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)                      
       AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)              
       AND PAL.TicketStatus ='New'            
       AND (@rState IS NULL OR @rState = '' OR @rState = '0' OR @rState = '- All -' OR PAL.State = @rState)             
       AND (@rBussnessid IS NULL OR @rBussnessid = '' OR @rBussnessid = '0' OR @rBussnessid = '- All -' OR SCT.id = @rBussnessid)          
 )tmp            
 ORDER BY tmp.CreatedDateTime ASC;                    
END
GO
PRINT N'Altering Procedure [sHospitalization].[pDashboardOpenAndNewDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardOpenAndNewDetailsGetAll]                
    @rFromDate NVARCHAR(50) = NULL,                
    @rToDate NVARCHAR(50) = NULL,                
    @rDoctorId NVARCHAR(50) = NULL,                
    @rStatus NVARCHAR(50) = NULL,                
    @rState NVARCHAR(50) = NULL,           
    @rBussnessid NVARCHAR(1000) = NULL,        
    @rOrgId BIGINT = NULL                
AS                
BEGIN                      
    SET NOCOUNT ON;                    
                    
                
    IF @rFromDate = '' SET @rFromDate = NULL;                    
    IF @rToDate = '' SET @rToDate = NULL;                    
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;                    
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;                    
    IF @rBussnessid = '' OR @rBussnessid = '0' SET @rBussnessid = NULL;               
    DECLARE @FromDateConverted DATE = NULL;                    
    DECLARE @ToDateConverted DATE = NULL;                    
                
    IF @rFromDate IS NOT NULL                    
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);            
                    
    IF @rToDate IS NOT NULL                    
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);            
                 
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)                    
    BEGIN                    
        DECLARE @tmp DATE;                    
        SET @tmp = @FromDateConverted;                    
        SET @FromDateConverted = @ToDateConverted;                    
        SET @ToDateConverted = @tmp;                    
    END                    
                    
                
    DECLARE @DoctorIdConverted BIGINT = NULL;                    
    IF ISNUMERIC(@rDoctorId) = 1                    
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);                    
                    
                
      SELECT ROW_NUMBER() OVER (ORDER BY TicketNumber) AS [Sr.No.] ,          
     [Employee Code],       
  [Employee Name],      
  [Business],       
  [Hr Location],       
  [Beneficiary Name],      
  [Relation],          
     [TreatingDoctor],      
  [Age],      
  [Nature Of Illness],      
  [Assigned Doctor],       
  [Status],      
  [Remarks],       
  [Hospital Name],          
     [Network City],       
  [State],       
  [Claim Type],      
  [Date Of Intimation] from          
 (           
 SELECT distinct  PAL.TicketNumber, PAL.EmpCode AS [Employee Code], PAL.ProposerName AS [Employee Name],SCT.Title as Business,          
      LM.Title AS [Hr Location],PAL.BeneficiaryName as [Beneficiary Name]        
   ,PAL.Relation,        
   Isnull(PAL.TreatingDoctor,'NA') as TreatingDoctor,        
   PAL.Age,            
      PAL.NatureOfIllness as [Nature Of Illness],CUR.EmployeeName AS [Assigned Doctor],PAL.TicketStatus AS [Status],              
      STUFF(( SELECT CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103) + ': ' + R.Remark            
        FROM sHospitalization.tIntimationRemark R            
        WHERE R.HospitalizationIntimationDetailId = pal.Id            
        ORDER BY R.CreatedDateTime DESC            
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,          
      Pal.HospitalName as [Hospital Name],PAL.NetworkCity as [Network City],PAL.State as [State],PAL.ClaimType as [Claim Type],            
      CASE             
      WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)            
      THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)            
      ELSE             
      CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103) + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)            
      END AS [Date Of Intimation],PAL.CreatedDateTime                     
                    
    FROM [sHospitalization].[tIntimationDetails] PAL                 
  --  INNER JOIN sHospitalization.tIntimationAssignedDoctor ASID On ASID.DoctorEmployeeId =PAL.AssignedDoctorId                 
    --LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM ON SM.Id = PAL.IntimationAssignedDoctorId                    
    LEFT JOIN [sSecurity].[tUser] UR ON UR.Id = PAL.CreatedUserId AND UR.IsObsolete = 0 AND UR.OrgId = PAL.OrgId                    
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR ON CUR.EmployeeId = PAL.AssignedDoctorId          
   -- LEFT JOIN [sHrm].[tSectorMaster] HosB ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId          
    LEFT JOIN [sHrm].[tEmployeeMaster] EMD ON EMD.Id = PAL.AssignedDoctorId                      
    LEFT JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.Id = PAL.ParticipantSourceId           
    LEFT JOIN [sHrm].[tEmployeeCommunications] ECD ON ECD.EmployeeId = EMP.Id                      
    LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EMP.Id                      
    LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM ON ETM.Id = EJD.EmployeeTypeId                      
    LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM ON ECM.Id = EJD.EmployeeCompanyId                      
    LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM ON CGM.Id = ECM.CompanyGroupId                      
    LEFT JOIN [sHrm].[tVerticalMaster] VTM ON VTM.Id = CGM.VerticalId                      
    LEFT JOIN [sHrm].[tSectorMaster] SCT ON SCT.Id = VTM.SectorId                      
    LEFT JOIN [sCommon].[tLocationMaster] LM ON LM.Id = EJD.EmployeeLocationId                      
    LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM ON DGM.Id = EJD.OrganizationDepartmentId                      
    LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM ON ODM.Id = EJD.OrganizationDepartmentId          
    LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS ON EMDS.Id = EJD.EmployeeDesignationId                      
    LEFT JOIN [sHrm].[vExtEmployeeMaster] VEMDS ON VEMDS.EmployeeId = PAL.ParticipantSourceId                      
    LEFT JOIN [sHrm].[vEmployeeCommonDetail] VEMDS1 ON VEMDS1.EmployeeId = PAL.AssignedDoctorId                      
    LEFT JOIN [sHrm].[vEmployeeCommonDetail] VEMDS2 ON VEMDS2.EmployeeId = PAL.UpdatedUserId                      
    LEFT JOIN [sHrm].[tGradeMaster] GRD ON GRD.Id = VEMDS.GradeId                      
                      
    WHERE                     
       PAL.OrgId = @rOrgId AND PAL.IsObsolete = 0                
       AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)                    
       AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))                    
       AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)                    
       AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)            
       AND PAL.TicketStatus ='Open'          
       AND (@rState IS NULL OR @rState = '' OR @rState = '0' OR @rState = '- All -' OR PAL.State = @rState)        
       AND (@rBussnessid IS NULL OR @rBussnessid = '' OR @rBussnessid = '0' OR @rBussnessid = '- All -' OR SCT.id = @rBussnessid)        
 )tmp          
 ORDER BY tmp.CreatedDateTime ASC;           
END
GO
PRINT N'Altering Procedure [sHospitalization].[pGetDoctorHospitalizationDataForDashboard]...';


GO
 CREATE OR ALTER PROCEDURE [sHospitalization].[pGetDoctorHospitalizationDataForDashboard]      
    @rFromDate NVARCHAR(50) = NULL,      
    @rToDate NVARCHAR(50) = NULL,      
    @rDoctorId NVARCHAR(50) = NULL,      
    @rStatus NVARCHAR(50) = NULL,      
 @rState NVARCHAR(50) = NULL,      
  @rBussnessid NVARCHAR(1000) = NULL,     
    @rOrgId BIGINT = NULL      
AS      
BEGIN      
    SET NOCOUNT ON;      
        
    -------------------------------------------------------------      
    -- 🔄 STEP 0: Convert Empty Strings ('') to NULL      
    -------------------------------------------------------------      
    IF @rFromDate = '' SET @rFromDate = NULL;      
    IF @rToDate = '' SET @rToDate = NULL;      
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;      
    IF @rStatus = '' SET @rStatus = NULL;      
 IF @rState = '' SET @rState = NULL;     
  IF @rBussnessid = '' SET @rBussnessid = NULL;  
      
   -- IF @rOrgId IS NULL SET @rOrgId = 9999;      
      
    -------------------------------------------------------------      
    -- 🔄 STEP 1: Convert NVARCHAR date inputs to DATE      
    -------------------------------------------------------------      
    --DECLARE @FromDateConverted DATE = TRY_CAST(@rFromDate AS DATE);      
    --DECLARE @ToDateConverted DATE = TRY_CAST(@rToDate AS DATE);      
    --DECLARE @DoctorIdConverted BIGINT = TRY_CAST(@rDoctorId AS BIGINT);      
      
 -------------------------------------------------------------      
-- STEP 1: Convert NVARCHAR date inputs to DATE (dd/MM/yyyy)      
-------------------------------------------------------------      
DECLARE @FromDateConverted DATE = NULL;      
DECLARE @ToDateConverted DATE = NULL;      
DECLARE @DoctorIdConverted BIGINT = TRY_CAST(@rDoctorId AS BIGINT);      
      
-- Convert FromDate      
IF (@rFromDate IS NOT NULL AND @rFromDate <> '')      
BEGIN      
    SET @FromDateConverted = CONVERT(DATE, @rFromDate, 103);      
END      
      
-- Convert ToDate      
IF (@rToDate IS NOT NULL AND @rToDate <> '')      
BEGIN      
    SET @ToDateConverted = CONVERT(DATE, @rToDate, 103);      
END      
      
-- Swap if reversed      
IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL      
    AND @FromDateConverted > @ToDateConverted)      
BEGIN      
    DECLARE @tmp DATE = @FromDateConverted;      
    SET @FromDateConverted = @ToDateConverted;      
    SET @ToDateConverted = @tmp;      
END      
      
      
    -------------------------------------------------------------      
    -- 🧹 STEP 2: Prepare base data      
    -------------------------------------------------------------      
    IF OBJECT_ID('tempdb..#BaseData') IS NOT NULL      
        DROP TABLE #BaseData;      
      
    SELECT       
        TD.Id,      
        TD.OrgId,      
        TD.BeneficiaryName,      
        TD.DateOfIntimation,      
        TD.DateOfAdmission,      
    CASE     
        WHEN TD.ParticipantSourceId IS NULL     
         AND TD.ParticipantSourceTypeId IS NULL     
            THEN 'Non-Oracle'    
        ELSE 'Oracle'    
    END AS OracleNonOracleType,    
    
        TD.DateOfDischarge,      
        TD.ClaimType,      
        TD.IntimationNumber,      
        TD.StatusOfIntimation,      
        TD.NetworkCity,      
        TD.State,      
        SM.StateName,      
        TD.HospitalName,      
        TD.Age,      
        TD.Relation,      
        TD.ProposerName,      
        TD.NatureOfIllness,      
        TD.TicketStatus,      
        TD.AssignedDoctorId,      
        ISNULL(      
            CASE       
                WHEN ISNULL(EM.EmployeePrefix, '') = ''       
                    THEN EM.FirstName + ' ' + ISNULL(EM.LastName, '')      
                ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + ISNULL(EM.LastName, '')      
            END,       
        'Unassigned') AS DoctorName,      
        TD.TicketNumber,      
        TD.TicketOpenDate,      
        TD.ModeOfStatus,      
        TD.Grade,      
        TD.GroupCode,      
        TD.AdmissionType,      
        CASE       
            WHEN TD.EstimatedAmount IS NOT NULL       
         AND TD.EstimatedAmount != ''      
                 AND ISNUMERIC(REPLACE(REPLACE(TD.EstimatedAmount, ',', ''), '.', '')) = 1      
            THEN TRY_CAST(REPLACE(TD.EstimatedAmount, ',', '') AS DECIMAL(18,2))      
            ELSE NULL       
        END AS EstimatedAmount,      
        TD.NetworkStatus,      
        TD.IsObsolete,      
        TD.Remarks,      
        TD.CreatedDateTime,      
    SCT.Title AS Business,    
        DATEDIFF(DAY, TD.TicketOpenDate, ISNULL(TD.DateOfDischarge, GETDATE())) AS AgeingDays,      
        CASE       
            WHEN TD.TicketStatus = 'Close' THEN 'Close'      
       WHEN TD.TicketStatus = 'New'   THEN 'New'      
            ELSE 'Open'      
        END AS StatusCategory      
    INTO #BaseData      
    FROM sHospitalization.tIntimationDetails TD      
    LEFT JOIN sHospitalization.tStateMaster SM      
        ON SM.StateName = TD.State AND SM.OrgId = TD.OrgId      
    LEFT JOIN sHrm.tEmployeeMaster EM      
        ON EM.Id = TD.AssignedDoctorId      
          LEFT JOIN [sHrm].[tEmployeeCommunications] ECD       
            ON ECD.EmployeeId = EM.Id      
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD       
            ON EJD.EmployeeId = EM.Id      
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM       
            ON ETM.Id = EJD.EmployeeTypeId      
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM       
            ON ECM.Id = EJD.EmployeeCompanyId      
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM       
            ON CGM.Id = ECM.CompanyGroupId      
        LEFT JOIN [sHrm].[tVerticalMaster] VTM       
            ON VTM.Id = CGM.VerticalId      
        LEFT JOIN [sHrm].[tSectorMaster] SCT       
            ON SCT.Id = VTM.SectorId      
        Left JOIN [sCommon].[tLocationMaster] LM       
            ON LM.Id = EJD.EmployeeLocationId      
    WHERE       
        TD.OrgId = @rOrgId      
        AND TD.IsObsolete = 0      
AND (      
        @FromDateConverted IS NULL       
        OR CAST(TD.DateOfIntimation AS DATE) >= @FromDateConverted      
    )      
AND (      
        @ToDateConverted IS NULL       
        OR CAST(TD.DateOfIntimation AS DATE) <= @ToDateConverted      
    )      
      
 AND (
    @rBussnessid IS NULL           -- When parameter is NULL, include all
    OR @rBussnessid = '0'          -- When '0', include all (for backward compatibility)
    OR SCT.id = @rBussnessid       -- Filter by specific business
)   
        AND (@DoctorIdConverted IS NULL OR TD.AssignedDoctorId = @DoctorIdConverted)      
        AND (@rStatus IS NULL OR @rStatus = '0' OR TD.TicketStatus = @rStatus)      
   And (@rState IS NULL OR @rState = '0' OR TD.State = @rState)      
      
      
      
-- select @rState      
      
    -------------------------------------------------------------      
    -- 🧾 STEP 3: Summary Data      
    -------------------------------------------------------------      
    IF OBJECT_ID('tempdb..#SummaryData') IS NOT NULL      
        DROP TABLE #SummaryData;      
      
    SELECT       
        COUNT(DISTINCT Id) AS TotalCases,      
        COUNT(DISTINCT AssignedDoctorId) AS TotalDoctors,      
        COUNT(DISTINCT State) AS TotalStates,      
        COUNT(DISTINCT HospitalName) AS TotalHospitals,      
        SUM(CASE WHEN StatusCategory = 'Close' THEN 1 ELSE 0 END) AS ClosedCases,      
        SUM(CASE WHEN StatusCategory = 'Open' THEN 1 ELSE 0 END) AS OpenCases,     
  SUM(CASE WHEN StatusCategory = 'New' THEN 1 ELSE 0 END) AS NewCases,    
        CAST(AVG(EstimatedAmount) AS DECIMAL(18,2)) AS AverageEstimatedAmount,      
        CAST(SUM(EstimatedAmount) AS DECIMAL(18,2)) AS TotalEstimatedAmount,      
        CAST(SUM(CASE WHEN StatusCategory = 'Close' THEN 1 ELSE 0 END) * 100.0 / NULLIF(COUNT(DISTINCT Id), 0) AS DECIMAL(5,2)) AS ClosureRate      
    INTO #SummaryData      
    FROM #BaseData;      
      
      
    -------------------------------------------------------------      
    -- 📊 STEP 4: Result Sets      
    -------------------------------------------------------------      
      
    -- 1️⃣ Monthly Trend Data      
    SELECT       
        FORMAT(DateOfIntimation, 'yyyy-MM') AS MonthYear,      
        FORMAT(DateOfIntimation, 'MMM yyyy') AS MonthYearDisplay,      
      COUNT(Id) AS CaseCount      
    FROM #BaseData      
    WHERE DateOfIntimation IS NOT NULL      
    GROUP BY FORMAT(DateOfIntimation, 'yyyy-MM'), FORMAT(DateOfIntimation, 'MMM yyyy')      
    ORDER BY MonthYear;      
      
    -- 2️⃣ Status Summary (Pie Chart)      
    SELECT       
        TicketStatus,      
        COUNT(Id) AS StatusCount,      
        CASE       
            WHEN TicketStatus = 'New' THEN '#36A2EB'      
            WHEN TicketStatus = 'Open' THEN '#FF6384'      
            WHEN TicketStatus = 'Close' THEN '#4BC0C0'      
            ELSE '#9966FF'      
        END AS ColorCode      
    FROM #BaseData      
    GROUP BY TicketStatus      
    ORDER BY StatusCount DESC;      
      
    -- 3️⃣ Doctor-wise Beneficiary Count      
    SELECT       
        DoctorName,      
        COUNT(Id) AS BeneficiaryCount,  
     SUM(CASE WHEN TicketStatus = 'Open' THEN 1 ELSE 0 END) AS OpenCases,  
    SUM(CASE WHEN TicketStatus = 'Close' THEN 1 ELSE 0 END) AS CloseCases,  
    SUM(CASE WHEN TicketStatus = 'New' THEN 1 ELSE 0 END) AS NewCases  
    FROM #BaseData      
    WHERE DoctorName IS NOT NULL      
    GROUP BY DoctorName      
    ORDER BY BeneficiaryCount DESC;      
      
   -- 4️⃣ Open Cases Ageing Analysis (0-7, 8-15, 16-30 Days)    
SELECT    
    AgeingCategory,    
    TotalCases    
FROM (    
    SELECT    
        CASE    
            WHEN AgeingDays <= 7  THEN '0-7 Days'    
            WHEN AgeingDays <= 15 THEN '8-15 Days'    
            WHEN AgeingDays <= 30 THEN '16-30 Days'    
            ELSE 'Above 30 Days'    
        END AS AgeingCategory,    
        COUNT(*) AS TotalCases,    
        CASE    
            WHEN AgeingDays <= 7  THEN 1    
            WHEN AgeingDays <= 15 THEN 2    
            WHEN AgeingDays <= 30 THEN 3    
            ELSE 4    
        END AS SortOrder    
    FROM #BaseData    
    WHERE StatusCategory IN('Open','New')    
    GROUP BY    
        CASE    
            WHEN AgeingDays <= 7  THEN '0-7 Days'    
            WHEN AgeingDays <= 15 THEN '8-15 Days'    
            WHEN AgeingDays <= 30 THEN '16-30 Days'    
            ELSE 'Above 30 Days'    
        END,    
        CASE    
            WHEN AgeingDays <= 7  THEN 1    
            WHEN AgeingDays <= 15 THEN 2    
            WHEN AgeingDays <= 30 THEN 3    
            ELSE 4    
        END    
) AS AgedData    
ORDER BY SortOrder;    
    
      
    -- 5️⃣ Summary Statistics      
    SELECT       
        TotalCases,      
        TotalDoctors,      
        TotalStates,      
        TotalHospitals,      
        ClosedCases,      
        OpenCases,     
  NewCases,    
        ClosureRate,      
        AverageEstimatedAmount,      
        TotalEstimatedAmount      
    FROM #SummaryData;      
      
    -- 6️⃣ State-wise Distribution      
    SELECT       
        ISNULL(StateName, 'Unknown') AS StateName,      
        COUNT(Id) AS CaseCount    ,  
       SUM(CASE WHEN TicketStatus = 'Open' THEN 1 ELSE 0 END) AS OpenCases,  
    SUM(CASE WHEN TicketStatus = 'Close' THEN 1 ELSE 0 END) AS CloseCases,  
    SUM(CASE WHEN TicketStatus = 'New' THEN 1 ELSE 0 END) AS NewCases  
    FROM #BaseData      
    GROUP BY ISNULL(StateName, 'Unknown')      
    ORDER BY CaseCount DESC;      
      
    -- 7️⃣ Hospital-wise Distribution      
    SELECT       
        ISNULL(HospitalName, 'Unknown') AS HospitalName,      
        COUNT(Id) AS CaseCount      
    FROM #BaseData      
    GROUP BY ISNULL(HospitalName, 'Unknown')      
    ORDER BY CaseCount DESC;      
      
    -- 8️⃣ Claim Type Distribution      
    SELECT       
        ISNULL(ClaimType, 'Unknown') AS ClaimType,      
        COUNT(Id) AS CaseCount      
    FROM #BaseData      
    GROUP BY ISNULL(ClaimType, 'Unknown')      
    ORDER BY CaseCount DESC;      
    
         
     -- 8️⃣ Oracle vs Non-Oracle Distribution    
     SELECT       
         OracleNonOracleType AS OracleandNonOracleChartType,    
         COUNT(Id) AS CaseCount    
     FROM #BaseData    
     GROUP BY OracleNonOracleType    
     ORDER BY CaseCount DESC;    
    
     -- 9️⃣ Business-wise Distribution    
      SELECT       
          ISNULL(Business, 'Unknown') AS Business,    
          COUNT(Id) AS CaseCount  ,  
         SUM(CASE WHEN TicketStatus = 'Open' THEN 1 ELSE 0 END) AS OpenCases,  
    SUM(CASE WHEN TicketStatus = 'Close' THEN 1 ELSE 0 END) AS CloseCases,  
    SUM(CASE WHEN TicketStatus = 'New' THEN 1 ELSE 0 END) AS NewCases  
      FROM #BaseData    
      GROUP BY ISNULL(Business, 'Unknown')    
      ORDER BY CaseCount DESC;    
          
      
      
    -------------------------------------------------------------      
    -- 🧹 Clean up      
    -------------------------------------------------------------      
    DROP TABLE #BaseData;      
    DROP TABLE #SummaryData;      
      
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]        
(        
    @rOrgId INT,        
    @rTemplate NVARCHAR(MAX),        
    @rMailSubject NVARCHAR(MAX),        
    @rIntimationDetailId BIGINT,        
    @rEventId INT        
)        
AS        
BEGIN        
    SET NOCOUNT ON;        
      
    SELECT        
        ID.OrgId AS OrgGroupId,        
        95 AS SourceTypeId,        
        EC.MobileNumber AS MobileNo,        
        EC.CompanyEmail AS EmailId,        
        ID.TicketNumber,        
        EM.FirstName,        
        EC.ExtensionNo,        
        ID.Relation,        
        EM1.FirstName,        
      
        -- 🔹 Message text with ALL replacements      
        REPLACE(      
            REPLACE(      
                REPLACE(      
                    REPLACE(      
                        REPLACE(      
                            REPLACE(      
                                REPLACE(      
                                    REPLACE(      
                                        @rTemplate,      
                                        '[DoctorName]',      
                                        LTRIM(RTRIM(      
                                            ISNULL(EM.FirstName, '') +      
                                            CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +      
                                            CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END      
                                        ))      
                                    ),      
                                    '[BeneficiaryName]', ISNULL(ID.BeneficiaryName, '')      
                                ),      
                                '[RecipientName]',      
                                LTRIM(RTRIM(      
                                    ISNULL(EM1.FirstName, '') +      
                                    CASE WHEN ISNULL(EM1.MiddleName, '') <> '' THEN ' ' + EM1.MiddleName ELSE '' END +      
                                    CASE WHEN ISNULL(EM1.LastName, '') <> '' THEN ' ' + EM1.LastName ELSE '' END      
                                ))      
                            ),      
                            '[Relationship]', ISNULL(ID.Relation, '')      
                        ),      
                        '[Extension]', ISNULL(EC.ExtensionNo, '')      
                    ),      
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')      
                ),      
                '[NewAssignedCount]',      
                CAST(      
                    (      
               SELECT COUNT(1)      
                FROM sHospitalization.tIntimationDetails ID2      
                WHERE ID2.AssignedDoctorId = EM.Id      
      
                    ) AS NVARCHAR(10)      
                )      
            ),      
              '[OpenFrom]',      
             CAST(      
             (      
                SELECT COUNT(1)          
                 FROM sHospitalization.tIntimationDetails ID2           
                 WHERE ID2.AssignedDoctorId = EM.Id          
                   AND ISNULL(ID2.IsObsolete, 0) = 0          
                  AND TicketStatus IN ('Open', 'New')         
                  AND ID2.CreatedDateTime <= DATEADD(HOUR, -48, GETDATE())          
             ) AS NVARCHAR(10)      
             )      
      
        ) AS MsgText,      
      
        @rMailSubject AS Subject        
      
    FROM sHospitalization.tIntimationDetails ID        
    LEFT JOIN sHrm.tEmployeeMaster EM        
        ON ID.AssignedDoctorId = EM.Id        
    LEFT JOIN sHrm.tEmployeeCommunications EC        
        ON EM.Id = EC.EmployeeId        
    LEFT JOIN sHrm.tEmployeeMaster EM1        
        ON ID.ParticipantSourceId = EM1.Id        
      
    WHERE ID.Id = @rIntimationDetailId      
      AND ISNULL(ID.AssignedDoctorId, 0) <> 0;        
      
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsGetList]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsGetList]            
(            
    @rFromDate NVARCHAR(50) = NULL,            
    @rToDate   NVARCHAR(50) = NULL,            
    @rOrgId    INT            
)            
AS            
BEGIN            
    SET NOCOUNT ON;            
            
    DECLARE @FromDate DATETIME = NULL,            
            @ToDate   DATETIME = NULL,
            @UseNewTable BIT = 0;            
    
    ---------------------------------------------------            
    -- Check configuration to determine which table to use
    ---------------------------------------------------            
    SELECT @UseNewTable = CASE 
        WHEN EXISTS (  
            SELECT 1  
            FROM [sConfig].[tConfigurationMaster]  
            WHERE ItemKey = 'ClaimIntimation.HospitalizationAssignDoctorMaster'  
            AND ItemValue = 'True'  
            AND IsObsolete = 0  
        )  
        THEN 1 ELSE 0  
    END;
    
    ---------------------------------------------------            
    -- Convert only if valid AND not blank            
    ---------------------------------------------------            
    IF (ISDATE(@rFromDate) = 1 AND LTRIM(RTRIM(@rFromDate)) <> '')            
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);            
            
    IF (ISDATE(@rToDate) = 1 AND LTRIM(RTRIM(@rToDate)) <> '')            
        SET @ToDate = CONVERT(DATETIME, @rToDate, 103);            
            
    ---------------------------------------------------            
    IF (@FromDate IS NULL)            
    BEGIN            
        SET @FromDate = '1900-01-01';  -- earliest            
        SET @ToDate = '2099-12-31';    -- latest            
    END            
    ELSE            
    BEGIN            
        -- If FromDate is valid but ToDate is blank, use today            
        IF (@ToDate IS NULL)            
            SET @ToDate = GETDATE();            
    END            
            
    ---------------------------------------------------            
    -- MAIN QUERY            
    ---------------------------------------------------            
    
    -- If using new table
    IF @UseNewTable = 1
    BEGIN
        SELECT            
            TD.Id,            
            TD.OrgId,            
            TD.EmpCode as EmployeeCode,            
            TD.BeneficiaryName,            
            TD.DateOfIntimation,            
            CONVERT(VARCHAR(10), TD.DateOfIntimation, 103) AS DateOfIntimation1,            
            TD.DateOfAdmission,            
            TD.DateOfDischarge,            
            TD.HospitalName,            
            TD.State,            
            TD.TicketStatus as Status,            
            TD.NetworkCity,            
            TD.TypeOfIntimation,            
            TD.StatusOfIntimation,            
            TD.ClaimType,            
            TD.IntimationNumber,            
            TD.Relation,            
            TD.Age,            
            TD.ProposerName,            
            TD.Mobile1,            
            TD.EstimatedAmount,            
            TD.AdmissionType,            
            TD.NetworkStatus,            
            TD.NatureOfIllness,            
            TD.TAT,            
            TD.TAT_Godi,            
            TD.TAT_Band_Godi,            
            TD.Remarks,            
            TD.CreatedDateTime,                     
            CONVERT(VARCHAR(10), TD.CreatedDateTime, 103) AS CreatedDate,            
            TD.AssignedDoctorId,            
            EM.Code AS DoctorCode,            
            TD.IsObsolete,            
            TD.TicketNumber,                           
            -- Direct from new table - if NULL, show 'Not Assigned'
           AD.AssignDesignationName AS Designation,
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignDoctor            
        FROM [sHospitalization].[tIntimationDetails] TD            
        Left JOIN [sHospitalization].[tClaimIntimationAssignedDoctor] AD             
            ON TD.AssignedDoctorId = AD.DoctorEmployeeId 
           AND AD.IsObsolete = 0            
        Left JOIN [sHrm].[tEmployeeMaster] EM            
            ON EM.Id = TD.AssignedDoctorId
            AND EM.IsObsolete = 0            
        WHERE                     
             TD.DateOfIntimation BETWEEN @FromDate AND @ToDate            
            AND (@rOrgId = 0 OR TD.OrgId = @rOrgId)            
        ORDER BY TD.DateOfIntimation DESC;
    END
    ELSE 
    BEGIN
        SELECT            
            TD.Id,            
            TD.OrgId,            
            TD.EmpCode as EmployeeCode,            
            TD.BeneficiaryName,            
            TD.DateOfIntimation,            
            CONVERT(VARCHAR(10), TD.DateOfIntimation, 103) AS DateOfIntimation1,            
            TD.DateOfAdmission,            
            TD.DateOfDischarge,            
            TD.HospitalName,            
            TD.State,            
            TD.TicketStatus as Status,            
            TD.NetworkCity,            
            TD.TypeOfIntimation,            
            TD.StatusOfIntimation,            
            TD.ClaimType,            
            TD.IntimationNumber,            
            TD.Relation,            
            TD.Age,            
            TD.ProposerName,            
            TD.Mobile1,            
            TD.EstimatedAmount,            
            TD.AdmissionType,            
            TD.NetworkStatus,            
            TD.NatureOfIllness,            
            TD.TAT,            
            TD.TAT_Godi,            
            TD.TAT_Band_Godi,            
            TD.Remarks,            
            TD.CreatedDateTime,                     
            CONVERT(VARCHAR(10), TD.CreatedDateTime, 103) AS CreatedDate,            
            TD.AssignedDoctorId,            
            EM.Code AS DoctorCode,            
            TD.IsObsolete,            
            TD.TicketNumber,                           
            CASE ISNULL(AD.DesignationId, 0)
                WHEN 1 THEN 'Business Doctor'            
                WHEN 2 THEN 'Central Doctor'            
                WHEN 3 THEN 'Site Doctor'            
                WHEN 4 THEN 'Zonal Doctor'
            END AS Designation,
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignDoctor            
        FROM [sHospitalization].[tIntimationDetails] TD            
        Left JOIN [sHospitalization].[tIntimationAssignedDoctor] AD             
            ON TD.AssignedDoctorId = AD.DoctorEmployeeId  
           AND AD.IsObsolete = 0            
        Left JOIN [sHrm].[tEmployeeMaster] EM            
            ON EM.Id = TD.AssignedDoctorId
            AND EM.IsObsolete = 0            
        WHERE            
           
             TD.DateOfIntimation BETWEEN @FromDate AND @ToDate            
            AND (@rOrgId = 0 OR TD.OrgId = @rOrgId)            
        ORDER BY TD.DateOfIntimation DESC;
    END
END
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsInsert]...';


GO

CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsInsert]       
    @rHospitalName NVARCHAR(255) = NULL,        
    @rPatientName NVARCHAR(255) = NULL,        
    @rEmpCode NVARCHAR(100) = NULL,        
    @rMobile1 NVARCHAR(20) = NULL,        
    @rOrgId INT = NULL,          
    @rRawEmployeeNo NVARCHAR(100) = NULL,        
    @rRawBeneficiaryName NVARCHAR(255) = NULL,        
    @rRawAge NVARCHAR(10) = NULL,        
    @rRawRelation NVARCHAR(100) = NULL,        
    @rRawNatureOfIllness NVARCHAR(500) = NULL,        
    @rRawProposerName NVARCHAR(255) = NULL,        
    @rRawContact1 NVARCHAR(20) = NULL,        
    @rRawHospitalName NVARCHAR(255) = NULL,        
    @rRawNetworkCity NVARCHAR(100) = NULL,        
    @rRawState NVARCHAR(100) = NULL,        
    @rRawTreatingDoctor NVARCHAR(255) = NULL,        
    @rRawLikelyDateOfAdmission NVARCHAR(200) = NULL,        
    @rRawDateOfDischarge NVARCHAR(200) = NULL,        
    @rRawStatusOfIntimation NVARCHAR(100) = NULL,        
    @rRawTypeOfIntimation NVARCHAR(100) = NULL,        
    @rRawFIRNo NVARCHAR(100) = NULL,        
    @rRawDateOfFileReceived NVARCHAR(200) = NULL,        
    @rRawClaimType NVARCHAR(200) = NULL,        
    @rRawIntimationNo NVARCHAR(100) = NULL,        
    @rRawDateOfIntimation NVARCHAR(200) = NULL,        
    @rRawTPACardNo NVARCHAR(100) = NULL,        
    @rRawGrade NVARCHAR(200) = NULL,        
    @rRawGroupCode NVARCHAR(200) = NULL,        
    @rRawModeOfStatus NVARCHAR(200) = NULL,        
    @rRawTAT NVARCHAR(200) = NULL,        
    @rRawAdmissionType NVARCHAR(200) = NULL,        
    @rRawEstimatedAmount NVARCHAR(200) = NULL,        
    @rRawNetworkStatus NVARCHAR(200) = NULL,        
    @rRawTAT_Godi NVARCHAR(200) = NULL,        
    @rRawTAT_Band_Godi NVARCHAR(200) = NULL,        
    @rCreatedUserId BIGINT = NULL,        
    @rIsObsolete BIT = 0,        
    @AssignedDoctorId BIGINT = NULL,        
    @IntimationAssignedDoctorId INT = NULL ,  
    @rflag BIT = 0   
            
AS        
BEGIN        
    SET nocount ON;        
 DECLARE @NewRecordId BIGINT ;        
  DECLARE @ParticipantSourceId BIGINT ;       
    BEGIN try        
        DECLARE @EmployeeId BIGINT = NULL,        
                @PreviousDoctorId BIGINT = NULL,        
                @TicketStatus NVARCHAR(50) = 'New',        
                @CurrentDateTime DATETIME = Getutcdate(),        
                @TicketNumber NVARCHAR(50) = NULL,        
                @AssignTypeId BIGINT = NULL,        
                @AssignSubTypeId BIGINT = NULL,        
                @DesignationId BIGINT = NULL,        
                @ParsedDateOfAdmission DATE,        
                @ParsedDateOfDischarge DATE,        
                @ParsedDateOfIntimation DATE,        
                @ParsedEstimatedAmount DECIMAL(18, 2),        
                @ParsedAge INT,        
                @lNextNumber BIGINT,        
                @FIRNo_num NUMERIC(18, 0) = NULL,        
                @TPACardNo_num NUMERIC(18, 0) = NULL,        
                @EstimatedAmount_num DECIMAL(18, 2) = NULL,        
                @TAT_Godi_int INT = NULL,        
                @ParticipantSourceTypeId BIGINT = NULL,       
				@AssignedDoctorDetails NVARCHAR(1000) = NULL;
            
        ---------------------------------------------------------------------        
        -- Generate new RowId        
        ---------------------------------------------------------------------        
        EXEC scommon.ptablerowidget @rOrgId = @rOrgId,        
                                    @rTableTitle = 'sHospitalization.tIntimationDetails',        
                                    @rIsCurrentNumber = 0,        
                                    @rSeed = 1,        
                                    @rIncrement = 1,        
                                    @outNextNumber = @lNextNumber output;        
        SET @NewRecordId = @lNextNumber;        
        ---------------------------------------------------------------------        
        -- Resolve EmployeeId (if present)        
        ---------------------------------------------------------------------        
        ---------------------------------------------------------------------        
        -- Resolve EmployeeId (if present)        
        ---------------------------------------------------------------------        
        IF ISNULL(LTRIM(RTRIM(@rRawEmployeeNo)), '') <> ''        
        BEGIN        
            SELECT @EmployeeId = Id        
            FROM [sHrm].[tEmployeeMaster]        
            WHERE Code = @rRawEmployeeNo        
     AND IsObsolete = 0;        
        
            IF @EmployeeId IS NOT NULL        
            BEGIN        
        
                SET @ParticipantSourceTypeId = 95;        
            END        
            ELSE        
            BEGIN        
        
                SET @ParticipantSourceTypeId = NULL;        
            END        
        END        
        ELSE        
        BEGIN        
        
            SET @ParticipantSourceTypeId = NULL;        
        END        
        
        ---------------------------------------------------------------------        
        -- Doctor assignment placeholder logic (currently manual or external)        
        ---------------------------------------------------------------------        
        -- ASSIGNDOCTORDONE:        
        ---------------------------------------------------------------------        
        -- Generate Ticket Number        
        ---------------------------------------------------------------------        
        -- SET @TicketNumber = 'TKT-' + Format(Getutcdate(), 'yyyyMMdd') + '-' + RIGHT('00000' + Cast(Abs(Checksum(Newid())) % 100000 AS NVARCHAR(5)), 5);        
        -- Generate sequential TicketNumber (e.g. TKT-20251105-00001)        
        ---------------------------------------------------------------------        
        -- Generate sequential TicketNumber like TKT-20251105-00001        
        ---------------------------------------------------------------------        
        DECLARE @NextNumber INT;        
        
        SELECT @NextNumber = ISNULL(MAX(CAST(RIGHT(TicketNumber, 5) AS INT)), 0) + 1        
        FROM [sHospitalization].[tIntimationDetails]        
        WHERE TicketNumber LIKE 'TKT-' + FORMAT(GETUTCDATE(), 'yyyyMMdd') + '%';        
        
        SET @TicketNumber        
            = 'TKT-' + FORMAT(GETUTCDATE(), 'yyyyMMdd') + '-' + RIGHT('00000' + CAST(@NextNumber AS NVARCHAR(5)), 5);        
        
        
        ---------------------------------------------------------------------        
        -- Parse / normalize fields        
        ---------------------------------------------------------------------        
        SET @ParsedDateOfAdmission = dbo.Fn_parsedatestring(@rRawLikelyDateOfAdmission);        
        SET @ParsedDateOfDischarge = dbo.Fn_parsedatestring(@rRawDateOfDischarge);        
        SET @ParsedDateOfIntimation = dbo.Fn_parsedatestring(@rRawDateOfIntimation);        
        -- Normalize estimated amount        
        IF Isnull(Ltrim(Rtrim(@rRawEstimatedAmount)), '') <> ''        
        BEGIN        
            SET @rRawEstimatedAmount = Replace(Replace(Ltrim(Rtrim(@rRawEstimatedAmount)), ',', ''), ' ', '');        
            SET @ParsedEstimatedAmount = try_cast(@rRawEstimatedAmount as decimal(18, 2));        
        END        
        ELSE        
            SET @ParsedEstimatedAmount = NULL;        
        SET @ParsedAge = try_cast(@rRawAge as int);        
        ---------------------------------------------------------------------        
        -- Validate numeric fields BEFORE INSERT        
        ---------------------------------------------------------------------        
        -- FIRNo        
        IF Isnull(Ltrim(Rtrim(@rRawFIRNo)), '') <> ''        
        BEGIN        
            SET @FIRNo_num = try_cast(Replace(Ltrim(Rtrim(@rRawFIRNo)), ' ', '') as numeric(18, 0));        
            IF @FIRNo_num IS NULL        
            RAISERROR('Invalid FIRNo: cannot convert [%s] to numeric', 16, 1, @rRawFIRNo);        
        END        
        ELSE        
            SET @FIRNo_num = NULL;        
        -- TPACardNo        
        IF Isnull(Ltrim(Rtrim(@rRawTPACardNo)), '') <> ''        
        BEGIN        
            SET @TPACardNo_num = try_cast(Replace(Ltrim(Rtrim(@rRawTPACardNo)), ' ', '') as numeric(18, 0));        
            IF @TPACardNo_num IS NULL        
                RAISERROR('Invalid TPACardNo: cannot convert [%s] to numeric', 16, 1, @rRawTPACardNo);        
        END        
        ELSE        
            SET @TPACardNo_num = NULL;        
        -- EstimatedAmount        
        IF Isnull(Ltrim(Rtrim(@rRawEstimatedAmount)), '') <> ''        
        BEGIN        
            IF @ParsedEstimatedAmount IS NULL        
                RAISERROR('Invalid EstimatedAmount: cannot convert [%s] to decimal', 16, 1, @rRawEstimatedAmount);        
            ELSE        
                SET @EstimatedAmount_num = @ParsedEstimatedAmount;        
        END        
        ELSE        
           SET @EstimatedAmount_num = NULL;        
        -- TAT_Godi        
        IF Isnull(Ltrim(Rtrim(@rRawTAT_Godi)), '') <> ''        
        BEGIN        
            SET @TAT_Godi_int = try_cast(Ltrim(Rtrim(@rRawTAT_Godi)) as int);        
            IF @TAT_Godi_int IS NULL        
                RAISERROR('Invalid TAT_Godi: cannot convert [%s] to int', 16, 1, @rRawTAT_Godi);        
        END        
        ELSE        
            SET @TAT_Godi_int = NULL;        
        
        
           ---------------------------------------------------------------------        
        -- Insert / Update State Master        
        ---------------------------------------------------------------------        
        IF ISNULL(LTRIM(RTRIM(@rRawState)), '') <> ''        
        BEGIN        
            DECLARE @lStateId BIGINT;        
        
            -- Check if state already exists        
            SELECT @lStateId = Id        
            FROM [sHospitalization].[tStateMaster]        
            WHERE StateName = @rRawState        
                  AND OrgId = @rOrgId        
                  AND IsObsolete = 0;        
        
            -- If not found, insert new        
            IF @lStateId IS NULL        
            BEGIN        
                EXEC scommon.ptablerowidget         
                    @rOrgId = @rOrgId,        
                    @rTableTitle = 'sHospitalization.tStateMaster',        
                    @rIsCurrentNumber = 0,        
                    @rSeed = 1,        
                    @rIncrement = 1,        
                    @outNextNumber = @lStateId OUTPUT;        
        
                INSERT INTO [sHospitalization].[tStateMaster]        
                (        
                    Id,        
                    OrgId,        
                    StateName,        
                    CreatedUserId,        
                    CreatedDateTime,        
                    UpdatedUserId,        
                    UpdatedDateTime,        
                    IsObsolete        
                )        
                VALUES        
                (        
                    @lStateId,        
                    @rOrgId,        
                    @rRawState,        
                    @rCreatedUserId,        
                    @CurrentDateTime,        
                    @rCreatedUserId,        
                    @CurrentDateTime,        
                    0        
                );        
            END        
        END        
        
        ---------------------------------------------------------------------        
        -- All validations passed — perform insert inside a transaction        
        ---------------------------------------------------------------------   
		IF @IntimationAssignedDoctorId IS NOT NULL
         BEGIN
         
         SELECT 
         @AssignedDoctorDetails =
         CAST(Id AS NVARCHAR) + ',' +
         CAST(OrgId AS NVARCHAR) + ',' +
         CAST(BusinessId AS NVARCHAR) + ',' +
         CAST(SubBusinessId AS NVARCHAR) + ',' +
         CAST(LocationId AS NVARCHAR) + ',' +
         CAST(SubLocationId AS NVARCHAR) + ',' +
         CAST(StateId AS NVARCHAR) + ',' +
         CAST(OrganizationId AS NVARCHAR) + ',' +
         CAST(DoctorEmployeeId AS NVARCHAR) + ',' +
         CAST(AssignDesignationId AS NVARCHAR) + ',' +
         CAST(AssignDoctorIndex AS NVARCHAR) + ',' +
         CAST(IsObsolete AS NVARCHAR) + ',' +
         CAST(CreatedUserId AS NVARCHAR) + ',' +
         CONVERT(NVARCHAR,CreatedDateTime,120) + ',' +
         ISNULL(CAST(UpdatedUserId AS NVARCHAR),'') + ',' +
         ISNULL(CONVERT(NVARCHAR,UpdatedDateTime,120),'') + ',' +
         ISNULL(AssignDesignationName,'')
         FROM sHospitalization.tClaimIntimationAssignedDoctor
         WHERE Id = @IntimationAssignedDoctorId
         
      END
IF @ParsedDateOfIntimation IS NOT NULL AND NOT EXISTS    
(    
    SELECT 1    
    FROM [sHospitalization].[tIntimationDetails]    
    WHERE EmpCode = @rRawEmployeeNo    
      AND BeneficiaryName = @rRawBeneficiaryName    
      AND DateOfIntimation = @ParsedDateOfIntimation    
)     
  BEGIN        
        BEGIN TRANSACTION;        
        
          
    INSERT INTO [sHospitalization].[tIntimationDetails]        
        (        
            id,        
            orgid,        
            participantsourceid,        
            participantsourcetypeid,        
            empcode,        
            beneficiaryname,        
            dateofintimation,        
           dateofadmission,        
            dateofdischarge,        
            claimtype,        
            intimationnumber,        
            natureofillness,        
            status,        
            hospitalname,        
            networkcity,        
            state,        
            age,        
            mobile1,        
            assigneddoctorid,        
            IntimationAssignedDoctorId,        
            ticketnumber,        
            ticketstatus,        
            ticketopendate,        
            relation,        
            proposername,        
            statusofintimation,        
            typeofintimation,        
            firno,        
            tpacardno,        
            grade,        
            groupcode,        
            modeofstatus,        
            tat,        
            admissiontype,        
            estimatedamount,        
            networkstatus,        
            tat_godi,        
            tat_band_godi,        
            isobsolete,        
            createddatetime,        
            createduserid,        
            updateddatetime,        
            updateduserid,  
            TreatingDoctor,  
             Flag ,
			 AssignedDoctorDetails
			 
        )        
        VALUES        
        (@NewRecordId,        
         Isnull(@rOrgId, 0),        
         @EmployeeId,        
         @ParticipantSourceTypeId,        
         @rRawEmployeeNo,        
         @rRawBeneficiaryName,        
         @ParsedDateOfIntimation,        
         @ParsedDateOfAdmission,        
         @ParsedDateOfDischarge,        
         @rRawClaimType,        
         @rRawIntimationNo,        
         @rRawNatureOfIllness,        
         @rRawStatusOfIntimation,        
         @rRawHospitalName,        
         @rRawNetworkCity,        
         @rRawState,        
         @ParsedAge,        
         @rRawContact1,        
         @AssignedDoctorId,        
         @IntimationAssignedDoctorId,        
         @TicketNumber,        
         @TicketStatus,        
         @CurrentDateTime,        
         @rRawRelation,        
         @rRawProposerName,        
         @rRawStatusOfIntimation,        
         @rRawTypeOfIntimation,        
         @FIRNo_num,        
         @TPACardNo_num,        
         @rRawGrade,        
         @rRawGroupCode,        
         @rRawModeOfStatus,        
         @rRawTAT,        
         @rRawAdmissionType,        
         @EstimatedAmount_num,        
         @rRawNetworkStatus,        
         @TAT_Godi_int,        
         @rRawTAT_Band_Godi,        
         @rIsObsolete,        
         @CurrentDateTime,        
         @rCreatedUserId,        
         @CurrentDateTime,        
         @rCreatedUserId ,  
         NULLIF(LTRIM(RTRIM(@rRawTreatingDoctor)), ''),  
         @rflag      ,
		 @AssignedDoctorDetails
        );        
          
        ---------------------------------------------------------------------        
        -- Insert doctor assignment log        
        ---------------------------------------------------------------------        
                
  IF @AssignedDoctorId IS NOT NULL        
        BEGIN        
            DECLARE @lAssignLogId BIGINT;        
            EXEC scommon.ptablerowidget @rOrgId = @rOrgId,        
                                        @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',        
                                        @rIsCurrentNumber = 0,        
                                        @rSeed = 1,        
                                        @rIncrement = 1,        
                 @outNextNumber = @lAssignLogId output;        
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]        
            (        
                id,        
                orgid,        
                hospitalizationintimationdetailid,        
                previousdoctoremployeeid,        
                newdoctoremployeeid,        
                assigneddate,        
                ticketnumber,        
                createduserid,        
                createddatetime,        
                updateduserid,        
                updateddatetime,        
    Status        
            )        
            VALUES        
            (@lAssignLogId,        
             Isnull(@rOrgId, 0),        
             @NewRecordId,        
             @PreviousDoctorId,        
             @AssignedDoctorId,        
             @CurrentDateTime,        
             @TicketNumber,        
             @rCreatedUserId,        
             @CurrentDateTime,        
             @rCreatedUserId,        
             @CurrentDateTime,        
    'New'        
            );        
        
        END        
        COMMIT TRANSACTION;        
  END        
  ---------------------------------------------------------------------        
-- Insert default remark entry with Status = 'New'        
---------------------------------------------------------------------        
--IF @AssignedDoctorId IS NOT NULL        
--BEGIN        
--    DECLARE @lRemarkId BIGINT;        
        
--    EXEC scommon.ptablerowidget         
--        @rOrgId = @rOrgId,        
--        @rTableTitle = 'sHospitalization.tIntimationRemark',        
--        @rIsCurrentNumber = 0,        
--        @rSeed = 1,        
--        @rIncrement = 1,        
--        @outNextNumber = @lRemarkId OUTPUT;        
        
--    INSERT INTO [sHospitalization].[tIntimationRemark]        
--    (        
--        Id,        
--        OrgId,        
--        HospitalizationIntimationDetailId,        
--        DoctorEmployeeId,        
--        Remark,        
--        CreatedUserId,        
--        CreatedDateTime,        
--        UpdatedUserId,        
--        UpdatedDateTime,        
--        Status        
--    )        
--    VALUES        
--    (        
--        @lRemarkId,        
--        @rOrgId,        
--        @NewRecordId,        
--        @AssignedDoctorId,        
--        NULL,                     -- Remark initially empty        
--        @rCreatedUserId,        
--        @CurrentDateTime,        
--        @rCreatedUserId,        
--        @CurrentDateTime,        
--        'New'                     -- Default Status        
--    );        
--END        
        
        ---------------------------------------------------------------------        
        -- Return newly created record id        
        ---------------------------------------------------------------------        
        SELECT @NewRecordId AS newrecordid ,@EmployeeId as ParticipantSourceId ,@IntimationAssignedDoctorId as IntimationAssignedDoctorId ;        
        
        RETURN;        
    END try        
    BEGIN catch        
        -- Ensure rollback        
        IF @@TRANCOUNT > 0        
            ROLLBACK TRANSACTION;        
        DECLARE @ErrorMessage NVARCHAR(4000) = Error_message();        
        DECLARE @lErrorId BIGINT;        
        EXEC scommon.ptablerowidget @rOrgId = @rOrgId,        
                                    @rTableTitle = 'sHospitalization.tErrorLog',        
                                    @rIsCurrentNumber = 0,        
                                    @rSeed = 1,        
                                    @rIncrement = 1,        
                                    @outNextNumber = @lErrorId output;        
        INSERT INTO [sHospitalization].[tErrorLog]        
        (        
            id,        
            errormessage,        
            storedprocedure,        
            errordatetime,        
            userid,        
   orgid        
        )        
        VALUES        
        (@lErrorId, @ErrorMessage, 'sHospitalization.pIntimationDetailsInsert', Getutcdate(), @rCreatedUserId, @rOrgId);        
        
        SET @NewRecordId = -1;        
        RAISERROR(@ErrorMessage, 16, 1);        
        RETURN;        
    END catch        
END;
GO
PRINT N'Altering Procedure [sOrderEntry].[pSaveTestsAccordingStaticTestNew]...';


GO

CREATE OR ALTER PROCEDURE [sOrderEntry].[pSaveTestsAccordingStaticTestNew]
@rtid varchar(max),
@rOrgId int
as
begin
	delete from sOrderEntry.tTestMaster where OrgId = @rOrgId
	delete from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId
	delete from sOrderEntry.tTestDetail where OrgId = @rOrgId
	delete from sOrderEntry.tTestParameterDetail where OrgId = @rOrgId
	delete from sExamination.tTestListTypeSetup where OrgId = @rOrgId
	
	declare @tblTest table(tid int identity(1,1),t_StaticTestId int,t_TestId int)
	insert into @tblTest
	select Item,sCommon.fGetIntIdForOrg(Item,@rOrgId) from dbo.fSplitStr(@rtid,',') where Item <> ''
	
	declare @lFromNumber int	
	select @lFromNumber = MAX(Id) from sOrderEntry.tTestMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sOrderEntry.tTestMaster AS Target USING 
	(
		SELECT t_StaticTestId,t_TestId,SP.Code,SP.Title,SP.ServiceSubGroupId,SP.IsObsolete,SP.CreatedUserId,SP.CreatedDateTime,
		SP.UpdatedUserId,SP.UpdatedDateTime,SP.OrderIndex,ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sOrderEntry.tTestMaster t
		) as maxid
		
		FROM @tblTest TT INNER JOIN sOrderEntry.tStaticTestMaster SP
		ON TT.t_StaticTestId = SP.Id LEFT JOIN sOrderEntry.tTestMaster T ON TT.t_TestId = T.Id AND T.OrgId = @rOrgId
	) AS Source ON Target.Id = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Code,Title,ServiceSubGroupId,IsObsolete,CreatedUserId,CreatedDateTime,
			UpdatedUserId,UpdatedDateTime,OrgId,StaticTestId,OrderIndex
		)
		VALUES
		(
			t_TestId,Code,Title,sCommon.fGetIntIdForOrg(ServiceSubGroupId,@rOrgId),IsObsolete,
			CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,@rOrgId,t_StaticTestId,OrderIndex
		);
		
	select @lFromNumber = MAX(Id) from sOrderEntry.tServiceMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sOrderEntry.tServiceMaster AS Target USING 
	(
		SELECT t_StaticTestId,t_TestId,SP.Code,SP.Title,SP.ServiceSubGroupId,SP.IsObsolete,SP.CreatedUserId,SP.CreatedDateTime,
		SP.UpdatedUserId,SP.UpdatedDateTime,SP.OrderIndex,ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sOrderEntry.tServiceMaster t
		) as maxid
		
		FROM @tblTest TT INNER JOIN sOrderEntry.tStaticTestMaster SP
		ON TT.t_StaticTestId = SP.Id LEFT JOIN sOrderEntry.tServiceMaster T ON TT.t_TestId = T.Id AND T.OrgId = @rOrgId
	) AS Source ON Target.Id = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Code,Title,ServiceSubGroupId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgId
		)
		VALUES
		(
			t_TestId,Code,Title,ServiceSubGroupId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,@rOrgId
		);
	
	select @lFromNumber = MAX(Id) from sExamination.tAreaMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sExamination.tAreaMaster AS Target USING 
	(
		SELECT t_StaticTestId,t_TestId,SP.Code,SP.Title,SP.ServiceSubGroupId,SP.IsObsolete,SP.CreatedUserId,SP.CreatedDateTime,
		SP.UpdatedUserId,SP.UpdatedDateTime,SP.OrderIndex,ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sExamination.tAreaMaster t
		) as maxid
		
		FROM @tblTest TT INNER JOIN sOrderEntry.tStaticTestMaster SP
		ON TT.t_StaticTestId = SP.Id LEFT JOIN sExamination.tAreaMaster T ON TT.t_TestId = T.Id AND AreaTypeId = 1 AND T.OrgId = @rOrgId
	) AS Source ON Target.Id = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Title,Remark,AreaTypeId,AreaGroupId,IsObsolete,PagePath,OrderIndex,ImagePath,OrgId,StaticAreaId
		)
		VALUES
		(
			t_TestId,Title,Title,1,ServiceSubGroupId,IsObsolete,
			'~/Pages/Examination/ServiceResult.aspx?ServiceAreaId=' + convert(varchar,t_TestId),
			OrderIndex,'~/Images/Icon 16x16/icon_outpatient.gif',@rOrgId,t_StaticTestId
		);
	
	select @lFromNumber = max(Id) from sExamination.tAreaOrganizationMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sExamination.tAreaOrganizationMaster AS Target USING 
	(
		SELECT tid,t_StaticTestId,t_TestId,SG.Title,SG.IsObsolete,SG.CreatedUserId,SG.CreatedDateTime,
		SG.UpdatedUserId,SG.UpdatedDateTime,ROW_NUMBER()OVER(ORDER BY SG.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sExamination.tAreaOrganizationMaster t
		) as maxid
		
		FROM @tblTest TT inner join sOrderEntry.tStaticTestMaster SG on TT.t_StaticTestId = SG.Id
		LEFT JOIN sExamination.tAreaOrganizationMaster T ON TT.t_TestId = T.AreaId AND T.OrgId = @rOrgId
		LEFT JOIN sExamination.tAreaMaster AM on T.AreaId = AM.Id AND TT.t_TestId = AM.Id AND AM.AreaTypeId = 1 AND AM.OrgId = @rOrgId
	) AS Source ON Target.AreaId = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,OrgId,AreaId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
		VALUES
		(
			@lFromNumber + tid,@rOrgId,t_TestId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		);
		
	declare @tblParameters table(tid int identity(1,1),t_ParamId int,t_StaticParamId int,t_TestId int,t_StaticTestId int,t_DetailId int)
	insert into @tblParameters
	select sCommon.fGetIntIdForOrg(StaticTestParameterId,@rOrgId),StaticTestParameterId,
	sCommon.fGetIntIdForOrg(StaticTestId,@rOrgId),StaticTestId,STD.Id from sOrderEntry.tStaticTestDetail STD 
	inner join @tblTest T on T.t_StaticTestId = STD.StaticTestId
	
	select @lFromNumber = MAX(Id) from sOrderEntry.tTestParameterMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sOrderEntry.tTestParameterMaster AS Target USING 
	(
		SELECT t_ParamId,t_StaticParamId,SP.Code,SP.Title,SP.Remark,SP.SampleId,SP.ClinicalUOM,
		SP.StaticParameterValueTypeId,StaticListValueTypeId,SP.NumericFormat,SP.ServiceSubGroupId,
		SP.IsObsolete,SP.CreatedUserId,SP.CreatedDateTime,SP.UpdatedUserId,SP.UpdatedDateTime,SP.OrderIndex,SP.LowerLimitText,SP.UpperLimitText,
		SP.NormalRange,ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sOrderEntry.tTestParameterMaster t
		) as maxid
		
		FROM @tblParameters TT INNER JOIN sOrderEntry.tStaticTestParameterMaster SP
		ON TT.t_StaticParamId = SP.Id LEFT JOIN sOrderEntry.tTestParameterMaster T ON TT.t_ParamId = T.Id ANd T.OrgId = @rOrgId
	) AS Source ON Target.Id = Source.t_ParamId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Code,Title,Remark,SampleId,ClinicalUOM,ParameterValueTypeId,ListValueTypeId,NumericFormat,ServiceSubGroupId,
			IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgId,StaticTestParameterId,NormalRange,OrderIndex,LowerLimitText,UpperLimitText
		)
		VALUES
		(
			t_ParamId,Code,Title,Remark,SampleId,ClinicalUOM,StaticParameterValueTypeId,sCommon.fGetIntIdForOrg(StaticListValueTypeId,@rOrgId),
			NumericFormat,sCommon.fGetIntIdForOrg(ServiceSubGroupId,@rOrgId),IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,
			UpdatedDateTime,@rOrgId,t_StaticParamId,NormalRange,OrderIndex,LowerLimitText,UpperLimitText
		);
	
	select @lFromNumber = MAX(Id) from sOrderEntry.tTestDetail
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sOrderEntry.tTestDetail AS Target USING 
	(
		SELECT t_ParamId,t_StaticParamId,t_TestId,t_StaticTestId,SP.IsObsolete,t_DetailId,ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sOrderEntry.tTestDetail t
		) as maxid
		
		FROM @tblParameters TT INNER JOIN sOrderEntry.tStaticTestDetail SP
		ON TT.t_StaticParamId = SP.StaticTestParameterId and TT.t_StaticTestId = SP.StaticTestId
		LEFT JOIN sOrderEntry.tTestDetail T ON TT.t_ParamId = T.TestParameterId and TT.t_TestId = T.TestId AND T.OrgId = @rOrgId
	) AS Source ON Target.Id = Source.t_ParamId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,TestId,TestParameterId,IsObsolete,OrgId
		)
		VALUES
		(
			scommon.fgetIntIdForOrg(t_DetailId,@rOrgId),t_TestId,t_ParamId,IsObsolete,@rOrgId
		);
			
	declare @tbltmpParameterDetail table(tid int identity(1,1),t_ParamId int,t_StaticParamId int,t_StaticId int,t_Id int)
	insert into @tbltmpParameterDetail
	select t_ParamId,t_StaticParamId,Id,sCommon.fGetIntIdForOrg(Id,@rOrgId)
	from sOrderEntry.tStaticTestParameterDetail PD inner join @tblParameters TP on TP.t_StaticParamId = PD.StaticTestParameterId
	
	select @lFromNumber = MAX(Id) from sOrderEntry.tTestParameterDetail
	select @lFromNumber = isnull(@lFromNumber,0)
	
	insert into sOrderEntry.tTestParameterDetail
	(			
		Id,TestParameterId,GenderId,AgeFrom,AgeTo,Minimum,Maximum,Remark,IsObsolete,LessDiagnosisRemark,
		MoreDiagnosisRemark,LessRecommendationRemark,MoreRecommendationRemark,IsNormal,Diagnosis,OrgId,DisplayRange,
		Recommendation
	)
	select sCommon.fGetIntIdForOrg(Id,@rOrgId),t_ParamId,SP.GenderId,SP.AgeFrom,SP.AgeTo,SP.Minimum,SP.Maximum,SP.Remark,SP.IsObsolete,
	SP.LessDiagnosisRemark,SP.MoreDiagnosisRemark,SP.LessRecommendationRemark,SP.MoreRecommendationRemark,SP.IsNormal,SP.Diagnosis,@rOrgId,
	SP.DisplayRange,Recommendation from sOrderEntry.tStaticTestParameterDetail SP inner join @tblParameters TP on TP.t_StaticParamId = SP.StaticTestParameterId
	
	select @lFromNumber = MAX(Id) from sExamination.tTestListTypeSetup
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sExamination.tTestListTypeSetup AS Target USING 
	(
		SELECT t_ParamId,t_StaticParamId,StaticListValueId,SP.IsNormal,SP.DiagnosisRemark,SP.RecommendationRemark,
		ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sExamination.tTestListTypeSetup t
		) as maxid
		
		FROM @tblParameters TT INNER JOIN sExamination.tStaticTestListTypeSetup SP
		ON TT.t_StaticParamId = SP.StaticTestParameterId LEFT JOIN sExamination.tTestListTypeSetup T
		ON TT.t_ParamId = T.Id AND T.OrgId = @rOrgId
	) AS Source ON Target.Id = Source.t_ParamId
	WHEN NOT MATCHED THEN
		INSERT
		(			
			Id,TestParameterId,ListValueId,IsNormal,DiagnosisRemark,RecommendationRemark,OrgId
		)
		VALUES
		(
			@lFromNumber + rno,t_ParamId,sCommon.fGetIntIdForOrg(StaticListValueId,@rOrgId),IsNormal,
			DiagnosisRemark,RecommendationRemark,@rOrgId
		);

	select 1
end
GO
PRINT N'Altering Procedure [sOrderEntry].[pTestParameterDetailAdd]...';


GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterDetailAdd]
	@rOrgId int,
	@rTestParameterId [int],
	@rGenderId [int],
	@rAgeFrom [int],
	@rAgeTo [int],
	@rMinimum Decimal(12,4),
	@rMaximum Decimal(12,4),
	@rRemark [nvarchar](1000),
	@rDiagnosisRemark nvarchar(1000) = NULL,
	@rRecommendationRemark nvarchar(1000) = NULL,
	@rIsNormal bit = NULL,
	@rDisplayRange nvarchar(200),
	@rOrderIndex int = 0,
	@rIsBorderLine bit = NULL
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	if not exists (select * from sOrderEntry.tTestParameterDetail where [TestParameterId] = @rTestParameterId and AgeFrom = @rAgeFrom and GenderId = @rGenderId
	and AgeTo = @rAgeTo and Minimum = @rMinimum and Maximum = @rMaximum and (OrgId = @rOrgId or OrgId is null))
	begin
		DECLARE @lNextNumber BIGINT	
		EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tTestParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sOrderEntry.tTestParameterDetail
		(
			[Id],[TestParameterId],[GenderId],[AgeFrom],[AgeTo],[Minimum],[Maximum],
			[Remark],IsObsolete,IsNormal,Diagnosis,Recommendation,DisplayRange,OrgId,OrderIndex,IsBorderLine
		)
		VALUES
		(
			@lNextNumber,@rTestParameterId,@rGenderId,@rAgeFrom,@rAgeTo,@rMinimum,
			@rMaximum,@rRemark,0,@rIsNormal,@rDiagnosisRemark,@rRecommendationRemark,@rDisplayRange,@rOrgId,@rOrderIndex,@rIsBorderLine
		)
	end
	BEGIN
		SELECT 1 AS Result
	END
END
GO
PRINT N'Altering Procedure [sExamination].[pBindDataEntryTemplateAreas]...';


GO
CREATE OR ALTER PROCEDURE [sExamination].[pBindDataEntryTemplateAreas]  
@rId bigint = 0,  
@rOrgId int,  
@rFlag int  
as  
begin  
 declare @lResult varchar(max)=''  
 if @rFlag = 1  --vital
 begin  
  select @lResult = @lResult + '<tr>  
  <td><input class="csscheckbox" type="checkbox" ' + case when DETS.Id is not null then 'checked="checked"' else '' end + ' attrid="' + convert(varchar,TPM.Id) + '" /></td>  
  <td>' + TPM.Title + '</td><td>' + TM.Title + '</td></tr>'  
  from sExamination.tGeneralTemplateMaster TM    
  inner join sExamination.tGeneralTemplateParameter TPM on TM.Id = TPM.GeneralTemplateId  
  left join sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = TPM.Id  
  and DETS.DataEntryTemplateId = @rId and DETS.SourceTemplateId = 119  
  where TM.OrgId = @rOrgId and TM.IsObsolete = 0 and TPM.IsObsolete = 0 and TM.GeneralTemplateGroupId = 4  
  order by TPM.OrderIndex  
 end  
 if @rFlag = 2  --test
 begin  
  select @lResult = @lResult + '<tr>  
  <td><input class="csscheckbox" type="checkbox" ' + case when DETS.Id is not null then 'checked="checked"' else '' end + ' attrid="' + convert(varchar,TPM.Id) + '" /></td>  
  <td>' + TPM.Title + '</td><td>' + TM.Title + '</td></tr>'  
  from sOrderEntry.tTestMaster TM  
  inner join sOrderEntry.tTestDetail TD on TM.Id = TD.TestId  
  inner join sOrderEntry.tTestParameterMaster TPM on TD.TestParameterId = TPM.Id  
  left join sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = TPM.Id  
  and DETS.DataEntryTemplateId = @rId and DETS.SourceTemplateId = 118 -- sCommon.tSourceTypeMaster  
  where TM.OrgId = @rOrgId and TM.IsObsolete = 0 and TPM.IsObsolete = 0  
  order by TPM.OrderIndex  
 end  
 else if @rFlag = 3  ---habits
 begin  
  select @lResult = @lResult + '<tr>  
  <td><input class="csscheckbox" type="checkbox" ' + case when DETS.Id is not null then 'checked="checked"' else '' end + ' attrid="' + convert(varchar,TM.Id) + '" /></td>  
  <td>' + TM.Title + '</td></tr>'  
  from sExamination.tHabitTypeMaster TM  
  left join sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = TM.Id  
  and DETS.DataEntryTemplateId = @rId and DETS.SourceTemplateId = 10160  
  where TM.OrgId = @rOrgId  
  order by TM.Title  
 end  
 else if @rFlag = 4 --disease 
 begin  
  select @lResult = @lResult + '<tr>  
  <td><input class="csscheckbox" type="checkbox" ' + case when DETS.Id is not null then 'checked="checked"' else '' end + ' attrid="' + convert(varchar,TM.Id) + '" /></td>  
  <td>' + TM.Title + '</td></tr>'  
  from sExamination.tDiseaseMaster TM  
  left join sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = TM.Id  
  and DETS.DataEntryTemplateId = @rId and DETS.SourceTemplateId = 10161  
  where TM.OrgId = @rOrgId  
  order by TM.Title  
 end  
 if @rFlag = 5  --Personal
 begin  
  select @lResult = @lResult + '<tr>  
  <td><input class="csscheckbox" type="checkbox" ' + case when DETS.Id is not null then 'checked="checked"' else '' end + ' attrid="' + convert(varchar,TPM.Id) + '" /></td>  
  <td>' + TPM.Title + '</td><td>' + TM.Title + '</td></tr>'  
  from sExamination.tGeneralTemplateMaster TM    
  inner join sExamination.tGeneralTemplateParameter TPM on TM.Id = TPM.GeneralTemplateId  
  left join sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = TPM.Id  
  and DETS.DataEntryTemplateId = @rId and DETS.SourceTemplateId = 119  
  where TM.OrgId = @rOrgId and TM.IsObsolete = 0 and TPM.IsObsolete = 0 and TM.GeneralTemplateGroupId = 1  
  order by TPM.OrderIndex
 end  
  
 select @lResult as res  
end
GO
PRINT N'Altering Procedure [sOrderEntry].[pTestParameterAdd]...';


GO
 

-- exec [sOrderEntry].[pTestParameterAdd]
-- drop proc [sOrderEntry].[pTestParameterAdd]
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterAdd]
@rCode [nvarchar](100),
@rTitle [nvarchar](100),
@rRemark [nvarchar](1000),
@rSampleId [int],
@rClinicalUOM nvarchar(50),
@rParameterValueTypeId [int],
@rListValueTypeId [int],
@rNumericFormat [nvarchar](20),
@rServiceSubGroupId [int],	
@rIsObsolete [bit],
@rCreatedUserId [bigint],
@rOrgId [int],
@rId [int],
@rNormalRange nvarchar(200),
@rDefaultValue varchar(30)='',
@rOrderIndex smallint,
@rLowerLimitText nvarchar(200),
@rUpperLimitText nvarchar(200)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lNextNumber BIGINT
	DECLARE @Id BIGINT
	DECLARE @TestParameterId BIGINT

	IF(@rId=0)
				BEGIN
					IF EXISTS(select Id from sOrderEntry.tTestParameterMaster where Code=@rCode AND OrgId=@rOrgId)
						BEGIN
							select -102 as Result
							RETURN
						END 

					IF EXISTS(select Id from  sOrderEntry.tTestParameterMaster where Title=@rTitle AND OrgId=@rOrgId)
						BEGIN
							SELECT -103 [Status]
							RETURN
						END 
                    IF EXISTS(select Id from sExamination.tGeneralTemplateParameter where Title=@rTitle AND OrgId=@rOrgId)
						BEGIN
							select -104 as Result
							RETURN
						END 
				END	
		ELSE
			BEGIN
				IF EXISTS(select Id from sOrderEntry.tTestParameterMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
						BEGIN
							select -102 as Result
							RETURN
						END 

				IF EXISTS(select Id from sOrderEntry.tTestParameterMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
					BEGIN
						SELECT -103 as Result
						RETURN
					END 
                IF EXISTS(select Id from sExamination.tGeneralTemplateParameter where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
					BEGIN
						select -104 as Result
						RETURN
					END 
			END

	IF(@rSampleId < 0)
		SET @rSampleId = 0

	IF @rId = 0
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tTestParameterMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sOrderEntry.tTestParameterMaster
		(
			[Id],[Code],[Title],[Remark],[SampleId],[ClinicalUOM],[ParameterValueTypeId],[ListValueTypeId],
			[NumericFormat],[ServiceSubGroupId],[IsObsolete],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],
			[UpdatedDateTime],[NormalRange],[DefaultValue],[OrderIndex],[OrgId],LowerLimitText,UpperLimitText
		)
		VALUES
		(
			@lNextNumber,@rCode,@rTitle,@rRemark,@rSampleId,@rClinicalUOM,@rParameterValueTypeId,@rListValueTypeId,
			@rNumericFormat,@rServiceSubGroupId,@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,
			sCommon.fGetDate(),@rNormalRange,@rDefaultValue,@rOrderIndex,@rOrgId,@rLowerLimitText,@rUpperLimitText
		)
		
		Declare @rMaxid int = (select isnull(max(Id),0) + 1 from  [sHrm].[tExaminationCustomColumns])
		INSERT INTO [sHrm].[tExaminationCustomColumns](Id,[ColumnName],[IsObsolete],DataType,ColumnType)
		VALUES(@rMaxid,@rTitle,0,'varchar(300)',4)

		Declare @rMaxidOPD int = (select isnull(max(Id),0) + 1 from  [sExamination].[tOPDCustomColumns])
		INSERT INTO [sExamination].[tOPDCustomColumns](Id,[ColumnName],[IsObsolete],DataType,ColumnType)
		VALUES(@rMaxidOPD,@rTitle,0,'varchar(300)',3)
	END
	ELSE
	BEGIN
		DECLARE @lId int
	    Declare @OldTitle varchar(300) = (select Title from sOrderEntry.tTestParameterMaster where Id = @rId)
		UPDATE sOrderEntry.tTestParameterMaster SET [Code]=@rCode,[Title]=@rTitle,[Remark]=@rRemark,
		--[SampleId]	=	@rSampleId,
		[ClinicalUOM]	=	@rClinicalUOM,
		--[ParameterValueTypeId]	=	@rParameterValueTypeId,
		--[ListValueTypeId]	=	@rListValueTypeId,
		[NumericFormat]=@rNumericFormat,[ServiceSubGroupId]=@rServiceSubGroupId,
		[IsObsolete]=@rIsObsolete,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate(),NormalRange=@rNormalRange,
		DefaultValue=@rDefaultValue,[OrderIndex]=@rOrderIndex,LowerLimitText = @rLowerLimitText,UpperLimitText = @rUpperLimitText
		WHERE Id = @rId

		Select @lId = Id from [sHrm].[tExaminationCustomColumns] where ColumnName = @OldTitle and ColumnType = 4

		If Not Exists(select Id from [sHrm].[tExaminationCustomColumns] where ColumnName = @rTitle and ColumnType = 4)
		BEGIN
						
			Update [sHrm].[tExaminationCustomColumns] set ColumnName = @rTitle where Id = @lId			
		END
		IF NOT Exists(select Id from [sHrm].[tExaminationCustomColumns] where ColumnName = @rTitle and IsObsolete = @rIsObsolete and ColumnType = 4)
		BEGIN
						
			Update [sHrm].[tExaminationCustomColumns] set IsObsolete = @rIsObsolete where Id = @lId			
		END

		DECLARE @OPDId int
		Select @OPDId = Id from [sExamination].[tOPDCustomColumns] where ColumnName = @OldTitle and ColumnType = 3

		If Not Exists(select Id from [sExamination].[tOPDCustomColumns] where ColumnName = @rTitle and ColumnType = 3)
		BEGIN
						
			Update [sExamination].[tOPDCustomColumns] set ColumnName = @rTitle where Id = @OPDId			
		END
		IF NOT Exists(select Id from [sExamination].[tOPDCustomColumns] where ColumnName = @rTitle and IsObsolete = @rIsObsolete and ColumnType = 3)
		BEGIN
						
			Update [sExamination].[tOPDCustomColumns] set IsObsolete = @rIsObsolete where Id = @OPDId			
		END
	END	 
	
	--BEGIN
	--	SET @Id=(SELECT ISNULL(Id,0) as Id FROM sOrderEntry.tTestParameterMaster WHERE Title=@rTitle AND OrgId = @rOrgId)
		
	--	IF @Id != 0 
	--	BEGIN
	--		SET @TestParameterId=@Id
	--	END
	--	ELSE
	--	BEGIN
	--		SET @TestParameterId=@lNextNumber
	--	END
	--	BEGIN
	--		DELETE FROM sOrderEntry.tTestParameterDetail WHERE TestParameterId=@TestParameterId
	--	END
		IF @rId != 0
		BEGIN
			SELECT @rId AS Result
		END
		ELSE
		BEGIN
			SELECT @lNextNumber AS Result
		END
		--SELECT @rId AS Result
	
	--END
END
GO
PRINT N'Altering Procedure [sWellness].[pGetProgramParameters]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramParameters] 	
(
	@rOrgId INT,
	@rProgramId BIGINT
)
AS
BEGIN
	
	SET NOCOUNT ON;
	
    SELECT 
		pp.AutoID, 
		pp.OrgId,
		pp.ProgramId, 
		pp.ParameterTypeId,
		'General' AS ParameterType,
		pp.ParameterSourceTypeId,
		pp.ParameterSourceId, 
		GTP.Title AS ParameterName,
		ISNULL(gtp.StaticGeneralTemplateParameterId,0) AS StaticParameterSourceId, 
		pp.OrderIndex		
	FROM 
		[sWellness].[tProgramParameter] PP
	INNER JOIN 
		[sExamination].[tGeneralTemplateParameter] GTP 
	ON 
		pp.ParameterSourceId = gtp.Id
	WHERE 
		pp.ParameterTypeId = 2 
	AND 
		pp.ProgramId = @rProgramId 
	AND 
		pp.OrgId = @rOrgId

	UNION

	SELECT 
		pp.AutoID, 
		pp.OrgId, 
		pp.ProgramId, 
		pp.ParameterTypeId,
		'Test' as ParameterType,
		pp.ParameterSourceTypeId,
		pp.ParameterSourceId,
		tpm.Title AS ParameterName,
		ISNULL(tpm.StaticTestParameterId,0) AS StaticParameterSourceId, 
		pp.OrderIndex
	FROM 
		[sWellness].[tProgramParameter] pp
	INNER JOIN 
		[sOrderEntry].[tTestParameterMaster] tpm ON pp.ParameterSourceId = tpm.Id
	WHERE 
		pp.ParameterTypeId = 3 
	AND 
		pp.ProgramId = @rProgramId 
	AND 
		pp.OrgId = @rOrgId
END
GO
PRINT N'Altering Procedure [sSupport].[pHealthSurveySetupIndicatorSaveOrUpdate]...';


GO
-- exec [sSupport].[pHealthSurveySetupIndicatorSaveOrUpdate] 9999,1234
CREATE OR ALTER PROCEDURE [sSupport].[pHealthSurveySetupIndicatorSaveOrUpdate]
	@rOrgId smallint,
	@rStrSetupIndicator varchar(max)
as
begin
		BEGIN TRY 
				declare @loindicatorXML xml
				select @rStrSetupIndicator=[sSetup].[fPortalXMLTagsReplaceReverse](@rStrSetupIndicator)
				set @loindicatorXML = cast(@rStrSetupIndicator as xml)		
	
				declare @tblSetupIndicator table(tid int identity(1,1),t_id int,t_code varchar(100),t_title varchar(100),t_minrange varchar(200),t_maxrange varchar(200),t_isObsolete bit,t_healthSurveyId int,t_colorCode varchar(200),t_healthIndicatorLabel varchar(200))
				insert into @tblSetupIndicator
				select T.c.value('@Id','int') as Id,
				T.c.value('@Code','varchar(300)') as Code,
				T.c.value('@Title','varchar(300)') as Title,
				T.c.value('@MinRange','varchar(200)') as MinRange,
				T.c.value('@MaxRange','varchar(200)') as MaxRange,
				T.c.value('@IsObsolete','bit') as IsObsolete,
				T.c.value('@HealthSurveyId','int') as HealthSurveyId,
				T.c.value('@ColorCode','varchar(200)') as ColorCode,
				T.c.value('@HealthIndicatorLabel','varchar(200)') as HealthIndicatorLabel
				from @loindicatorXML.nodes('/IndicatorRanges/IndicatorRange')T(c)
				--select * from @tblSetupIndicator
				MERGE sSupport.tHealthSetupIndicator AS Target USING 
				(
					SELECT t_id,t_code,t_title,t_maxrange,t_minrange,t_isObsolete,t_healthSurveyId,t_colorCode,t_healthIndicatorLabel
					FROM @tblSetupIndicator 
				) AS Source ON Target.Id=Source.t_id and Target.HealthSurveyId = Source.t_healthSurveyId and Target.OrgId=@rOrgId
				WHEN MATCHED THEN
					UPDATE SET Target.RangeFrom = t_minrange,Target.RangeTo = t_maxrange,Target.ColorCode = t_colorCode,Target.HealthIndicatorLabel = t_healthIndicatorLabel,IsObsolete = case when t_isObsolete = 1 then 0 else 1 end
				WHEN NOT MATCHED THEN
					INSERT(Code,Title,IsObsolete,OrgId,RangeFrom,RangeTo,HealthSurveyId,ColorCode,HealthIndicatorLabel) values(t_code,t_title,case when t_isObsolete = 1 then 0 else 1 end,@rOrgId,t_minrange,t_maxrange,t_healthSurveyId,t_colorCode,t_healthIndicatorLabel);
				select 1 as StatusCode
		END TRY 
		BEGIN CATCH
		--select ERROR_MESSAGE() as message
		select -101 as StatusCode
		END CATCH		
end
GO
PRINT N'Altering Procedure [sSupport].[pMobHealthSurveyResponseMasterSaveOrUpdate]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pMobHealthSurveyResponseMasterSaveOrUpdate]
	@rOrgId smallint,	
	@rStrSurveyResponseMasterXML nvarchar(max),
	@rStrSurveyResponseDetailXML nvarchar(max)	
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lNextNumber BIGINT 
	declare @earnedPoints decimal(10,2)
	declare @totalPoints decimal(10,2)
	declare @percentage decimal(10,2)
	declare @riskTitle nvarchar(100)
	declare @loXMLSurveyResponseMasters xml
	declare @loXMLSurveyResponseDetails xml
	
	BEGIN TRY	

	SET @loXMLSurveyResponseMasters = CAST(@rStrSurveyResponseMasterXML AS xml)
	SET @loXMLSurveyResponseDetails = CAST(@rStrSurveyResponseDetailXML AS xml)
	
	BEGIN Transaction		
		/*****************Start Insert or Update Survey Response Master*****************/	
		Create table #tbltmpSurveyResponseMaster
		(
			tid int identity(1,1),
			srd_Id int,
			srd_AssignSurveyId int,
			srd_SourceTypeId smallint,
			srd_SourceId bigint,
			srd_StatusId smallint
		)
		
		INSERT INTO #tbltmpSurveyResponseMaster
		SELECT 
			T.c.value('@Id','int') as Id,
			T.c.value('@AssignSurveyId','int') as AssignSurveyId,
			95 as SourceTypeId,
			T.c.value('@SourceId','bigint') as SourceId,
			T.c.value('@StatusId','smallint') as StatusId
		FROM @loXMLSurveyResponseMasters.nodes('/HealthSurveyResponseMasters/HealthSurveyResponseMaster')T(c)
			
		if(exists(select 1 from #tbltmpSurveyResponseMaster where srd_Id=0))
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSupport.tHealthSurveyResponseMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		END
		ELSE
		BEGIN
			select @lNextNumber=srd_Id from #tbltmpSurveyResponseMaster
		END
		
		SELECT * FROM #tbltmpSurveyResponseMaster
			
		MERGE sSupport.tHealthSurveyResponseMaster AS Target 
		USING 
		(
			select * from #tbltmpSurveyResponseMaster 
		) AS Source ON Target.Id=srd_Id and Target.SourceId = Source.srd_SourceId and Target.AssignSurveyId =Source.srd_AssignSurveyId and Target.OrgId=@rOrgId
		WHEN MATCHED THEN
			UPDATE SET StatusId=srd_StatusId,UpdatedUserId=srd_SourceId,UpdatedDateTime=sCommon.fGetDate()
		WHEN NOT MATCHED THEN
			INSERT
			(
				Id,AssignSurveyId,OrgId,SourceTypeId,SourceId,StatusId,CreatedDateTime,CreatedUserId		
			)
			VALUES
			(				
				@lNextNumber,srd_AssignSurveyId,@rOrgId,srd_SourceTypeId,srd_SourceId,srd_StatusId,sCommon.fGetDate(),srd_SourceId
			);
			/*****************End Insert or Update Survey Response Master*****************/	
			
			/*****************Start Insert or Update Survey Response Detail*****************/		
	        Create table #tbltmpSurveyResponseDetail
			(
				tid int identity(1,1),
				srd_Id int,
				srd_SurveyResponseId int,
				srd_QuestionId int,
				srd_Answer nvarchar(max),
				srd_EarnedPoints decimal(18,2),
				srd_TotalPoints decimal(18,2),
				srd_Recommendation nvarchar(250),
				srd_Remark nvarchar(max)
			)	
			
	        INSERT INTO #tbltmpSurveyResponseDetail
			SELECT 
				T.c.value('@Id','int') as Id,
				@lNextNumber as SurveyResponseId,
				T.c.value('@QuestionId','int') as QuestionId,		
				[sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Answer','nvarchar(max)')) as Answer,
				T.c.value('@EarnedPoints','decimal(10,2)') as EarnedPoints,
				T.c.value('@TotalPoints','decimal(10,2)') as TotalPoints,
				[sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Recommendation','nvarchar(250)')) as Recommendation,
				(T.c.value('@Remark','nvarchar(max)')) as Remark
			FROM @loXMLSurveyResponseDetails.nodes('/HealthSurveyResponseDetails/HealthSurveyResponseDetail')T(c)		
			
			IF OBJECT_ID('tempdb..#temp_FormulaQuestionList') IS NOT NULL
			BEGIN
				   DROP TABLE #temp_FormulaQuestionList
			END 

			SELECT 
				ROW_NUMBER() OVER(ORDER By Id) 'RowNumber',
				Id 'QuestionID',
				Code 'QuestionCode',
				Title 'QuestionTitle',
				SelectedFormulaQuestionIds 'SelectedFormulaQuestionIds',
				AppliedFormula 'AppliedFormula'
				INTO #temp_FormulaQuestionList
			FROM sSupport.tHealthSurveyParameterMaster 
			WHERE HealthSurveyAnsTypeId = 5 
				  AND HealthSurveyId IN (SELECT ASM.HealthSurveyId FROM sSupport.tAssignSurveyMaster ASM WHERE ASM.Id=(SELECT TOP(1) srd_AssignSurveyId FROM #tbltmpSurveyResponseMaster) and ASM.OrgId=@rOrgId)
			

			DECLARE @i_Row int = 1 
			DECLARE @TotalCount int = (SELECT COUNT(1) FROM #temp_FormulaQuestionList)
			WHILE @i_Row <= @TotalCount
			BEGIN 
				DECLARE @QuestionID int = 0, @QuestionCode NVARCHAR(MAX) = '', @QuestionTitle NVARCHAR(MAX) = '', @SelectedFormulaQuestionIds NVARCHAR(MAX) = '', @AppliedFormula NVARCHAR(MAX) = ''
				DECLARE @FormulaAnswer nvarchar(MAX) = ''
				SELECT
					TOP(1)
					@QuestionID = QuestionID,
					@QuestionCode = QuestionCode,
					@QuestionTitle = QuestionTitle,
					@SelectedFormulaQuestionIds = SelectedFormulaQuestionIds,
					@AppliedFormula = AppliedFormula
				FROM #temp_FormulaQuestionList WHERE RowNumber = @i_Row
				
				IF ISNULL(@SelectedFormulaQuestionIds,'') != ''
				BEGIN
					SELECT 
						@AppliedFormula = REPLACE(@AppliedFormula,'{'+HSP.Code+'}',CAST(TSR.srd_Answer as decimal(18,2)))
					FROM sSupport.tHealthSurveyParameterMaster HSP
					INNER JOIN #tbltmpSurveyResponseDetail TSR on HSP.Id = TSR.srd_QuestionId
					WHERE Id IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@SelectedFormulaQuestionIds,','))

					SET @AppliedFormula = 'SELECT ('+@AppliedFormula+')'

					DECLARE @Output table
					(
						Answer decimal(18,2)
					)

					BEGIN TRY 
						INSERT INTO @Output
						EXEC (@AppliedFormula)
					END TRY
					BEGIN CATCH 
						INSERT INTO @Output VALUES (0)
					END CATCH

					SELECT @FormulaAnswer = CAST(Answer as nvarchar) FROM @Output

					INSERT INTO #tbltmpSurveyResponseDetail (srd_Id,srd_SurveyResponseId,srd_QuestionId,srd_Answer,srd_EarnedPoints,srd_TotalPoints,srd_Recommendation,srd_Remark)	
					SELECT 0 'srd_Id',
						   @lNextNumber 'srd_SurveyResponseId',
						   @QuestionID 'srd_QuestionId',
						   @FormulaAnswer 'srd_Answer',
						   0 'srd_EarnedPoints',
						   MAX(CONVERT(numeric,Points)) 'srd_TotalPoints',
						   '' 'srd_Recommendation',
						   '' 'srd_Remark'
					FROM sSupport.tHealthSurveyParameterDetail 
					WHERE HealthSurveyParameterId = @QuestionID AND OrgId = @rOrgId
				END

				SET @i_Row = @i_Row +1
			END


			IF OBJECT_ID('tempdb..#temp_FormulaQuestionList') IS NOT NULL
			BEGIN
				   DROP TABLE #temp_FormulaQuestionList
			END 


			SELECT * FROM #tbltmpSurveyResponseDetail

			----- updating earned point and recommendation tips for numeric type questions -------
			UPDATE tmptbl 
				set tmptbl.srd_EarnedPoints=HSPD.Points,
					tmptbl.srd_Recommendation=HSPD.RecommendationTips 
			FROM #tbltmpSurveyResponseDetail tmptbl 
			INNER JOIN sSupport.tHealthSurveyParameterMaster HSPM on tmptbl.srd_QuestionId=HSPM.Id and (HSPM.HealthSurveyAnsTypeId=1 OR HSPM.HealthSurveyAnsTypeId = 5)
			INNER JOIN sSupport.tHealthSurveyParameterDetail HSPD on HSPM.Id=HSPD.HealthSurveyParameterId and convert(decimal(10,2),tmptbl.srd_Answer)>=convert(float,HSPD.FromValue) and convert(decimal(10,2),tmptbl.srd_Answer)<=convert(float,HSPD.ToValue)
			
			
	        MERGE sSupport.tHealthSurveyResponseDetail AS Target USING 
			(
				select * from #tbltmpSurveyResponseDetail
			) AS Source ON Target.SurveyResponseId = Source.srd_SurveyResponseId and Target.QuestionId=srd_QuestionId
			WHEN MATCHED THEN
				UPDATE SET Target.Answer=srd_Answer, 
						   Target.EarnedPoints = srd_EarnedPoints,
						   Target.TotalPoints = srd_TotalPoints,
					       Target.Recommendation  = srd_Recommendation,
						   Target.Remark=srd_Remark
			WHEN NOT MATCHED THEN
				INSERT
				(
					SurveyResponseId,QuestionId,Answer,EarnedPoints,
					TotalPoints,Recommendation,Remark
				)
				VALUES
				(
					srd_SurveyResponseId,srd_QuestionId,srd_Answer,srd_EarnedPoints,srd_TotalPoints,srd_Recommendation,srd_Remark
				);			
			/*****************End Insert or Update Survey Response Detail*****************/	


			------- update final earned and total points to assignsurveydetails-------
	
			DECLARE @tblHealthSurveyReport table
			(
				Id int identity(1,1),
				t_EarnedPoint decimal(18,2),
				t_TotalPoint decimal(18,2),
				t_EarnedPercentage decimal(18,2),
				t_RiskTitle nvarchar(100)
			)

			DECLARE @tmpTableUniqueValues table
			(
				Id int identity(1,1),
				srd_SourceId bigint,
				srd_AssignSurveyId int
			)

			insert into @tmpTableUniqueValues(srd_SourceId,srd_AssignSurveyId) 
			select distinct srd_SourceId,srd_AssignSurveyId from #tbltmpSurveyResponseMaster

			insert into @tblHealthSurveyReport 
			select 
				sum(HSRD.EarnedPoints) as EarnedPoint,
				sum(HSRD.TotalPoints) as TotalPoint,
				(sum(HSRD.EarnedPoints)*100)/sum(HSRD.TotalPoints) as t_EarnedPercentage,
				'' 
			from sSupport.tHealthSurveyResponseMaster HSRM
			inner join sSupport.tHealthSurveyResponseDetail HSRD on HSRM.Id=HSRD.SurveyResponseId
			inner join @tmpTableUniqueValues temp on temp.srd_SourceId=	HSRM.SourceId and temp.srd_AssignSurveyId=HSRM.AssignSurveyId
			where HSRM.Id=@lNextNumber and  HSRM.OrgId=@rOrgId 
			--where HSRM.Id=@lNextNumber and HSRM.SourceId=(select top 1 srd_SourceId from #tbltmpSurveyResponseMaster) 
			--and  HSRM.OrgId=@rOrgId and HSRM.AssignSurveyId=(select top 1 srd_AssignSurveyId from #tbltmpSurveyResponseMaster)

			select 
				@earnedPoints=t_EarnedPoint,
				@totalPoints=t_TotalPoint,
				@percentage=t_EarnedPercentage,
				@riskTitle=ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title)
			from @tblHealthSurveyReport temptbl 
			inner join sSupport.tHealthSetupIndicator HSI on temptbl.t_EarnedPercentage>=HSI.RangeFrom and temptbl.t_EarnedPercentage<=HSI.RangeTo
			inner join sSupport.tAssignSurveyMaster ASM on ASM.HealthSurveyId=HSI.HealthSurveyId			   
			where ASM.Id=(select top 1 srd_AssignSurveyId from #tbltmpSurveyResponseMaster)
				
			update sSupport.tAssignSurveyDetail set EarnedPoints=isnull(@earnedPoints,0),TotalPoints=isnull(@totalPoints,0),Percentage=isnull(@percentage,0),IndicatorName=@riskTitle,UpdatedDateTime=sCommon.fGetDate(),
			UpdatedUserId=(select top 1 srd_SourceId from #tbltmpSurveyResponseMaster)
				where SourceId=(select top 1 srd_SourceId from #tbltmpSurveyResponseMaster) 
					 and AssignSurveyId=(select top 1 srd_AssignSurveyId from #tbltmpSurveyResponseMaster)
        COMMIT Transaction
		--DROP TABLE #tbltmpParameterDetails
	select @lNextNumber as Result	
END TRY
BEGIN CATCH 
	IF @@TRANCOUNT > 0
        ROLLBACK
	select -101 as Result
	select ERROR_MESSAGE() 
	--DROP TABLE #tbltmpParameterDetails
END CATCH
END
GO
PRINT N'Altering Procedure [sSupport].[pHealthSurveyAnalysisDashboardDataGet]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pHealthSurveyAnalysisDashboardDataGet]
@rAssignSurveyId int,  
@rOrgId int  
AS  
BEGIN  
declare @totalCount decimal(18,2)  
declare @healthSurveyId int  
  
  
select @healthSurveyId=ASM.HealthSurveyId from sSupport.tAssignSurveyMaster ASM where ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId   
  
-------------------------------------------start getting survey templates------------------------------------------------  
  
select ASM.Title,case when SM.Title is null then '' else SM.Title end as SetupName,convert(varchar, ASM.FromDate, 103) as FromDate,convert(varchar, ASM.ToDate, 103) as ToDate,ASM.HealthSurveyId from sSupport.tAssignSurveyMaster ASM  
           left join sExamination.tSetupMaster SM on ASM.SetupId=SM.Id where ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId  
  
-------------------------------------------end getting survey templates------------------------------------------------  
  
-------------------------------------------start getting card employee count------------------------------------------------  
select @totalCount=count(ASM.Id) from sSupport.tAssignSurveyMaster ASM  
    inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
    left join sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId  
    where ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId  
  
select @totalCount as TotalEmployee,Count(SRM.Id) as SurveyedEmployee,Count(HSI.Id) as TotalRiskCount,case when Count(HSI.Id)>0 then(Count(HSI.Id)*100)/Count(SRM.Id) else 0 end as PercentageRisk from sSupport.tAssignSurveyMaster ASM  
    inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
    inner join sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId  
    left join sSupport.tHealthSetupIndicator HSI on ASM.HealthSurveyId=HSI.HealthSurveyId and HSI.Title like '%Risk%' and ((isnull(ASD.EarnedPoints,0)*100)/isnull(ASD.TotalPoints,0))>=HSI.RangeFrom and ((isnull(ASD.EarnedPoints,0)*100)/isnull(ASD.TotalPoints,0))<=HSI.RangeTo  
    where ASM.id=@rAssignSurveyId and ASD.TotalPoints!=0 and  ASM.OrgId=@rOrgId  AND HSI.IsObsolete = 0
  
--select 100 as TotalEmployee,80 as SurveyedEmployee,20 as TotalRiskCount,(20*100)/80 as PercentageRisk   
-------------------------------------------end getting card employee count------------------------------------------------  
  
-------------------------------------------start getting doughnut chart and indicator wise chart data------------------------------------------------  
select ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) AS Title ,count(ASD.IndicatorName) as IndicatorCount,HSI.ColorCode AS IndicatorColor,
case when count(ASD.IndicatorName)>0 then count(ASD.IndicatorName)*100/sum(count(ASD.IndicatorName)) over() else 0 end as Percentage from sSupport.tAssignSurveyMaster ASM  
   inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId and ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId  
   inner join sSupport.tHealthSurveyResponseMaster HSRM on HSRM.StatusId=554 and HSRM.AssignSurveyId=ASM.Id and ASD.SourceId=HSRM.SourceId  
   right join sSupport.tHealthSetupIndicator HSI on (HSI.Title=ASD.IndicatorName OR HSI.HealthIndicatorLabel=ASD.IndicatorName) and HSI.HealthSurveyId=ASM.HealthSurveyId  
   where HSI.HealthSurveyId=@healthSurveyId AND HSI.IsObsolete = 0
   group by HSI.Id,ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),HSI.ColorCode order by HSI.Id asc  

--declare @tmpTable1 table(Id int identity(1,1),Title nvarchar(50),IndicatorCount int,Percentage decimal(18,2))  
--insert into @tmpTable1 values('High Risk',10,(10*100)/80)  
--insert into @tmpTable1 values('Moderate Risk',5,(5*100)/80)  
--insert into @tmpTable1 values('Low Risk',5,(5*100)/80)  
--insert into @tmpTable1 values('Healthy',30,(30*100)/80)  
--insert into @tmpTable1 values('Very Healthy',18,(18*100)/80)  
--insert into @tmpTable1 values('Classic Well',12,(12*100)/80)  
--select * from @tmpTable1  
  
-------------------------------------------end getting doughnut chart and indicator wise chart data------------------------------------------------  
  
-------------------------------------------start getting department wise chart data------------------------------------------------  
  
  select case when t1.OrganizationDepartment is null then t2.OrganizationDepartment else t1.OrganizationDepartment end as DepartmentName,  
  ISNULL(t1.RiskCount,0) as RiskCount, ISNULL(t2.HealthyCount,0) as HealthyCount,ISNULL(t1.RiskCount,0)+ISNULL(t2.HealthyCount,0) as TotalCount from   
  (select ECS.OrganizationDepartmentId,ECS.OrganizationDepartment,Count(*) as RiskCount from sSupport.tAssignSurveyMaster ASM  
    inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
    inner join sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId   
    inner join sHrm.vEmployeeCustomSearch ECS on ECS.EmployeeId=SRM.SourceId  
    inner join sSupport.tHealthSetupIndicator HSI on (HSI.Title=ASD.IndicatorName OR HSI.HealthIndicatorLabel=ASD.IndicatorName) and HSI.HealthSurveyId=ASM.HealthSurveyId  
    where ASM.id=@rAssignSurveyId and  ASM.OrgId=@rOrgId AND HSI.IsObsolete = 0 and (HSI.Code=1 or HSI.Code=2 or HSI.Code=3) group by ECS.OrganizationDepartmentId,ECS.OrganizationDepartment) as t1  
  
    full join   
    (select ECS.OrganizationDepartmentId,ECS.OrganizationDepartment,Count(*) as HealthyCount from sSupport.tAssignSurveyMaster ASM  
    inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
    inner join sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId   
    inner join sHrm.vEmployeeCustomSearch ECS on ECS.EmployeeId=SRM.SourceId  
    inner join sSupport.tHealthSetupIndicator HSI on (HSI.Title=ASD.IndicatorName OR HSI.HealthIndicatorLabel=ASD.IndicatorName) and HSI.HealthSurveyId=ASM.HealthSurveyId  
    where ASM.id=@rAssignSurveyId and  ASM.OrgId=@rOrgId  AND HSI.IsObsolete = 0 and (HSI.Code=4 or HSI.Code=5 or HSI.COde=6) group by ECS.OrganizationDepartmentId,ECS.OrganizationDepartment) as t2  
    on t1.OrganizationDepartmentId=t2.OrganizationDepartmentId  
  
--  declare @tmpTable2 table(DepartmentId int,DepartmentName nvarchar(50),RiskCount int,HealthyCount int,TotalCount int)  
--insert into @tmpTable2 values(1,'ABEX',3,9,12)  
--insert into @tmpTable2 values(2,'Mechanical',6,6,12)  
--insert into @tmpTable2 values(3,'Acounts',2,23,25)  
--insert into @tmpTable2 values(4,'CORPORATE AFFAIRS',4,7,11)  
--insert into @tmpTable2 values(5,'BUSINESS & DEVELOPMENT',5,15,20)  
  
--select * from @tmpTable2  
    
      
-------------------------------------------end getting department wise chart data------------------------------------------------  
  
-------------------------------------------start getting health champion data------------------------------------------------  
   select  ECS.Code,ECS.Name ,ECS.OrganizationDepartment,EI.EmployeePhoto from sSupport.tAssignSurveyMaster ASM   
       inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
       inner join sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and ASD.AssignSurveyId=SRM.AssignSurveyId and ASD.SourceId=SRM.SourceId  
       inner join (select * from sSupport.tHealthSetupIndicator where HealthSurveyId=@healthSurveyId and RangeTo=(select max(RangeTo) from sSupport.tHealthSetupIndicator where HealthSurveyId=@healthSurveyId)) as HSI on HSI.Title=ASD.IndicatorName  
       inner join sHrm.vEmployeeCustomSearch ECS on SRM.SourceId=ECS.EmployeeId  
       left join sHrm.tEmployeeImages EI on EI.EmployeeId=ECS.EmployeeId  
       where ASM.id=@rAssignSurveyId and  ASM.OrgId=@rOrgId  
   --select  ECS.Code,ECS.Name ,ECS.OrganizationDepartment,EI.EmployeePhoto from  sHrm.vEmployeeCustomSearch ECS   
   --    left join sHrm.tEmployeeImages EI on EI.EmployeeId=ECS.EmployeeId   
   --    where  ECS.Code in ('1400004','1400006','1400008','1600023','64565','E-1222','EM17-160')  
     
-------------------------------------------end getting health champion data------------------------------------------------  
  
-------------------------------------------start getting indicator breakdown data------------------------------------------------  
   declare @tableHealthReport table(Id int identity(1,1),GroupId int,HealthTitle nvarchar(50),IndicatorId int,IndicatorName nvarchar(50),IndicatorCount int,IndicatorColor nvarchar(50)) 
   
   insert into @tableHealthReport select HSPGM.Id,HSPGM.Title,HSI.Id,ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) AS Title,count(HSPGM.Title) as IndicatorCount,HSI.ColorCode AS IndicatorColor
   from sSupport.tHealthSurveyResponseMaster HSRM  
   inner join sSupport.tHealthSurveyResponseDetail HSRD on HSRM.StatusId=554 and HSRM.Id=HSRD.SurveyResponseId and HSRM.AssignSurveyId=@rAssignSurveyId  
   inner join sSupport.tHealthSurveyParameterMaster HSPM on HSPM.Id=HSRD.QuestionId  
   inner join sSupport.tHealthSurveyParameterGroupMaster HSPGM on HSPGM.Id=HSPM.GroupId  
   inner join sSupport.tHealthSetupIndicator HSI on (case when HSRD.TotalPoints != 0 then (HSRD.EarnedPoints*100)/HSRD.TotalPoints else HSRD.TotalPoints end) >=HSI.RangeFrom and (case when HSRD.TotalPoints != 0 then (HSRD.EarnedPoints*100)/HSRD.TotalPoints else HSRD.TotalPoints end)<=HSI.RangeTo   
   where HSI.HealthSurveyId=@healthSurveyId and HSPM.HealthSurveyAnsTypeId != 4 AND HSI.IsObsolete = 0
   group by HSPGM.Id,HSPGM.Title,HSI.Id,ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),HSI.ColorCode,HSRM.SourceId order by HSPGM.Id,HSI.Id asc        


   IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
   BEGIN
   	    DROP TABLE #temp_AddedHeathDetail
   END

   CREATE TABLE #temp_AddedHeathDetail
   (
	   HealthTitle NVARCHAR(MAX),
	   IndicatorCount BIGINT,
	   IndicatorName NVARCHAR(MAX),
	   IndicatorColor NVARCHAR(MAX)
   )

   --select  @healthSurveyId,@rAssignSurveyId
   INSERT INTO #temp_AddedHeathDetail
    select 
		  'Mental Health' as HealthTitle,
		  SUM(case when tmptbl.IndicatorCount is null then 0 else tmptbl.IndicatorCount end) as IndicatorCount,
		  ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) as IndicatorName,HSI.ColorCode AS IndicatorColor
    from sSupport.tHealthSetupIndicator HSI  
    left join (select * from @tableHealthReport where GroupId=1) as tmptbl on HSI.Id=tmptbl.IndicatorId  
    where HSI.HealthSurveyId=@healthSurveyId  AND HSI.IsObsolete = 0
	GROUP BY ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),HSI.ColorCode

	INSERT INTO #temp_AddedHeathDetail
    select 
		'Physical Health' as HealthTitle,
		SUM(case when tmptbl.IndicatorCount is null then 0 else tmptbl.IndicatorCount end) as IndicatorCount,
		ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) as IndicatorName,HSI.ColorCode AS IndicatorColor
	from sSupport.tHealthSetupIndicator HSI  
    left join (select * from @tableHealthReport where GroupId=2) as tmptbl on HSI.Id=tmptbl.IndicatorId  
    where HSI.HealthSurveyId=@healthSurveyId  AND HSI.IsObsolete = 0
   GROUP BY ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),HSI.ColorCode

   INSERT INTO #temp_AddedHeathDetail
	select 
	   'General Health' as HealthTitle,
	    SUM(case when tmptbl.IndicatorCount is null then 0 else tmptbl.IndicatorCount end) as IndicatorCount,
		ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) as IndicatorName,HSI.ColorCode AS IndicatorColor 
	from sSupport.tHealthSetupIndicator HSI  
    left join (select * from @tableHealthReport where GroupId=3) as tmptbl on HSI.Id=tmptbl.IndicatorId  
    where HSI.HealthSurveyId=@healthSurveyId  AND HSI.IsObsolete = 0
     GROUP BY ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),HSI.ColorCode


	 SELECT * FROM #temp_AddedHeathDetail
 -------------------------------------------end getting indicator breakdown data------------------------------------------------   
   
END
GO
PRINT N'Altering Procedure [sSupport].[pHealthSurveyAnalysisDashboardReportRecord]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pHealthSurveyAnalysisDashboardReportRecord]
	@rAssignSurveyId int,  
	@rOrgId int  
AS  
BEGIN  
	DECLARE @TotalEmployeeCount DECIMAL(18,2)  
	DECLARE @healthSurveyId INT  
	DECLARE @SurvayName NVARCHAR(MAX)  
	IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
	BEGIN
		   DROP TABLE #temp_ReportSetup
	END

	IF OBJECT_ID('tempdb..#temp_tHealthSetupIndicator') IS NOT NULL
	BEGIN
		   DROP TABLE #temp_tHealthSetupIndicator
	END
 
	SELECT 
		@healthSurveyId=ASM.HealthSurveyId,
		@SurvayName = ASM.Title
	FROM sSupport.tAssignSurveyMaster ASM 
	WHERE ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId   
   
  
	
	SELECT 
		@TotalEmployeeCount=count(ASM.Id) 
	FROM sSupport.tAssignSurveyMaster ASM  
	INNER JOIN sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
	LEFT JOIN sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId  
	WHERE ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId  
	

	SELECT *,
	CASE WHEN Code = 1 THEN 'red' 
		 WHEN Code = 2 THEN 'yellow' 
		 WHEN Code = 3 THEN 'grey' 
		 WHEN Code = 4 THEN 'cyan' 
		 WHEN Code = 5 THEN 'green' 
		 ELSE 'blue' END 'ColorName',
	CASE
	WHEN NULLIF(LTRIM(RTRIM(ColorCode)), '') IS NOT NULL 
        THEN ColorCode
    ELSE 
        CASE 
            WHEN Code = 1 THEN '#f33'
            WHEN Code = 2 THEN '#777'
            WHEN Code = 3 THEN '#aaa'
            WHEN Code = 4 THEN '#149df9'
            WHEN Code = 5 THEN '#3bb200'
            ELSE '#00b2b2'
        END
	END AS ChartColorName,
		 CAST(ISNULL(RangeFrom,0) as nvarchar) + '% - ' + CAST(ISNULL(RangeTo,0) as nvarchar) + '%' 'Range'
	INTO #temp_tHealthSetupIndicator
	FROM sSupport.tHealthSetupIndicator WHERE OrgId = @rOrgId AND HealthSurveyId = @healthSurveyId AND IsObsolete = 0


	------------------------------------------- START Employee Count Details ------------------------------------------------  

	-- START Table 1 --
	SELECT 
		Count(SRM.Id) as SurveyedEmployee,
		(@TotalEmployeeCount - Count(SRM.Id)) as InProgessEmployee,
		((Count(SRM.Id) * 100) / @TotalEmployeeCount) 'CompletedPercetage'
	FROM sSupport.tAssignSurveyMaster ASM  
    INNER JOIN sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
    INNER JOIN sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId  
    LEFT JOIN #temp_tHealthSetupIndicator HSI on ASM.HealthSurveyId=HSI.HealthSurveyId and HSI.Title like '%Risk%' and ((isnull(ASD.EarnedPoints,0)*100)/isnull(ASD.TotalPoints,0))>=HSI.RangeFrom and ((isnull(ASD.EarnedPoints,0)*100)/isnull(ASD.TotalPoints,0))<=HSI.RangeTo  
    where ASM.id=@rAssignSurveyId and ASD.TotalPoints!=0 and  ASM.OrgId=@rOrgId  AND HSI.IsObsolete = 0 
	-- END Table 1 --

	-------------------------------------------END Employee Count Details------------------------------------------------  
  
    -------------------------------------- START Indicator Details Data - Table 2 ------------------------------------------------  
	SELECT 
		HSI.Id,
		ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) AS Title,
		count(ASD.IndicatorName) as IndicatorCount,
		CAST((CASE WHEN count(ASD.IndicatorName)>0 then CAST(count(ASD.IndicatorName) as decimal(18,2))*100/sum(CAST(count(ASD.IndicatorName) as decimal(18,2))) over() else 0 end) as decimal(18,2)) as Percentage,
		HSI.ColorName,
		HSI.ChartColorName,
		HSI.Range
	from sSupport.tAssignSurveyMaster ASM  
    INNER JOIN sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId and ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId  
    INNER JOIN sSupport.tHealthSurveyResponseMaster HSRM on HSRM.StatusId=554 and HSRM.AssignSurveyId=ASM.Id and ASD.SourceId=HSRM.SourceId  
    RIGHT JOIN #temp_tHealthSetupIndicator HSI on (HSI.Title=ASD.IndicatorName OR HSI.HealthIndicatorLabel=ASD.IndicatorName) and HSI.HealthSurveyId=ASM.HealthSurveyId  
   where HSI.HealthSurveyId=@healthSurveyId  AND HSI.IsObsolete = 0 
   group by HSI.Id,ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),HSI.ColorName,HSI.ChartColorName,HSI.Range
   order by HSI.Id asc  

   -------------------------------------- END Indicator Details Data - Table 2 ------------------------------------------------  
  

   -------------------------------------- START Section and Question Wise Details ------------------------------------------------ 

   DECLARE @tableHealthReport table
   (
	  Id int identity(1,1),
	  QuestionId int,
	  Question nvarchar(MAX),
	  IndicatorId int,
	  IndicatorName nvarchar(50),
	  ColorClass nvarchar(MAX),
	  ChartColor nvarchar(MAX),
	  TotalPercentage decimal(18,2),
	  RecommendationTips nvarchar(max),
	  ReportSetupID bigint,
	  SectionTitle nvarchar(max),
	  SectionDescription nvarchar(max),
	  EmployerDescription nvarchar(max),
	  ReadAboutIt nvarchar(max),
	  Probability nvarchar(max),
	  WhattoEat nvarchar(max)
   )  

   IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
   BEGIN
   	   DROP TABLE #temp_ReportSetup
   END


   SELECT
		SRM.Id 'ReportSetupID',
		SRM.SectionTitle,
		SRM.SectionDescription,
		SRM.ReadAboutIt,
		SRM.Probability,
		SRM.WhattoEat,
		SRM.EmployerDescription,
		OA.QuestionID
		INTO #temp_ReportSetup 
	FROM sSupport.tSurveyReportSetupMaster  SRM
	OUTER APPLY
	(
		SELECT CAST(item as bigint) 'QuestionID' FROM sCommon.fnsplit(SRM.ParameterMasterIds,',')
	) OA
	WHERE SRM.TemplateId = @healthSurveyId AND SRM.OrgId = @rOrgId


   INSERT INTO @tableHealthReport 
   SELECT 
		HSPM.Id 'QuestionId',
		ISNULL(HSPM.ShortName, ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title)) as Question,
		HSI.Id,
		ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) AS Title,
		HSI.ColorName,
		HSI.ChartColorName,
		--0 as Percentage,
		CASE WHEN HSRD.TotalPoints != 0 THEN (HSRD.EarnedPoints*100)/HSRD.TotalPoints ELSE 0 END as TotalPercentage,
		ISNULL(HSPDC.RecommendationTips,''),
		trs.ReportSetupID,
		trs.SectionTitle,
		trs.SectionDescription,
		trs.EmployerDescription,
		trs.ReadAboutIt,
		trs.Probability,
		trs.WhattoEat
   FROM sSupport.tHealthSurveyResponseMaster HSRM  
   INNER JOIN sSupport.tHealthSurveyResponseDetail HSRD on HSRM.Id=HSRD.SurveyResponseId  
   INNER JOIN sSupport.tHealthSurveyParameterMaster HSPM on HSPM.Id=HSRD.QuestionId  
   INNER JOIN #temp_ReportSetup trs on trs.QuestionID = HSPM.Id
   INNER JOIN #temp_tHealthSetupIndicator HSI on (case when HSRD.TotalPoints != 0 then (HSRD.EarnedPoints*100)/HSRD.TotalPoints else HSRD.TotalPoints end) BETWEEN HSI.RangeFrom and HSI.RangeTo 
   LEFT JOIN sSupport.tHealthSurveyParameterDetail HSPDC on HSPM.Id=HSPDC.HealthSurveyParameterId
   WHERE HSRM.AssignSurveyId=@rAssignSurveyId AND HSRM.StatusId=554 AND HSI.HealthSurveyId=@healthSurveyId and HSPM.HealthSurveyAnsTypeId != 4 AND HSI.IsObsolete = 0
   ORDER BY HSPM.Id,HSI.Id asc      
   
   --SELECT * FROM @tableHealthReport

   -- START Table 3 --
   SELECT 
		QuestionId,
		Question,
		ReportSetupID, 
		IndicatorId,
		IndicatorName,
		ColorClass,
		ChartColor,
		CAST((CASE WHEN COUNT(IndicatorId) > 0 then (CAST(COUNT(IndicatorId) as decimal(18,2))*100/ SUM(CAST(COUNT(IndicatorId) as decimal(18,2))) over(PARTITION BY QuestionId,Question,ReportSetupID)) else 0 END) as decimal(18,2)) 'Percentage'
   FROM @tableHealthReport
   GROUP BY QuestionId,Question,IndicatorId,IndicatorName,ColorClass,ChartColor,ReportSetupID
   -- END Table 3 --


   -- START Table 4 --
   SELECT tbl.*,
		HSI.Id 'IndicatorID',
		ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) 'IndicatorTitle',
		HSI.ColorName 'ColorName',
		HSI.ChartColorName 'ChartColorName'
   FROM (SELECT 
		ReportSetupID,
		SectionTitle,
		SectionDescription,
		ReadAboutIt,
		Probability,
		WhattoEat,
		ISNULL(EmployerDescription,'') 'EmployerDescription',
		CAST(AVG(TotalPercentage) as decimal(18,2)) 'Percentage'
   FROM @tableHealthReport
   GROUP BY ReportSetupID,
			SectionTitle,
			SectionDescription,
			EmployerDescription,
			ReadAboutIt,
			Probability,
			WhattoEat)tbl
	INNER JOIN #temp_tHealthSetupIndicator HSI on tbl.Percentage between  HSI.RangeFrom AND HSI.RangeTo
	ORDER BY tbl.ReportSetupID
	-- END Table 4 --

	-- START Table 5 --
	SELECT 
		tb.ReportSetupID,
		tb.SectionTitle,
		IndicatorId,
		IndicatorName,
		ColorClass,
		ChartColor,
		CAST((CASE WHEN COUNT(IndicatorId) > 0 then (CAST(COUNT(IndicatorId) as decimal(18,2))*100/ SUM(CAST(COUNT(IndicatorId) as decimal(18,2))) over(PARTITION BY ReportSetupID)) else 0 END) as decimal(18,2)) 'Percentage'
   FROM @tableHealthReport tb
   INNER JOIN #temp_tHealthSetupIndicator HSI on tb.IndicatorId = HSI.Id
   GROUP BY tb.ReportSetupID,
		    tb.SectionTitle,
			IndicatorId,
			IndicatorName,
			ColorClass,
			ChartColor
	-- END Table 5 --
    -------------------------------------- END Section and Question Wise Details ------------------------------------------------ 

	-- START Get detail of Surveyname Table 6 --

	SELECT @SurvayName 'SurvayName'

	-- END Get detail of Surveyname Table 6 --


	---------------- Table 7 - START Employee Age wise Grouping Details -------------------------
	IF OBJECT_ID('tempdb..#temp_EmployeeDetails') IS NOT NULL
    BEGIN
    	  DROP TABLE #temp_EmployeeDetails
    END

	IF OBJECT_ID('tempdb..#temp_EmployeeDemographicsDetails') IS NOT NULL
    BEGIN
    	  DROP TABLE #temp_EmployeeDemographicsDetails
    END

	IF OBJECT_ID('tempdb..#temp_EmployeeAgeGrouping') IS NOT NULL
    BEGIN
    	  DROP TABLE #temp_EmployeeAgeGrouping
    END

	CREATE TABLE #temp_EmployeeAgeGrouping 
	(
		Lable NVARCHAR(MAX),
		FromValue int,
		ToValue int
	)

	--INSERT INTO #temp_EmployeeAgeGrouping VALUES ('18-24',18,24)
	--INSERT INTO #temp_EmployeeAgeGrouping VALUES ('25-34',25,34)
	--INSERT INTO #temp_EmployeeAgeGrouping VALUES ('35-44',35,44)
	--INSERT INTO #temp_EmployeeAgeGrouping VALUES ('45-54',45,54)
	--INSERT INTO #temp_EmployeeAgeGrouping VALUES ('55-64',55,64)
	--INSERT INTO #temp_EmployeeAgeGrouping VALUES ('65+',65,150)

	INSERT INTO #temp_EmployeeAgeGrouping 
	SELECT Title,AgeFrom,AgeTo FROM  sCommon.tAgeGroupMaster WHERE OrgId = @rOrgId


	SELECT
		COUNT(*) OVER() 'SurveyedEmployee',
		EM.Id 'EmployeeID', 
		EPD.GenderId,
		GM.Title 'GenderTitle',
		EPD.DateOfBirth,
		CONVERT(int,ROUND(DATEDIFF(hour,EPD.DateOfBirth,GETDATE())/8766.0,0)) 'EmployeeAge'
		INTO #temp_EmployeeDetails
	FROM sHrm.tEmployeeMaster EM 
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
	WHERE EM.OrgId = @rOrgId AND EM.Id IN (SELECT ASD.SourceId
					FROM sSupport.tAssignSurveyMaster ASM  
					INNER JOIN sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId  
					INNER JOIN sSupport.tHealthSurveyResponseMaster SRM on SRM.StatusId=554 and SRM.AssignSurveyId=ASM.Id and ASD.SourceId=SRM.SourceId  
					where ASM.id=@rAssignSurveyId and ASD.TotalPoints!=0 and  ASM.OrgId=@rOrgId)
					 
	
	CREATE TABLE #temp_EmployeeDemographicsDetails
	(
		Lable NVARCHAR(MAX),
		Percentage decimal(18,2),
		isGenderGroup bit
	)

	INSERT INTO #temp_EmployeeDemographicsDetails
	SELECT GenderTitle,
		  CAST(CAST(COUNT(EmployeeID) as DECIMAL(18,2)) * 100/ SUM(CAST(COUNT(GenderTitle) as decimal(18,2))) OVER() as decimal(18,2)) 'Percentage',
		  1
	FROM #temp_EmployeeDetails 
	GROUP BY GenderTitle,GenderId
	ORDER BY GenderId
	 

	INSERT INTO #temp_EmployeeDemographicsDetails
	SELECT 
		EAG.Lable,
		CAST(CAST(COUNT(ED.EmployeeID) as DECIMAL(18,2)) * 100/ SUM(CAST(COUNT(EAG.Lable) as decimal(18,2))) OVER() as decimal(18,2)) 'Percentage',
		0
	FROM #temp_EmployeeDetails ED
	INNER JOIN  #temp_EmployeeAgeGrouping EAG ON ED.EmployeeAge BETWEEN EAG.FromValue AND EAG.ToValue
	GROUP BY EAG.Lable

	SELECT * FROM #temp_EmployeeDemographicsDetails

	---------------- Table 7 - END Employee Age wise Grouping Details -------------------------


   IF OBJECT_ID('tempdb..#temp_EmployeeDetails') IS NOT NULL
   BEGIN
       DROP TABLE #temp_EmployeeDetails
   END
   IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
   BEGIN
   	   DROP TABLE #temp_ReportSetup
   END
   IF OBJECT_ID('tempdb..#temp_tHealthSetupIndicator') IS NOT NULL
   BEGIN
   	   DROP TABLE #temp_tHealthSetupIndicator
   END
   IF OBJECT_ID('tempdb..#temp_EmployeeDemographicsDetails') IS NOT NULL
   BEGIN
   	   DROP TABLE #temp_EmployeeDemographicsDetails
   END
   IF OBJECT_ID('tempdb..#temp_EmployeeAgeGrouping') IS NOT NULL
   BEGIN
       DROP TABLE #temp_EmployeeAgeGrouping
   END
 -------------------------------------------end getting indicator breakdown data------------------------------------------------   
   
END
GO
PRINT N'Altering Procedure [sSupport].[pHealthSurveyEmployeeReport]...';


GO

CREATE OR ALTER PROCEDURE [sSupport].[pHealthSurveyEmployeeReport]
	@rEmployeeId bigint,  
	@rOrgId int,
	@rAssignSurveyId int
AS  
BEGIN  

	 DECLARE @tblHealthSurveyAnalysis table
	 (
		id int identity(1,1),
		t_QuestionId bigint,
		t_Question nvarchar(150),
		t_Answer nvarchar(max),
		t_EarnedPoint decimal(18,2),
		t_TotalPoint decimal(18,2),
		t_Percentage decimal(18,2),
		t_RecommendationTips nvarchar(max),
		t_ReportSetupID bigint,
		t_SectionTitle nvarchar(max),
		t_SectionDescription nvarchar(max),
		t_ReadAboutIt nvarchar(max),
		t_Probability nvarchar(max),
		t_WhattoEat nvarchar(max)
	 )

	IF OBJECT_ID('tempdb..#temp_ReportSetupWisePercentage') IS NOT NULL
	BEGIN
		DROP TABLE #temp_ReportSetupWisePercentage
	END

	IF OBJECT_ID('tempdb..#temp_HealthSurveyAnalysisDetail') IS NOT NULL
	BEGIN
		DROP TABLE #temp_HealthSurveyAnalysisDetail
	END

	IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
	BEGIN
		DROP TABLE #temp_ReportSetup
	END

	IF OBJECT_ID('tempdb..#temp_tHealthSetupIndicator') IS NOT NULL
	BEGIN
		   DROP TABLE #temp_tHealthSetupIndicator
	END

	DECLARE @healthSurveyId INT  
	DECLARE @SurvayName NVARCHAR(MAX) 
	SELECT 
		@healthSurveyId=ASM.HealthSurveyId,
		@SurvayName = ASM.Title
	FROM sSupport.tAssignSurveyMaster ASM 
	WHERE ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId   


	---------- START GET Survey Employee Details -----------
	SELECT
	   [Id]
      ,[Code]
      , ISNULL(NULLIF(LTRIM(RTRIM(HealthIndicatorLabel)), ''),Title) AS Title
      ,[IsObsolete]
      ,[OrgId]
      ,[RangeFrom]
      ,[RangeTo]
      ,[HealthSurveyId]
      ,[ColorCode]
      ,[HealthIndicatorLabel]
      ,[ProgramId],
	CASE WHEN Code = 1 THEN 'red' 
		 WHEN Code = 2 THEN 'yellow' 
		 WHEN Code = 3 THEN 'grey' 
		 WHEN Code = 4 THEN 'cyan' 
		 WHEN Code = 5 THEN 'green' 
		 ELSE 'blue' END 'ColorName',
	CASE 
    WHEN NULLIF(LTRIM(RTRIM(ColorCode)), '') IS NOT NULL 
        THEN ColorCode
    ELSE 
        CASE 
            WHEN Code = 1 THEN '#f33'
            WHEN Code = 2 THEN '#777'
            WHEN Code = 3 THEN '#aaa'
            WHEN Code = 4 THEN '#149df9'
            WHEN Code = 5 THEN '#3bb200'
            ELSE '#00b2b2'
        END
	END AS ChartColorName,
	CAST(ISNULL(RangeFrom,0) as nvarchar) + '% - ' + CAST(ISNULL(RangeTo,0) as nvarchar) + '%' 'Range'
	INTO #temp_tHealthSetupIndicator
	FROM sSupport.tHealthSetupIndicator WHERE OrgId = @rOrgId AND HealthSurveyId = @healthSurveyId AND IsObsolete = 0


	SELECT
		Id 'ReportSetupID',
		SectionTitle,
		SectionDescription,
		ParameterMasterIds,
		ReadAboutIt,
		Probability,
		WhattoEat
		INTO #temp_ReportSetup 
	FROM sSupport.tSurveyReportSetupMaster 
	WHERE TemplateId = @healthSurveyId AND OrgId = @rOrgId

	INSERT INTO @tblHealthSurveyAnalysis 
	SELECT DISTINCT 
		   HSPM.Id 'QuestionId',
		   ISNULL(HSPM.ShortName, HSPM.Title) as Question,
		   HSRD.Answer as Answer,
		   HSRD.EarnedPoints as EarnedPoint,
		   HSRD.TotalPoints as TotalPoint,
		   case when HSRD.TotalPoints != 0 then (HSRD.EarnedPoints*100)/HSRD.TotalPoints else 0 end as Percentage,
		   ISNULL(HSPDC.RecommendationTips,''),
		   trs.ReportSetupID,
		   trs.SectionTitle,
		   trs.SectionDescription,
		   trs.ReadAboutIt,
		   trs.Probability,
		   trs.WhattoEat
	FROM sSupport.tHealthSurveyResponseMaster HSRM 
	INNER JOIN sSupport.tHealthSurveyResponseDetail HSRD on HSRM.Id=HSRD.SurveyResponseId
	INNER JOIN sSupport.tHealthSurveyParameterMaster HSPM on HSPM.Id=HSRD.QuestionId
	INNER JOIN #temp_ReportSetup trs on EXISTS(SELECT 1 FROM sCommon.fnsplit(trs.ParameterMasterIds,',') WHERE CAST(item as int) = HSPM.Id)
	OUTER APPLY 
	(
		 SELECT TOP(1) ISNULL(RecommendationTips,'') 'RecommendationTips' FROM sSupport.tHealthSurveyParameterDetail WHERE HealthSurveyParameterId = HSPM.Id
	) HSPDC
	WHERE HSRM.AssignSurveyId= @rAssignSurveyId 
		  AND HSRM.SourceId=@rEmployeeId 
		  and HSRM.OrgId=@rOrgId
	 

		SELECT  
		tmptbl.id as Id,
		tmptbl.t_QuestionId 'QuestionId',
		tmptbl.t_Question 'Question',
		tmptbl.t_Answer 'Answer',
		tmptbl.t_EarnedPoint 'EarnedPoint',
		tmptbl.t_TotalPoint 'TotalPoint',
		tmptbl.t_Percentage 'Percentage',
		(case when tmptbl.t_TotalPoint != 0 
			then ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) 
			else '' end) 'RiskTitle',
		tmptbl.t_RecommendationTips 'RecommendationTips',
		tmptbl.t_ReportSetupID 'ReportSetupID',
		tmptbl.t_SectionTitle 'SectionTitle',
		tmptbl.t_SectionDescription 'SectionDescription',
		tmptbl.t_ReadAboutIt 'ReadAboutIt',
		tmptbl.t_Probability 'Probability',
		tmptbl.t_WhattoEat 'WhattoEat',
		HSI.ColorName 'ColorName',
		HSI.ChartColorName 'ChartColorName'
	INTO #temp_HealthSurveyAnalysisDetail
	FROM @tblHealthSurveyAnalysis tmptbl 
	INNER JOIN #temp_tHealthSetupIndicator HSI 
		ON tmptbl.t_Percentage >= HSI.RangeFrom 
	   AND tmptbl.t_Percentage <= HSI.RangeTo
	INNER JOIN sSupport.tAssignSurveyMaster ASM 
		ON ASM.HealthSurveyId = HSI.HealthSurveyId
	INNER JOIN sSupport.tHealthSurveyResponseMaster HSRM 
		ON HSRM.AssignSurveyId = ASM.Id
	WHERE HSRM.AssignSurveyId = @rAssignSurveyId 
	AND HSRM.SourceId = @rEmployeeId
	ORDER BY tmptbl.id ASC

	SELECT tbl.*,
	    HSI.Id 'IndicatorID',
		ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) 'IndicatorTitle',
		HSI.ColorName 'ColorName',
		HSI.ChartColorName 'ChartColorName',
		HSI.Range 'Range'
	INTO #temp_ReportSetupWisePercentage 
	FROM
	(SELECT 
		ReportSetupID,
		SectionTitle,
		SectionDescription,
		ReadAboutIt,
		Probability,
		WhattoEat,
		CAST(AVG(ISNULL(Percentage,0)) as decimal(18,2)) as 'Percentage'
	FROM #temp_HealthSurveyAnalysisDetail tmptbl
	GROUP BY ReportSetupID,
			 SectionTitle,
			 SectionDescription,
			 ReadAboutIt,
			 Probability,
			 WhattoEat)tbl
	INNER JOIN #temp_tHealthSetupIndicator HSI on tbl.Percentage between  HSI.RangeFrom AND HSI.RangeTo

	---------- END GET Survey Employee Details -----------
 

	
	---- START Table 1 - Over-all Percentage ---
	SELECT CAST(AVG(ISNULL(Percentage,0)) as decimal(18,2)) 'OverAllPercentage' FROM #temp_ReportSetupWisePercentage
	---- END Table 1 - Over-all Percentage ---

	---- START Table 2 - Section Details ---
	SELECT * FROM #temp_ReportSetupWisePercentage
	---- END Table 2 - Section Details ---

	---- START Table 3 - Question Details ---
	SELECT * FROM #temp_HealthSurveyAnalysisDetail ORDER By ReportSetupID,QuestionId
	---- END Table 3 - Question Details ---

	---- START Table 4 - Survey name and Employee Details ---
	SELECT @SurvayName 'SurvayName', (SELECT TOP(1) ISNULL(FirstName,'') + ' ' + ISNULL(LastName,'') FROM sHrm.tEmployeeMaster WHERE OrgID = @rOrgId AND Id = @rEmployeeId) 'EmployeeName'
	---- END Table 4 - Survey name AND Employee Details ---

	---- START Table 5 - Health Indicator Details ---
	SELECT * FROM #temp_tHealthSetupIndicator
	---- START Table 5 - Health Indicator Details  ---

	IF OBJECT_ID('tempdb..#temp_ReportSetupWisePercentage') IS NOT NULL
	BEGIN
		DROP TABLE #temp_ReportSetupWisePercentage
	END

	IF OBJECT_ID('tempdb..#temp_HealthSurveyAnalysisDetail') IS NOT NULL
	BEGIN
		DROP TABLE #temp_HealthSurveyAnalysisDetail
	END

	IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
	BEGIN
		DROP TABLE #temp_ReportSetup
	END

	IF OBJECT_ID('tempdb..#temp_tHealthSetupIndicator') IS NOT NULL
	BEGIN
		   DROP TABLE #temp_tHealthSetupIndicator
	END
END
GO
PRINT N'Altering Procedure [sSupport].[pHealthSurveySetupIndicatorListGet]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pHealthSurveySetupIndicatorListGet]
	@rOrgId smallint,	
	@rHealthSurveyId int
as
begin
	declare @lIndicatorRange varchar(max)=''
	if(exists(select 1 from sSupport.tHealthSetupIndicator where OrgId=@rOrgId and HealthSurveyId=@rHealthSurveyId))
		begin
			select @lIndicatorRange = @lIndicatorRange + '<tr attrId="'+convert(varchar,Id)+'" attrHealthSurveyId="'+convert(varchar,HealthSurveyId)+'" attrCode="' + Code + '" attrTitle="' + Title + '"><td>' + Title + '</td>
			<td><input type="text" class="healthindicatorlabel" value="' + convert(varchar,isnull(HealthIndicatorLabel,''))+'"/></td>
			<td><input type="text" class="minrange" value="' + convert(varchar,isnull(RangeFrom,0)) + '"
			onkeypress="return isNumberAudio(event);" onblur="CheckUpper(this);" /></td>
			<td><input type="text" class="maxrange" value="' + convert(varchar,isnull(RangeTo,0)) + '" onkeypress="return isNumberAudio(event);" onblur="CheckValue(this);" /></td>
			<td><input type="checkbox" class="ed" ' + case when isnull(IsObsolete,0) = 0 then 'checked="checked"' else '' end + ' /></td>
			<td><input type="text" class="form-control clsEntityColorCode spectrum with-add-on" value="' + convert(varchar,isnull(ColorCode,''))+'"/></td></tr>'
			from sSupport.tHealthSetupIndicator where OrgId=@rOrgId and HealthSurveyId=@rHealthSurveyId
		end
	else
		begin
			select @lIndicatorRange = @lIndicatorRange + '<tr attrId="'+convert(varchar,Id)+'" attrCode="' + Code + '" attrTitle="' + Title + '"><td>' + Title + '</td>
			<td><input type="text" class="healthindicatorlabel" value="' + convert(varchar,isnull(HealthIndicatorLabel,''))+'"/></td>
			<td><input type="text" class="minrange" value="' + convert(varchar,isnull(RangeFrom,0)) + '"
			onkeypress="return isNumberAudio(event);" onblur="CheckUpper(this);" /></td>
			<td><input type="text" class="maxrange" value="' + convert(varchar,isnull(RangeTo,0)) + '" onkeypress="return isNumberAudio(event);"  onblur="CheckValue(this);" /></td>
			<td><input type="checkbox" class="ed" ' + case when isnull(IsObsolete,0) = 0 then 'checked="checked"' else '' end + ' /></td>
			<td><input type="text" class="form-control clsEntityColorCode spectrum with-add-on" value="' + convert(varchar,isnull(ColorCode,''))+'"/></td></tr>'
			from sSupport.tHealthSetupIndicator where OrgId=1 and HealthSurveyId=0
		end
	
	select @lIndicatorRange as IndicatorRange
end
GO
PRINT N'Altering Procedure [sSupport].[pMobHealthSurveyAnalysisGeneratePivotReport]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pMobHealthSurveyAnalysisGeneratePivotReport]
(
	@rOrgId smallint,
	@rAssignSurveyId int,
	@rEmployeeCode nvarchar(100) = '',
	@rEmployeeName nvarchar(200) = '',
	@rDepartmentId int = 0
 )
AS
SET NOCOUNT ON
BEGIN	
	IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
	BEGIN
		   DROP TABLE #temp_ReportSetup
	END

	--IF OBJECT_ID('tempdb..#temp_EmployeeIDs') IS NOT NULL
	--BEGIN
	--	   DROP TABLE #temp_EmployeeIDs
	--END
	
	--CREATE TABLE #temp_EmployerDetails
	--(
	--	SectionTitle NVARCHAR(MAX),
	--	Question NVARCHAR(MAX),
	--	Answer NVARCHAR(MAX),
	--	EarnedPoint decimal(18,2),
	--	TotalPoint decimal(18,2),
	--	Percentage decimal(18,2)
	--)

	DECLARE @healthSurveyId INT  
	SELECT @healthSurveyId=ASM.HealthSurveyId FROM sSupport.tAssignSurveyMaster ASM WHERE ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId   

	SELECT
		Id 'ReportSetupID',
		SectionTitle,
		ParameterMasterIds
		INTO #temp_ReportSetup 
	FROM sSupport.tSurveyReportSetupMaster WHERE TemplateId = @healthSurveyId AND OrgId = @rOrgId


	--CREATE TABLE #temp_EmployeeIDs 
	--(
	--	EmployeeId bigint
	--)

	--DECLARE @isSeachWithEmployee BIT = 0
	--IF ISNULL(@rEmployeeCode,'') != '' OR ISNULL(@rEmployeeName,'') != '' OR ISNULL(@rDepartmentId,0) != 0
	--BEGIN
	--	SET @isSeachWithEmployee = 1

	--	INSERT INTO #temp_EmployeeIDs
	--	SELECT DISTINCT
	--	   EmployeeId 
	--	FROM sHrm.vEmployeeCustomSearch ECS 
	--	WHERE OrgId = @rOrgId 
	--		  AND  (ECS.Code like '%'+@rEmployeeCode+'%' or isnull(@rEmployeeCode,'')='')
	--		  AND (ECS.Name like '%'+@rEmployeeName+'%' or isnull(@rEmployeeName,'')='')
	--		  AND (ECS.OrganizationDepartmentId=@rDepartmentId or isnull(@rDepartmentId,0)=0)
	--END
	

	 
	SELECT 
		DENSE_RANK() OVER(ORDER BY ReportSetupID ASC) 'ID',
		SectionTitle,
		Question,
		EarnedPoint,
		TotalPoint,
		CAST(ROUND(Percentage,0) as bigint) 'Percentage',
		IndicatorName,
		EmployeeName,
		QuestionType
	FROM
	(SELECT 
		trs.ReportSetupID,
		trs.SectionTitle,
		HSPM.Id 'QuestionID',
		HSPM.Title as Question,
		--HSRD.Answer as Answer,
		ISNULL(HSRD.EarnedPoints,0) as EarnedPoint,
		HSRD.TotalPoints as TotalPoint,
		(CASE WHEN HSRD.TotalPoints != 0 THEN (ISNULL(HSRD.EarnedPoints,0)*100)/HSRD.TotalPoints ELSE 0 END) as Percentage,
		ISNULL(ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title),'') 'IndicatorName',
		ISNULL(ECS.Name,'') 'EmployeeName',
		ISNULL(HSPG.Title,'') 'QuestionType'
	FROM  sSupport.tHealthSurveyResponseMaster HSRM 
	INNER JOIN sHrm.vEmployeeCustomSearch ECS on ECS.EmployeeId = HSRM.SourceId
	INNER JOIN sSupport.tHealthSurveyResponseDetail HSRD on HSRM.Id=HSRD.SurveyResponseId
	INNER JOIN sSupport.tHealthSurveyParameterMaster HSPM on HSPM.Id=HSRD.QuestionId
	INNER JOIN sSupport.tHealthSurveyParameterGroupMaster HSPG ON HSPG.Id = HSPM.GroupId
	INNER JOIN sSupport.tHealthSetupIndicator HSI on HSI.HealthSurveyId = HSPM.HealthSurveyId AND  (case when HSRD.TotalPoints != 0 then (HSRD.EarnedPoints*100)/HSRD.TotalPoints else 0 end) between HSI.RangeFrom and HSI.RangeTo
	INNER JOIN #temp_ReportSetup trs on EXISTS(SELECT 1 FROM sCommon.fnsplit(trs.ParameterMasterIds,',') WHERE CAST(item as int) = HSPM.Id)
	WHERE HSRM.AssignSurveyId=@rAssignSurveyId and HSRM.OrgId=@rOrgId AND HSRM.StatusId=554 AND HSI.HealthSurveyId=@healthSurveyId AND HSPM.HealthSurveyAnsTypeId != 4 
	      AND  (ECS.Code like '%'+@rEmployeeCode+'%' or isnull(@rEmployeeCode,'')='')
		  AND (ECS.Name like '%'+@rEmployeeName+'%' or isnull(@rEmployeeName,'')='')
		  AND (ECS.OrganizationDepartmentId=@rDepartmentId or isnull(@rDepartmentId,0)=0)
	--GROUP By trs.ReportSetupID,trs.SectionTitle,HSPM.Id,HSPM.Title,ISNULL(HSI.Title,'')
	)tbl

	 
	IF OBJECT_ID('tempdb..#temp_ReportSetup') IS NOT NULL
	BEGIN
		   DROP TABLE #temp_ReportSetup
	END

	--IF OBJECT_ID('tempdb..#temp_EmployeeIDs') IS NOT NULL
	--BEGIN
	--	   DROP TABLE #temp_EmployeeIDs
	--END

END
GO
PRINT N'Altering Procedure [sSupport].[pMobHealthSurveyAnalysisReport]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pMobHealthSurveyAnalysisReport]
(
	@rOrgId smallint,
	@rAssignSurveyId int,
	@rSourceId bigint
 )
AS
SET NOCOUNT ON
BEGIN	
	declare @tblHealthSurveyAnalysis table(id int identity(1,1),t_Question nvarchar(150),t_Answer nvarchar(max)
	,t_EarnedPoint decimal(18,2),t_TotalPoint decimal(18,2),t_Percentage decimal(18,2),t_Remark nvarchar(1000))
	insert into @tblHealthSurveyAnalysis select HSPM.Title as Question,HSRD.Answer as Answer,HSRD.EarnedPoints as EarnedPoint,HSRD.TotalPoints as TotalPoint,case when HSRD.TotalPoints != 0 then (HSRD.EarnedPoints*100)/HSRD.TotalPoints else 0 end as Percentage,HSRD.Remark from  sSupport.tHealthSurveyResponseMaster HSRM 
	inner join sSupport.tHealthSurveyResponseDetail HSRD on HSRM.Id=HSRD.SurveyResponseId
	inner join sSupport.tHealthSurveyParameterMaster HSPM on HSPM.Id=HSRD.QuestionId
	where HSRM.AssignSurveyId=@rAssignSurveyId and HSRM.SourceId=@rSourceId and HSRM.OrgId=@rOrgId
	order by HSPM.Id asc
	select tmptbl.id as Id,tmptbl.t_Question as Question,tmptbl.t_Answer as Answer,tmptbl.t_EarnedPoint as EarnedPoint,tmptbl.t_TotalPoint as TotalPoint
	,tmptbl.t_Percentage as Percentage,case when tmptbl.t_TotalPoint != 0 then ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) else '' end as RiskTitle,isnull(t_Remark,'')as Remark  from @tblHealthSurveyAnalysis tmptbl 
					inner join sSupport.tHealthSetupIndicator HSI on tmptbl.t_Percentage>=HSI.RangeFrom and tmptbl.t_Percentage<=HSI.RangeTo
					inner join sSupport.tAssignSurveyMaster ASM on ASM.HealthSurveyId=HSI.HealthSurveyId
					inner join sSupport.tHealthSurveyResponseMaster HSRM on HSRM.AssignSurveyId=ASM.Id
					where HSRM.AssignSurveyId=@rAssignSurveyId and HSRM.SourceId=@rSourceId
					order by tmptbl.id asc
END
GO
PRINT N'Altering Procedure [sSupport].[pMobHealthSurveyReportGet]...';


GO

CREATE OR ALTER PROCEDURE [sSupport].[pMobHealthSurveyReportGet]
(
	@rOrgId smallint,
	@rAssignSurveyId int,
	@rSourceId bigint
	
 )
AS
SET NOCOUNT ON
BEGIN	
declare @t_totalEarnedPoint decimal(18,2)
declare @t_TotalPoint decimal(18,2)
declare @tblHealthSurveyReport table(Id int identity(1,1),t_HealthTitle nvarchar(100),t_EarnedPoint decimal(18,2),t_TotalPoint decimal(18,2),t_EarnedPercentage decimal(18,2))

	IF exists(select 1 from sSupport.tAssignSurveyMaster ASM where OrgId=@rOrgId and ASM.Id=@rAssignSurveyId and ASM.IsShowMarksDetails=1)
		begin

			insert into @tblHealthSurveyReport select HSPGM.Title as HealthTitle,sum(HSRD.EarnedPoints) as EarnedPoint,sum(HSRD.TotalPoints) as TotalPoint,(sum(HSRD.EarnedPoints)*100)/sum(HSRD.TotalPoints) as t_EarnedPercentage
			from sSupport.tHealthSurveyResponseMaster HSRM
			inner join sSupport.tHealthSurveyResponseDetail HSRD on HSRM.Id=HSRD.SurveyResponseId
			inner join sSupport.tHealthSurveyParameterMaster HSPM on HSPM.Id=HSRD.QuestionId
			inner join sSupport.tHealthSurveyParameterGroupMaster HSPGM on HSPGM.Id=HSPM.GroupId
			---new added
			inner join sSupport.tAssignSurveyMaster ASM on ASM.Id=HSRM.AssignSurveyId
			where ASM.IsShowMarksDetails=1 and HSRM.SourceId=@rSourceId and  HSRM.OrgId=@rOrgId and HSRM.AssignSurveyId=@rAssignSurveyId and HSRD.TotalPoints != 0
			group by HSPGM.Title

			select @t_totalEarnedPoint=sum(t_EarnedPoint),@t_TotalPoint=sum(t_TotalPoint) from @tblHealthSurveyReport

			select @t_totalEarnedPoint as TotalEarnedPoint,@t_TotalPoint as TotalPoint,ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) as RiskTitle,HSI.ColorCode AS RiskColorCode,IsShowRecommendation,IsShowMarksDetails  from 
			 sSupport.tHealthSetupIndicator HSI 
				inner join sSupport.tAssignSurveyMaster ASM on ASM.HealthSurveyId=HSI.HealthSurveyId			   
				 where ASM.Id=@rAssignSurveyId and ((@t_totalEarnedPoint*100)/@t_TotalPoint)>=HSI.RangeFrom and ((@t_totalEarnedPoint*100)/@t_TotalPoint)<=HSI.RangeTo
				select t_HealthTitle as HealthTitle,t_EarnedPoint as EarnedPoint,t_TotalPoint as TotalPoint,ISNULL(NULLIF(LTRIM(RTRIM(HSI.HealthIndicatorLabel)), ''), HSI.Title) as RiskTitle,HSI.ColorCode AS RiskColorCode from @tblHealthSurveyReport temptbl 
				inner join sSupport.tHealthSetupIndicator HSI on temptbl.t_EarnedPercentage>=HSI.RangeFrom and temptbl.t_EarnedPercentage<=HSI.RangeTo
				inner join sSupport.tAssignSurveyMaster ASM on ASM.HealthSurveyId=HSI.HealthSurveyId			   
				 where ASM.Id=@rAssignSurveyId
				 --where HSI.HealthSurveyId=@rAssignSurveyId
		end
	ELSE
		begin
		select -102 as StatusCode,'You are not authorized to view result' as StatusMessage
		end		
END
GO
PRINT N'Altering Procedure [sWellness].[pGetProgramMasterEmployeeList]...';


GO
CREATE OR ALTER PROCEDURE[sWellness].[pGetProgramMasterEmployeeList]
(
    @rId BIGINT,
    @rProgramName NVARCHAR(10),
    @rFromDate DATETIME = null,
    @rToDate DATETIME = null,
	@rLocationId BIGINT = 0,
	@rIsRegistrationRequired BIT = 0,
	@rEmployeeId BIGINT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		P.Id,
        Title,
		ModeId,
        Description AS ProgramDescription,
        FromDate AS FromDate,
		ToDate AS ToDate,
		RegisterUptoDatetime,
		IsRegistrationRequired,
		IsSurveyRequired,
		AssignSurveyId,
		[sWellness].[fn_IsEmployeeRegistered](P.Id,@rEmployeeId) AS RegistrationStatus,
		FromTime,
		ToTime
    FROM 
		[sWellness].[tProgramMaster] P
	INNER JOIN
		[sWellness].[tProgramLocation] PL
	ON	
		P.Id = PL.ProgramId
    WHERE 
		P.IsObsolete = 0
	AND
		(ISNULL(P.Id, 0) = @rId OR ISNULL(@rId, 0) = 0)
	AND
		(ISNULL(P.IsRegistrationRequired, 0) = @rIsRegistrationRequired OR ISNULL(@rIsRegistrationRequired, 0) = 0)
    AND 
		(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
    AND 
		OrgId = @rOrgId
    AND 
		((Title LIKE (@rProgramName + '%')) OR ISNULL(@rProgramName, '') = '')
    AND 
		((FromDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
    AND 
		((FromDate <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
	ORDER BY 
		RegistrationStatus
END
GO
PRINT N'Altering Procedure [sWellness].[pAddOrUpdatePrograms]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdatePrograms]
(
    @rId BIGINT,
    @rOrgId SMALLINT,
    @rTitle NVARCHAR(100),
    @rModeId TINYINT,
    @rDescription NVARCHAR(500),
    @rFromDate DATETIME,
    @rToDate DATETIME,
    @rFromTime TIME(7),
    @rToTime TIME(7),
	@rCategoryId SMALLINT,
	@rMHIIndicatorId INT,
    @rIsSurveyRequired BIT,
    @rAssignedSurveyId INT,
    @rProgramSubTypeId INT,
    @rIsRegistrationRequired BIT,
    @rRegisterUptoDateTime DATETIME,
    @rIsObsolete BIT,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @lNextNumber BIGINT = 0;

    IF EXISTS
    (
        SELECT 
			1
        FROM 
			[sWellness].[tProgramMaster]
        WHERE
			Id <> @rId 
		AND 
			Title = @rTitle 
		AND 
			OrgId = @rOrgId
    )
    BEGIN
        SELECT CAST(-102 AS NVARCHAR(10)) AS Result
        RETURN
    END

	IF(@rIsObsolete = 1)
	BEGIN
		IF EXISTS(SELECT Id FROM [sWellness].[tMHIScore] WHERE ProgramId = @rId AND OrgId = @rOrgId)
		BEGIN
			SELECT -104 AS Result -- Cannot inactive parent type without making inactive sub type
			RETURN
		END
		IF EXISTS(SELECT Id FROM [sWellness].[tMHIScore_History] WHERE ProgramId = @rId AND OrgId = @rOrgId)
		BEGIN
			SELECT -104 AS Result -- Cannot inactive parent type without making inactive sub type
			RETURN
		END
	END

    BEGIN TRY
        BEGIN TRANSACTION

        IF (@rId = 0)
        BEGIN
            EXEC sCommon.pTableRowIdGet 
                @rOrgId,
                'sWellness.tProgramMaster',
                0,1,1,
                @outNextNumber = @lNextNumber OUTPUT

            INSERT INTO [sWellness].[tProgramMaster]
            (
                Id, OrgId, Title, ModeId, Description, 
				FromDate, ToDate,FromTime, ToTime,CategoryId,MHIIndicatorId, 
				IsSurveyRequired, AssignSurveyId, ProgramSubTypeId,
                IsRegistrationRequired, RegisterUptoDatetime, IsObsolete,
                CreatedUserId, CreatedDatetime
            )
            VALUES
            (   
                @lNextNumber, @rOrgId, @rTitle, @rModeId, @rDescription,
                @rFromDate, @rToDate, @rFromTime, @rToTime, @rCategoryId,@rMHIIndicatorId,
                @rIsSurveyRequired, @rAssignedSurveyId, @rProgramSubTypeId,
                @rIsRegistrationRequired, @rRegisterUptoDateTime,
                @rIsObsolete, @rUserId, sCommon.fGetDate()
            )
        END
        ELSE
        BEGIN
            UPDATE [sWellness].[tProgramMaster]
            SET
                Title = @rTitle,
                ModeId = @rModeId,
                Description = @rDescription,
                FromDate = @rFromDate,
                ToDate = @rToDate,
                FromTime = @rFromTime,
                ToTime = @rToTime,
				CategoryId = @rCategoryId,
				MHIIndicatorId = @rMHIIndicatorId,
                IsSurveyRequired = @rIsSurveyRequired,
                AssignSurveyId = @rAssignedSurveyId,
                ProgramSubTypeId = @rProgramSubTypeId,
                IsRegistrationRequired = @rIsRegistrationRequired,
                RegisterUptoDatetime = @rRegisterUptoDateTime,
                IsObsolete = @rIsObsolete,
                UpdatedUserId = @rUserId,
                UpdatedDatetime = sCommon.fGetDate()
            WHERE Id = @rId
            AND OrgId = @rOrgId;

            SET @lNextNumber = @rId;
        END

        COMMIT TRANSACTION

        SELECT CAST(@lNextNumber AS NVARCHAR(10)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO
PRINT N'Altering Procedure [sWellness].[pGetAllDetailForProgramMaster]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetAllDetailForProgramMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT 
		 PM.Id
		,PM.OrgId
		,PM.Title
		,PM.ModeId
		,PM.Description
		,PM.FromDate
		,PM.ToDate
		,PM.FromTime
		,PM.ToTime
		,PM.CategoryId AS ProgramCategoryId
		,PM.MHIIndicatorId AS MHIIndicatorId
		,PM.IsSurveyRequired
		,PM.AssignSurveyId
		,PSTM.ProgramTypeMasterId AS ProgramTypeId
		,PM.ProgramSubTypeId
		,PM.IsRegistrationRequired
		,PM.RegisterUptoDatetime
		,PM.IsObsolete
	FROM
		[sWellness].[tProgramMaster] PM
	INNER JOIN
		[sWellness].[tProgramSubTypeMaster] PSTM
	ON
		PSTM.Id = PM.ProgramSubTypeId
	WHERE
		PM.OrgId = @rOrgId
	AND
		PM.Id = @rId


	SELECT
		LM.Title AS Text,
		LocationId AS Value
	FROM
		sWellness.tProgramLocation PL
	INNER JOIN
		sCommon.tLocationMaster LM
	ON
		LM.Id = PL.LocationId
	WHERE
		PL.ProgramId = @rId

	SELECT
		EM.FirstName + ' ' + EM.LastName AS Text,
		DoctorEmployeeId AS Value
	FROM
		sWellness.tProgramCoach PC
	INNER JOIN
		sCwb.tDoctorMaster DM
	ON
		DM.Id = PC.DoctorEmployeeId 
	INNER JOIN
		sHrm.tEmployeeMaster EM
	ON
		EM.Id = DM.EmployeeId
	WHERE
		PC.ProgramId = @rId

	--SELECT
	--	Id,
	--	FieldTitle,
	--	FieldRemark,
	--	FieldTypeId,
	--	FieldList,
	--	IsMandatory,
	--	FieldOrderIndex
	--FROM
	--	[sWellness].[tProgramCustomField] PCF
	--WHERE
	--	PCF.ProgramId = @rId
END
GO
PRINT N'Altering Procedure [sWellness].[pGetProgramMasterCoachList]...';


GO
CREATE OR ALTER PROCEDURE[sWellness].[pGetProgramMasterCoachList]
(
    @rId BIGINT,
    @rProgramName NVARCHAR(10),
    @rFromDate DATETIME = null,
    @rToDate DATETIME = null,
	@rLocationId BIGINT = 0,
	@rIsSurveyRequired BIT = 0,
	@rEmployeeId BIGINT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		P.Id,
        Title,
		ModeId,
        Description AS ProgramDescription,
        FromDate AS FromDate,
		ToDate AS ToDate,
		RegisterUptoDatetime,
		IsSurveyRequired,
		IsRegistrationRequired,
		AssignSurveyId,
		FromTime,
		ToTime
    FROM 
		[sWellness].[tProgramMaster] P
	INNER JOIN
		[sWellness].[tProgramCoach] PC
	ON	
		P.Id = P.Id
	INNER JOIN
		[sCwb].[tDoctorMaster] DM
	ON
		DM.Id = PC.DoctorEmployeeId 
    WHERE 
		P.IsObsolete = 0
	AND
		(ISNULL(P.Id, 0) = @rId OR ISNULL(@rId, 0) = 0)
	AND
		(ISNULL(P.IsSurveyRequired, 0) = @rIsSurveyRequired OR ISNULL(@rIsSurveyRequired, 0) = 0)
  --AND 
		--(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
	AND
		DM.EmployeeId = @rEmployeeId
    AND 
		P.OrgId = @rOrgId
    AND 
		((Title LIKE (@rProgramName + '%')) OR ISNULL(@rProgramName, '') = '')
    AND 
		((FromDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
    AND 
		((FromDate <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
	ORDER BY 
		Id
	DESC
END
GO
PRINT N'Altering Procedure [sWellness].[pGetPrograms]...';


GO
CREATE OR ALTER PROCEDURE[sWellness].[pGetPrograms]
(
    @rId BIGINT,
    @rProgramName NVARCHAR(10),
    @rFromDate DATETIME = null,
    @rToDate DATETIME = null,
	@rLocationId BIGINT = 0,
	@rIsRegistrationRequired BIT = 0,
	@rScreenFlagId SMALLINT = 0,
	@rEmployeeId BIGINT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		P.Id,
        Title,
		ModeId,
        Description,
        FromDate AS FromDate,
		ToDate AS ToDate,
		RegisterUptoDatetime,
		IsRegistrationRequired,
		FromTime,
		ToTime,
		IsObsolete
    FROM 
		[sWellness].[tProgramMaster] P
	LEFT JOIN
		[sWellness].[tProgramLocation] PL
	ON	
		P.Id = PL.ProgramId
    WHERE 
		(ISNULL(P.Id, 0) = @rId OR ISNULL(@rId, 0) = 0)
	AND
		(ISNULL(P.IsRegistrationRequired, 0) = @rIsRegistrationRequired OR ISNULL(@rIsRegistrationRequired, 0) = 0)
  --  AND 
		--(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
    AND 
		OrgId = @rOrgId
    AND 
		((Title LIKE (@rProgramName + '%')) OR ISNULL(@rProgramName, '') = '')
    AND 
		((FromDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
    AND 
		((FromDate <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
	ORDER BY 
		Id
	DESC
END
GO
PRINT N'Altering Procedure [sWellness].[pWellnessAppointmentListGetScheduling]...';


GO


CREATE OR ALTER PROCEDURE [sWellness].[pWellnessAppointmentListGetScheduling]      
    @rOrgId INT,
    @rId BIGINT = 0,      
    @rFromDate DATETIME,      
    @rToDate DATETIME,      
    @rEmployeeCode NVARCHAR(20) = '',      
    @rPatientName NVARCHAR(500) = '',      
    @rStoreLocationId INT = 0,      
    @rLocationId INT = 0,      
    @rSetupId INT = 0,      
    @rDoctorEmployeeId BIGINT = 0,      
    @rEmployeeStoreLocationId INT = 0,  
    @rAppointmentFlag NVARCHAR(500) = ''
AS      
BEGIN    
    SET @rEmployeeCode = CASE     
        WHEN CHARINDEX('*', @rEmployeeCode) > 0    
            THEN REPLACE(@rEmployeeCode, '*', '%')    
        ELSE '%' + @rEmployeeCode + '%'    
    END;    
    
    SELECT     
        A.Id,    
        A.AppointmentNumber,    
        A.PatientSourceTypeId,    
        A.PatientSourceId,    
        A.PatientName,    
        A.AppointmentDate,    
        ISNULL(A.FromTime, CONVERT(DATETIME, A.AppointmentDate)) AS FromTime,    
        ISNULL(A.ToTime, CONVERT(DATETIME, A.AppointmentDate)) AS ToTime,    
        ISNULL(A.DoctorEmployeeId, 0) AS DoctorEmployeeId,    
        A.EmployeeCode,    
        A.EmployeeId,    
        REPLACE(A.Relation, 'Ohter', 'Other') AS Relation,    
        A.Gender,    
        A.DoctorName,    
        A.OrgId,    
        A.IsRegister,    
        A.IsObsolete,    
        A.StatusName,    
        A.DepartmentName,    
        ISNULL(A.DepartmentId, 0) AS DepartmentId,    
        A.DependentId,    
        A.StoreLocationId,    
        A.SetupId,    
        A.ExaminationTypeId,    
        A.MainType,    
        A.Setup,    
        A.ReferSourceId,    
        A.LocationId,    
        ISNULL(A.CauseId, -1) AS CauseId,    
        A.StoreLocation,    
        ISNULL(A.OtherName, '') AS OtherName,    
        ISNULL(A.FollowupRemark, '') AS FollowupRemark,    
        A.Age,    
        A.Months,    
        A.GenderId,    
        A.ExaminationId,    
        A.Timeslot,
		ISNULL(A.CompliantRemark, '') AS CompliantRemark,
		A.AppointmentFlag
    FROM     
        [sWellness].[vExtPatientWellnessAppointmentDetail] A  
    LEFT JOIN 
        sWellness.tWellnessConsultation E ON A.ExaminationId = E.Id    
        OR A.ReferSourceId = E.Id
    WHERE     
        A.ApprovalStatusId = 548    
        AND A.AppointmentDate BETWEEN ISNULL(@rFromDate, sCommon.fGetDate()) AND ISNULL(@rToDate, sCommon.fGetDate())    
        AND (A.Id = @rId OR @rId = 0)    
        AND A.OrgId = @rOrgId    
        AND (A.PatientName LIKE @rPatientName + '%' OR A.OtherName LIKE @rPatientName + '%' OR ISNULL(@rPatientName, '') = '')    
        AND (A.EmployeeCode LIKE @rEmployeeCode OR ISNULL(@rEmployeeCode, '') = '')    
        AND (A.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)    
        AND (A.LocationId = @rLocationId OR @rLocationId = 0)    
        AND (A.SetupId = @rSetupId OR @rSetupId = 0)    
        AND (A.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0)    
        AND (A.AppointmentFlag = @rAppointmentFlag OR @rAppointmentFlag = '0')    
        --AND ISNULL(A.ExaminationId, 0) = 0   
        AND ISNULL(E.IsCancel, 0) = 0  
		--AND A.Id NOT IN (SELECT IsNull(AppointmentId,0) FROM [sWellness].[tWellnessRegistration] WHERE OrgId =@rOrgId);
END
GO
PRINT N'Altering Procedure [dbo].[prc_getAzureDocuments_newsearch_Ng]...';


GO
 
CREATE OR ALTER PROCEDURE [dbo].[prc_getAzureDocuments_newsearch_Ng]  
@maintypeid int,  
@setupid int,  
@code varchar(300),  
@Name Varchar(300) = '',  
@orgid int,  
@readpermission bit = null,  
@deletepermission bit = null,  
@DocName varchar(300) = null,  
@StoreLocationId int = null,  
@ruserid bigint=0  
as  
begin  
 declare @empid bigint,@lTotRec int  
 select @empid = Id from sHrm.tEmployeeMaster where Code = @code  
 if @code = ''  
 begin  
  select @empid = 0  
 end   
 select @empid = isnull(@empid,0)  
  
 declare @lConfValue varchar(20)='False'  
 select @lConfValue = Isnull(CS.ItemValue,CM.ItemValue)   
 from sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id   
 where CM.ItemKey = 'Examination.IsDocumentLoadUserLocationWise'  
  
   
 declare @tbltmpHistory table(tid int identity(1,1),hid int)
 declare @tbltmpConsultation table(tid int identity(1,1),hid int)
   
 declare @res varchar(max)=''  
   
 --insert into @tbltmpHistory  
 --select HD.Id from tbl_azurehistorydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 --inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 --inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 --where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 --and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid        
 --and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)    
 --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
 --order by EM.Code  
   
 if(@lConfValue='True')  
 begin  
   if(@empid>0)  
   begin  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_azurehistorydata HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    --inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
    INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON  
    SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EJD.EmployeeLocationId  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    and (HD.employeeid = @empid ) and EM.OrgID = @orgid    
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    --and UL.UserId=@rUserId  
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    --and E.StorelocationId = @StoreLocationId  
    --order by EM.Code 
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002 
    
     insert into @tbltmpHistory  
     select distinct HD.Id from tbl_azurehistorydata HD 
     inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
	 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
	 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
	 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
	 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)  

	 insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end  
   else   
   begin  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_azurehistorydata HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    --inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
    INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON  
    SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EJD.EmployeeLocationId  
  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
    and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))      
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)   
    --and UL.UserId=@rUserId  
    --order by EM.Code  
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002
    
    insert into @tbltmpHistory  
     select distinct HD.Id from tbl_azurehistorydata HD 
     inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
	 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
	 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
	 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
	 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)  

	 insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end  
 end    
 else   
 begin  
   if(@empid>0)  
   begin  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_azurehistorydata HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    and (HD.employeeid = @empid ) and EM.OrgID = @orgid    
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    and UL.UserId=@rUserId  
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    --and E.StorelocationId = @StoreLocationId  
    --order by EM.Code  
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002
    
    insert into @tbltmpHistory  
     select distinct HD.Id from tbl_azurehistorydata HD 
     inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
	 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
	 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
	 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
	 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)

	 insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end  
   else   
   begin  
    print 'test'  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_azurehistorydata HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    --and (HD.employeeid = @empid or @empid = 0)   
    and EM.OrgID = @orgid  
    and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))      
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)   
    and UL.UserId=@rUserId  
    --order by EM.Code  
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002
    
    insert into @tbltmpHistory  
     select distinct HD.Id from tbl_azurehistorydata HD 
     inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
	 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
	 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
	 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
	 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)  

	 insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end  
 end  
  
 select @lTotRec = count(*) from @tbltmpHistory  
   
 select * from (
 select HD.Id,HD.MainTypeId,MT.Title as MainType, SM.Title as SetupMaster , Code , isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName, name as FileName, 
 SM.Id as SetupMasterId ,isnull(hd.OpdId,0)as OpdId, 0 as ConfigId  --mantis id: 46943; yogesh; Dt- 07/11/2025
 from tbl_azurehistorydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory  
 where hid = HD.Id 
 --order by HD.Id desc
  UNION ALL
 select HD.Id,STM.MainTypeId,MT.Title as MainType,SM.Title as SetupMaster, Code ,isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName,FileName,
	SM.Id as SetupMasterId,isnull(hd.ConsultationId,0) as ConsultationId, HD.ConfigId     
 from sWellness.tConsultationDocuments HD
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id,@tbltmpConsultation      
 where hid = HD.Id
 ) t
 order by t.Id desc
 --order by tid  
   
 --if @permission >= 8  
 --begin  
 -- insert into @tbltmpHistory  
 -- select HD.Id from tbl_azurehistorydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 -- where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 -- and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid        
 -- and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)    
 -- and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
 -- order by EM.Code  
    
 -- select @lTotRec = count(*) from @tbltmpHistory  
    
 -- select @res = @res + '<tr><td>' + MT.Title + '</td><td>' + SM.Title + '</td><td>' + Code + '</td>  
 -- <td>' + isnull(FirstName,'') + ' ' + isnull(LastName,'') + '</td><td>' + name + '</td>  
 -- <td><a onclick="ViewAzure(this);" style="cursor:pointer;"  
 -- attrMTitle="'+ MT.Title +'"  
 -- attrSId="' + convert(varchar,SM.Id) + '"  
 -- attrCode="' + Code + '"  
 -- attrTitle="' + name + '">View</a>  
 -- <a class="testview" target="_blank" href="javascript:;" style="display:none;">View</a>  
 -- &nbsp;&nbsp;<a attrMTitle="'+ MT.Title +'"  
 -- attrSId="' + convert(varchar,SM.Id) + '"  
 -- attrCode="' + Code + '"  
 -- attrTitle="' + name + '" onclick="DownloadAzure(this);" style="cursor:pointer;">Download</a>  
 -- &nbsp;&nbsp;<a href="javascript:;" onclick="deletethis(' + convert(varchar,HD.Id) + ')">Delete</a></td></tr>'  
 -- from tbl_azurehistorydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory  
 -- where hid = HD.Id order by tid  
 --end    
 --else  
 --begin  
 -- insert into @tbltmpHistory  
 -- select HD.Id from tbl_azurehistorydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 -- where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 -- and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid    
 -- and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)    
 -- and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
 -- order by EM.Code  
    
 -- select @lTotRec = count(*) from @tbltmpHistory  
    
 -- select @res = @res + '<tr><td>' + MT.Title + '</td><td>' + SM.Title + '</td><td>' + Code + '</td>  
 -- <td>' + isnull(FirstName,'') + ' ' + isnull(LastName,'') + '</td><td>' + name + '</td>  
 -- <td><a onclick="ViewAzure(this);" style="cursor:pointer;"  
 -- attrMTitle="'+ MT.Title +'"  
 -- attrSId="' + convert(varchar,SM.Id) + '"  
 -- attrCode="' + Code + '"  
 -- attrTitle="' + name + '">View</a>  
 -- <a class="testview" target="_blank" href="javascript:;" style="display:none;">View</a>  
 -- &nbsp;&nbsp;<a attrMTitle="'+ MT.Title +'"  
 -- attrSId="' + convert(varchar,SM.Id) + '"  
 -- attrCode="' + Code + '"  
 -- attrTitle="' + name + '" onclick="DownloadAzure(this);" style="cursor:pointer;">Download</a></td></tr>'  
 -- from tbl_azurehistorydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory  
 -- where HD.Id = hid order by tid  
 --end  
 --select @res as res,@lTotRec as TotRec  
end
GO
PRINT N'Altering Procedure [dbo].[prc_getDocuments_newsearch_Ng]...';


GO
  
CREATE OR ALTER PROCEDURE [dbo].[prc_getDocuments_newsearch_Ng]      
@maintypeid int,      
@setupid int,      
@code varchar(300),      
@Name Varchar(300) = '',      
@orgid int,      
@readpermission bit = null,      
@deletepermission bit = null,      
@DocName varchar(300) = null,      
@StoreLocationId int = null,      
@ruserid bigint=0      
as      
begin      
 declare @empid bigint,@lTotRec int,@delmessage varchar(100)='''Are you sure to delete this item?'''      
 select @empid = Id from sHrm.tEmployeeMaster where Code = @code      
 if @code = ''      
 begin      
  select @empid = 0      
 end       
 select @empid = isnull(@empid,0)      
 print @empid      
      
 declare @lConfValue varchar(20)='False'      
 select @lConfValue = Isnull(CS.ItemValue,CM.ItemValue)       
 from sConfig.tConfigurationMaster CM      
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id       
 where CM.ItemKey = 'IsExamination.IsDocumentLoadUserLocationWise'      
      
       
 declare @tbltmpHistory table(tid int identity(1,1),hid int)
 declare @tbltmpConsultation table(tid int identity(1,1),hid int)
       
 declare @res varchar(max)=''      
 if(@lConfValue='False')      
 begin      
   if(@empid>0)      
   begin      
    insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD       
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id      
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId      
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId      
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId      
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id       
    --inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id      
    INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON      
    SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EJD.EmployeeLocationId      
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)      
    and (HD.employeeid = @empid ) and EM.OrgID = @orgid        
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)      
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002     
    --and UL.UserId=@rUserId      
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)      
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))      
    --and SLM.Id = @StoreLocationId      
    --and E.StorelocationId = @StoreLocationId      
    --order by EM.Code  
      
    insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)   
 
  insert into @tbltmpConsultation      
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end      
   else       
   begin      
    insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD       
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id      
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId      
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId      
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId      
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id       
    --inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id      
    INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON      
    SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EJD.EmployeeLocationId      
      
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)      
    and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid      
    and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))          
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)      
    and (HD.name like '%' + @DocName + '%' or @DocName = '')      
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)      
    and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))      
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))      
    --and SLM.Id = @StoreLocationId      
    and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)       
    --and UL.UserId=@rUserId      
    --order by EM.Code 
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002      
      
     insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)      

  insert into @tbltmpConsultation      
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end      
 end        
 else       
 begin      
   if(@empid>0)      
   begin      
    insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD       
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id      
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId      
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId      
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId      
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id       
    inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id      
      
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)      
    and (HD.employeeid = @empid ) and EM.OrgID = @orgid        
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)      
    and (HD.name like '%' + @DocName + '%' or @DocName = '')      
    and UL.UserId=@rUserId      
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)      
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))      
    --and SLM.Id = @StoreLocationId      
    --and E.StorelocationId = @StoreLocationId      
    --order by EM.Code 
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002      
      
     insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)      

 insert into @tbltmpConsultation      
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end      
   else       
   begin      
    print 'test'      
    insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD       
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id      
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId      
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId      
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId      
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id       
    inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id      
      
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)      
    --and (HD.employeeid = @empid or @empid = 0)       
    and EM.OrgID = @orgid      
    and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))          
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)      
    and (HD.name like '%' + @DocName + '%' or @DocName = '')      
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)      
    and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))      
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))      
    --and SLM.Id = @StoreLocationId      
    and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)       
    and UL.UserId=@rUserId      
    --order by EM.Code 
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002      
      
     insert into @tbltmpHistory      
    select distinct HD.Id from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)   
 
  insert into @tbltmpConsultation      
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end      
 end      
 --select * from @tbltmpHistory      
      
 select @lTotRec = count(*) from @tbltmpHistory      
 
 select * from (
 select HD.Id,HD.MainTypeId,MT.Title as MainType,SM.Title as SetupMaster, Code ,isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName,name as FileName, CASE 
        WHEN ISNULL(HD.OpdId, 0) > 0 THEN 
            '../../../Content/' + CONVERT(VARCHAR, @orgid) + '/HistoryData/' 
            + MT.Title + '/' + CONVERT(VARCHAR, SM.Id) + '/' 
            + CONVERT(VARCHAR, HD.OpdId) + '/' + name
        ELSE 
            '../../../Content/' + CONVERT(VARCHAR, @orgid) + '/HistoryData/' 
            + MT.Title + '/' + CONVERT(VARCHAR, SM.Id) + '/' 
            + Code + '/' + name
    END AS FilePath,SM.Id as SetupMasterId,isnull(hd.OpdId,0)as OpdId, 0 as ConfigId  --mantis id: 46943; yogesh; Dt- 07/11/2025     
 from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory      
 where hid = HD.Id
 --order by HD.Id desc
 UNION ALL
 select HD.Id,STM.MainTypeId,MT.Title as MainType,SM.Title as SetupMaster, Code ,isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName,FileName,
	'../../../Content/' + convert(varchar,@orgid) + '/WellnessConsultationDocuments/'   
			+ convert(varchar,HD.ConsultationId) + '/' + FileName as FilePath,
	SM.Id as SetupMasterId,isnull(hd.ConsultationId,0) as ConsultationId, HD.ConfigId     
 from sWellness.tConsultationDocuments HD
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id,@tbltmpConsultation      
 where hid = HD.Id
 ) t
 order by t.Id desc
 --order by tid      
    
    
-- UNION ALL    
    
--select  'VaccinationCertificate' as MainType,'VaccinationCertificate' as SetupMaster, EM.Code ,isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'') as FullName,ISNULL(VL.FileName,'') as FileName,'../../../Content/' + convert(varchar,@orgid) + '/Vaccinat
--ionCertificate/' + convert(varchar,VL.ParticipantSourceId) + '/' + VL.FileName as FilePath,0 as SetupMasterId  
--from sSupport.tVaccineLog VL   
--left join sSecurity.tUser UM on UM.Id= VL.ParticipantSourceId     
--inner join sHrm.tEmployeeMaster EM on VL.ParticipantSourceId = EM.Id     
--where ISNULL(VL.FileName,'')<>'' AND EM.IsObsolete = 0     
       
 --if @permission >= 8      
 --begin      
 -- insert into @tbltmpHistory      
 -- select HD.Id from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id      
 -- where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)      
 -- and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid      
 -- and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))          
 -- and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)      
 -- and (HD.name like '%' + @DocName + '%' or @DocName = '')      
 -- and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)      
 -- order by EM.Code      
        
 -- select @lTotRec = count(*) from @tbltmpHistory      
        
 -- select @res = @res + '<tr><td>' + MT.Title + '</td><td>' + SM.Title + '</td><td>' + Code + '</td>      
 -- <td>' + isnull(FirstName,'') + ' ' + isnull(LastName,'') + '</td><td>' + name + '</td>      
 -- <td><a target="_blank" href="../../../Content/' + convert(varchar,@orgid) + '/HistoryData/' + MT.Title + '/' + convert(varchar,SM.Id) + '/' + Code + '/' + name + '">View</a>      
 -- &nbsp;&nbsp;<a attrcode="' + Code + '" onclick="downloadthis(this,' + convert(varchar,@orgid) + ',' + convert(varchar,SM.Id) + ',''' + MT.Title + ''',''' + Code + ''',''' + name + ''');" style="cursor:pointer;">Download</a>      
 -- &nbsp;&nbsp;<a href="javascript:;" onclick="deletethis(' + convert(varchar,HD.Id) + ')">Delete</a></td></tr>'      
 -- from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory      
 -- where hid = HD.Id order by tid      
 --end        
 --else      
 --begin      
 -- insert into @tbltmpHistory      
 -- select HD.Id from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id      
 -- where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)      
 -- and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid      
 -- and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))          
 -- and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)      
 -- and (HD.name like '%' + @DocName + '%' or @DocName = '')      
 -- and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)      
 -- order by EM.Code      
        
 -- select @lTotRec = count(*) from @tbltmpHistory      
        
 -- select @res = @res + '<tr><td>' + MT.Title + '</td><td>' + SM.Title + '</td><td>' + Code + '</td>      
 -- <td>' + isnull(FirstName,'') + ' ' + isnull(LastName,'') + '</td><td>' + name + '</td>      
 -- <td><a target="_blank" href="../../../Content/' + convert(varchar,@orgid) + '/HistoryData/' + MT.Title + '/' + convert(varchar,SM.Id) + '/' + Code + '/' + name + '">View</a>      
 -- &nbsp;&nbsp;<a attrcode="' + Code + '" onclick="downloadthis(this,' + convert(varchar,@orgid) + ',' + convert(varchar,SM.Id) + ',''' + MT.Title + ''',''' + Code + ''',''' + name + ''');" style="cursor:pointer;">Download</a></td></tr>'      
 -- from tbl_historydata HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id      
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id      
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory      
 -- where HD.Id = hid order by tid      
 --end      
-- select @res as res,@lTotRec as TotRec      
end
GO
PRINT N'Altering Procedure [dbo].[prc_getOutSideDocuments_newsearch_Ng]...';


GO
 
CREATE OR ALTER PROCEDURE [dbo].[prc_getOutSideDocuments_newsearch_Ng]  
@maintypeid int,  
@setupid int,  
@code varchar(300),  
@Name Varchar(300) = '',  
@orgid int,  
@readpermission bit = null,  
@deletepermission bit = null,  
@DocName varchar(300) = null,  
@StoreLocationId int = null,  
@ruserid bigint=0  
as  
begin  
 declare @empid bigint,@lTotRec int,@delmessage varchar(100)='''Are you sure to delete this item?'''  
 select @empid = Id from sHrm.tEmployeeMaster where Code = @code  
 if @code = ''  
 begin  
  select @empid = 0  
 end   
 select @empid = isnull(@empid,0)  
  
 declare @lConfValue varchar(20)='False'  
 select @lConfValue = Isnull(CS.ItemValue,CM.ItemValue)   
 from sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id   
 where CM.ItemKey = 'Examination.IsDocumentLoadUserLocationWise'  
   
 declare @tbltmpHistory table(tid int identity(1,1),hid int)
 declare @tbltmpConsultation table(tid int identity(1,1),hid int)
   
 declare @res varchar(max)=''  
   
 --insert into @tbltmpHistory  
 --select HD.Id from tbl_historydataoutside HD   
 --inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 --inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
 --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
 --inner join sIp.tStoreLocationMaster SLM on SLM.LocationId=LM.Id  
 --inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 --inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 --where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 --and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid        
 --and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)    
 --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
 --and (SLM.Id = @StoreLocationId)  
 --order by EM.Code  
  
 if(@lConfValue='True')  
 begin  
   if(@empid>0)  
   begin  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_historydataoutside HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    --inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
    INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON  
    SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EJD.EmployeeLocationId  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    and (HD.employeeid = @empid ) and EM.OrgID = @orgid    
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '') 
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002 
    --and UL.UserId=@rUserId  
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    --and E.StorelocationId = @StoreLocationId  
    --order by EM.Code  
    
    insert into @tbltmpHistory
    select distinct HD.Id from tbl_historydataoutside HD 
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 	inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 	inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 	where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 	and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 	and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)  

	insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
 	
   end  
   else   
   begin  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_historydataoutside HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    --inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
    INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON  
    SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EJD.EmployeeLocationId  
  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
    and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))      
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)   
    --and UL.UserId=@rUserId  
    --order by EM.Code  
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002 
    
    insert into @tbltmpHistory
    select distinct HD.Id from tbl_historydataoutside HD 
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 	inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 	inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 	where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 	and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 	and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)

	insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end  
 end    
 else   
 begin  
   if(@empid>0)  
   begin  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_historydataoutside HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
	
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    and (HD.employeeid = @empid ) and EM.OrgID = @orgid    
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    and UL.UserId=@rUserId
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002   
    --and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    --and E.StorelocationId = @StoreLocationId  
    --order by EM.Code  
    
    insert into @tbltmpHistory
    select distinct HD.Id from tbl_historydataoutside HD 
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 	inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 	inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 	where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 	and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 	and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)

	insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
 
   end  
   else   
   begin  
    print 'test'  
    insert into @tbltmpHistory  
    select distinct HD.Id from tbl_historydataoutside HD   
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
    inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
    inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
    --inner join sCommon.tLocationMaster LM on LM.Id=EJD.EmployeeLocationId  
    inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
    inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
    inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
    inner join sSecurity.tUserLocation UL On UL.StorelocationId=SLM.Id  
  
    where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
    --and (HD.employeeid = @empid or @empid = 0)   
    and EM.OrgID = @orgid  
    and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = ''))      
    and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)  
    and (HD.name like '%' + @DocName + '%' or @DocName = '')  
    and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
    --and (1=(case when @maintypeid =1 then 1 else 0 end) or (SLM.Id = @StoreLocationId))  
    --and SLM.Id = @StoreLocationId  
    and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)   
    and UL.UserId=@rUserId  
    --order by EM.Code  
	and IsNULL(E.IsCancel,0) = 0 -- Nidhi Pandey, dt - 13/10/2023, mantis - 28002 
     
     insert into @tbltmpHistory
    select distinct HD.Id from tbl_historydataoutside HD 
    inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 	inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 	inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 	where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 	and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
 	and HD.setupid = sCommon.fGetIntIdForOrg(8, @orgid)
	
	insert into @tbltmpConsultation
    select distinct HD.Id from sWellness.tConsultationDocuments HD 
	 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
	 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
	 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
	 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
	 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id  
	 where (setupid = @setupid or @setupid = 0) and (STM.maintypeid = @maintypeid or @maintypeid = 0)  
	 and (WC.ParticipantSourceId = @empid or @empid = 0) and EM.OrgID = @orgid
	 and WC.setupid = sCommon.fGetIntIdForOrg(17, @orgid)
   end  
 end  
   
 select @lTotRec = count(*) from @tbltmpHistory  
 
 select * from (
 select HD.Id,HD.MainTypeId,MT.Title as MainType , SM.Title as SetupMaster ,Code ,isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName ,name as FileName,
 SM.Id as SetupMasterId,ext as Extension,isnull(hd.OpdId,0)as OpdId, 0 as ConfigId  --mantis id: 46943; yogesh; Dt- 07/11/2025    
 from tbl_historydataoutside HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory  
 where hid = HD.Id
 
 UNION ALL
 
 select HD.Id,STM.MainTypeId,MT.Title as MainType,SM.Title as SetupMaster, Code ,isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName,FileName,
	SM.Id as SetupMasterId,'' as Extension,isnull(hd.ConsultationId,0) as ConsultationId, HD.ConfigId    
 from sWellness.tConsultationDocuments HD
 inner join sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 inner join sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 inner join sExamination.tSetupMaster SM on WC.setupid = SM.id
 inner join sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 inner join sExamination.tMainTypeMaster MT on STM.maintypeid = MT.Id,@tbltmpConsultation
 where hid = HD.Id
 ) t
 order by t.Id desc
 --order by tid  
   
 --if @permission >= 8  
 --begin  
 -- insert into @tbltmpHistory  
 -- select HD.Id from tbl_historydataoutside HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 -- where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 -- and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid        
 -- and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)    
 -- and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
 -- order by EM.Code  
    
 -- select @lTotRec = count(*) from @tbltmpHistory  
    
 -- select @res = @res + '<tr><td>' + MT.Title + '</td><td>' + SM.Title + '</td><td>' + Code + '</td>  
 -- <td>' + isnull(FirstName,'') + ' ' + isnull(LastName,'') + '</td><td>' + name + '</td>  
 -- <td><a onclick="Viewthis(this);" style="cursor:pointer;"  
 -- attrMTitle="'+ MT.Title +'"  
 -- attrSId="' + convert(varchar,SM.Id) + '"  
 -- attrCode="' + Code + '"  
 -- attrTitle="' + name + '"  
 -- attrExt="' + ext + '">View</a>  
 -- <a class="testview" target="_blank" href="javascript:;" style="display:none;">View</a>  
 -- &nbsp;&nbsp;<a attrcode="' + Code + '" onclick="downloadthis(this,' + convert(varchar,@orgid) + ',' + convert(varchar,SM.Id) + ',''' + MT.Title + ''',''' + Code + ''',''' + name + ''');" style="cursor:pointer;">Download</a>  
 -- &nbsp;&nbsp;<a href="javascript:;" onclick="deletethis(' + convert(varchar,HD.Id) + ')">Delete</a></td></tr>'  
 -- from tbl_historydataoutside HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory  
 -- where hid = HD.Id order by tid  
 --end    
 --else  
 --begin  
 -- insert into @tbltmpHistory  
 -- select HD.Id from tbl_historydataoutside HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
 -- where (setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
 -- and (employeeid = @empid or @empid = 0) and EM.OrgID = @orgid    
 -- and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid)    
 -- and (SM.StoreLocationId = @StoreLocationId or SM.StoreLocationId = 0)  
 -- order by EM.Code  
    
 -- select @lTotRec = count(*) from @tbltmpHistory  
    
 -- select @res = @res + '<tr><td>' + MT.Title + '</td><td>' + SM.Title + '</td><td>' + Code + '</td>  
 -- <td>' + isnull(FirstName,'') + ' ' + isnull(LastName,'') + '</td><td>' + name + '</td>  
 -- <td><a onclick="Viewthis(this);" style="cursor:pointer;"  
 -- attrMTitle="'+ MT.Title +'"  
 -- attrSId="' + convert(varchar,SM.Id) + '"  
 -- attrCode="' + Code + '"  
 -- attrTitle="' + name + '"  
 -- attrExt="' + ext + '">View</a>  
 -- <a class="testview" target="_blank" href="javascript:;" style="display:none;">View</a>  
 -- &nbsp;&nbsp;<a attrcode="' + Code + '" onclick="downloadthis(this,' + convert(varchar,@orgid) + ',' + convert(varchar,SM.Id) + ',''' + MT.Title + ''',''' + Code + ''',''' + name + ''');" style="cursor:pointer;">Download</a></td></tr>'  
 -- from tbl_historydataoutside HD inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
 -- inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
 -- inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id,@tbltmpHistory  
 -- where HD.Id = hid order by tid  
 --end  
 --select @res as res,@lTotRec as TotRec  
end
GO
PRINT N'Altering Procedure [sAppointment].[pAppointmentSchedulingAdd]...';


GO
   CREATE OR ALTER PROCEDURE [sAppointment].[pAppointmentSchedulingAdd]      
@rId bigint,      
@rOrgId int      
,@rPatientSourceId bigint      
,@rPatientSourceTypeId smallint      
,@rAppointmentDate datetime      
,@rDoctorEmployeeId bigint      
,@rFromTime time = null      
,@rToTime time = null      
,@rIsRegister bit      
,@rIsObsolete bit      
,@rCreatedUserId bigint      
,@rReferSourceId bigint      
,@rReferSourceTypeId int      
,@rStoreLocationId int      
,@rSetupId int,      
@rCauseId int,      
@rOtherName varchar(200)=null,      
--@rFollowUpDate datetime,    
@rFollowupRemark varchar(200)=null,  --mantis id:0042007 commented by shiv thapa  
@rComplaintRemark varchar(200)=null,  --  
--@rAppointmentRemark varchar(200)=null,     
@rAge int = null,      
@rMonth tinyint = null,      
@rGenderId tinyint = null,      
@rTimeslotId int = null,      
@rAppointmentType tinyint = null,      
@rEntryType tinyint = 0,      
@rApprovalStatusId int = null
AS      
BEGIN        
 DECLARE @1SubTypeId int      
 SELECT @1SubTypeId = SubTypeId From sExamination.tSetupMaster where Id = @rSetupId      
 IF EXISTS(Select 1 FROM sAppointment.tAppointment Where PatientSourceId = @rPatientSourceId AND PatientSourceTypeId = @rPatientSourceTypeId AND SetupId = @rSetupId) AND @1SubTypeId != 8 AND @rId = 0      
 BEGIN      
  SELECT -101 AS RESULT      
  RETURN      
 END    
    
  IF EXISTS(Select 1 FROM sAppointment.tAppointment Where TimeSlotId = @rTimeSlotId AND PatientSourceTypeId = @rPatientSourceTypeId AND ApprovalStatusId = @rApprovalStatusId) AND @rId = 0 AND @rTimeSlotId != 0     
 BEGIN      
  SELECT -102 AS RESULT      
  RETURN      
 END    
 --IF @rPatientSourceTypeId != 1009    
 --BEGIN    
 -- Declare @lAge int;    
 -- select @lAge = Case When @rPatientSourceTypeId = 1001 Then (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeeFamilyDetails where Id = @rPatientSourceId)    
 --     ELSE (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeePersonalDetail where EmployeeId = @rPatientSourceId) END    
 -- IF @lAge != @rAge    
 -- BEGIN    
 --  SELECT -3 AS Result
 --  RETURN    
 -- END    
 --END    
      
 IF NOT EXISTS (Select 1 FROM sAppointment.tAppointment Where PatientSourceId = @rPatientSourceId       
 AND PatientSourceTypeId = @rPatientSourceTypeId AND SetupId = @rSetupId  AND @1SubTypeId != 8) AND @rId = 0      
 BEGIN      
 BEGIN TRY      
 BEGIN TRANSACTION      
  DECLARE @lNextNumber BIGINT      
  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppointment.tAppointment ', 0, 1, 1,@outNextNumber = @lNextNumber output      
      
  DECLARE @loNextNumber nVarchar(20)      
  Set @rApprovalStatusId = Isnull(@rApprovalStatusId,548)    
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 8,      
  @rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT      
     SET @loNextNumber = ISNULL(@loNextNumber, '-300')    IF @loNextNumber = '-300'   BEGIN     SELECT -300 AS Result, '' AS Number, 0 AS Id     RETURN      
  END      
         
  INSERT INTO sAppointment.tAppointment       
  (      
   Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,      
   AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,      
   IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,      
   StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,CompliantRemark,Age,Months,GenderId,TimeSlotId,AppointmentType,EntryType,ApprovalStatusId,AppointmentFlag      
  )      
  VALUES      
  (      
   @lNextNumber,@rPatientSourceId,@rPatientSourceTypeId,@rAppointmentDate,      
   @loNextNumber,@rDoctorEmployeeId,@rFromTime,@rToTime,0,@rIsObsolete,@rOrgId,      
   1,@rReferSourceId,@rReferSourceTypeId,@rStoreLocationId,@rSetupId,@rCauseId,@rOtherName,      
   @rFollowupRemark,@rComplaintRemark,@rAge,@rMonth,@rGenderId,@rTimeslotId,@rAppointmentType,@rEntryType,@rApprovalStatusId,'New Appointment'     
  )      
  COMMIT TRANSACTION        
 END TRY      
 BEGIN CATCH       
  ROLLBACK TRANSACTION      
  SELECT -101 AS RESULT      
  RETURN      
 END CATCH      
 END      
 ELSE          
 BEGIN      
  SET @lNextNumber = @rId      
  UPDATE sAppointment.tAppointment SET       
  --AppointmentType=@rAppointmentType,TimeslotId=@rTimeslotId,PatientSourceId=@rPatientSourceId,PatientSourceTypeId=@rPatientSourceTypeId,    
  --AppointmentDate = @rAppointmentDate,    
  DoctorEmployeeId = @rDoctorEmployeeId,      
  FromTime = @rFromTime,ToTime = @rToTime    
  --AppointmentRemark = @rAppointmentRemark,    
  --FollowUpDate=@rFollowUpDate,FollowupRemark = @rFollowupRemark     
  WHERE Id = @rId       
 END        
 SELECT @lNextNumber AS RESULT          
END
GO
PRINT N'Altering Procedure [sAppointment].[pAppointmentSchedulingModify]...';


GO
-- exec [sAppointment].[pAppointmentSchedulingModify]  
-- drop proc [sAppointment].[pAppointmentSchedulingModify]  
CREATE OR ALTER PROCEDURE [sAppointment].[pAppointmentSchedulingModify]  
@rId bigint  
,@rPatientSourceId bigint  
,@rPatientSourceTypeId smallint  
,@rAppointmentDate date  
,@rAppointmentNumber nvarchar(20)  
,@rDoctorEmployeeId bigint  
,@rFromTime time  
,@rToTime time  
,@rIsRegister bit  
,@rIsObsolete bit  
,@rStoreLocationId int  
,@rSetupid int,  
@rCauseId int,  
@rOtherName varchar(200)=null,  
@rFollowupRemark varchar(200)=null, 
@rComplaintRemark varchar(200)=null,
@rAge int=null,  
@rMonth tinyint = null,  
@rGenderId tinyint = null  
AS  
BEGIN  
 BEGIN TRY   
 BEGIN TRANSACTION  
  
  --IF @rPatientSourceTypeId != 1009  
  --BEGIN  
  --  Declare @lAge int;  
  --  select @lAge = Case When @rPatientSourceTypeId = 1001 Then (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeeFamilyDetails where Id = @rPatientSourceId)  
  --      ELSE (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeePersonalDetail where EmployeeId = @rPatientSourceId) END  
  --  IF @lAge != @rAge  
  --  BEGIN  
  --   SELECT -3 AS Result  
  --   RETURN  
  --  END  
  --END  
  
  UPDATE sAppointment.tAppointment SET PatientSourceId = @rPatientSourceId,  
  PatientSourceTypeId = @rPatientSourceTypeId,AppointmentDate = @rAppointmentDate,  
  DoctorEmployeeId = @rDoctorEmployeeId,FromTime=@rFromTime,ToTime=@rToTime,  
  IsRegister = @rIsRegister,IsObsolete= @rIsObsolete,StoreLocationId = @rStoreLocationId,  
  SetupId = @rSetupid,CauseId = @rCauseId,OtherName = @rOtherName,  
  CompliantRemark = @rComplaintRemark, FollowupRemark = @rFollowupRemark,Age=@rAge,Months = @rMonth,GenderId = @rGenderId  
  WHERE Id=@rId AND AppointmentNumber=@rAppointmentNumber  
  SELECT 1 AS RESULT  
 COMMIT TRANSACTION  
  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRANSACTION  
  SELECT -1 AS RESULT  
 END CATCH  
END
GO
PRINT N'Altering Procedure [sAppointment].[pTimeSlotSetupAdd]...';


GO

CREATE OR ALTER PROCEDURE [sAppointment].[pTimeSlotSetupAdd]
        @rId int,
        @rOrgId smallint,
        @rStoreLocationId int,        
        @rCode nvarchar(100)=null,
		@rTitle nvarchar(100)=null,	
		@rSourceTypeId int,
		@rMainTypeId int,
		@rSetupId int=0,	    
		@rDoctorEmployeeId bigint=0,         
        @rCreatedUserId bigint,
        @rUpdatedUserId bigint,        		
		@rIsOnline bit=0,
		@rIsOffline bit=0,
		@rIsObsolete bit=0,
		@rServiceId bigint = 0
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		BEGIN 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Code)=UPPER(@rCode) AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -102 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Title)=UPPER(@rTitle) AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -106 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOnline=@rIsOnline AND @rIsOnline <> 0 AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -107 AS Result
				RETURN
			END
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOffline=@rIsOffline AND @rIsOffline <> 0 AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -108 AS Result
				RETURN
			END
		END
	END
	ELSE
	BEGIN
		BEGIN 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Code)=UPPER(@rCode) AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -102 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Title)=UPPER(@rTitle) AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -106 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOnline=@rIsOnline AND @rIsOnline <> 0 AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -107 AS Result
				RETURN
			END
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOffline=@rIsOffline AND @rIsOffline <> 0 AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -108 AS Result
				RETURN
			END
		END
	END
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
 
	IF(@rId = 0)	
	BEGIN
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSupport.tVaccineDoseMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO   [sAppointment].[tTimeSlotSetup] 		(Code,Title,SourceTypeId,MainTypeId,SetupId,DoctorEmployeeId,StoreLocationId,OrgId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,IsOnline,IsOffline,ServiceId 		) 		VALUES 		(			
			@rCode,@rTitle,@rSourceTypeId,@rMainTypeId,@rSetupId,@rDoctorEmployeeId,@rStoreLocationId,@rOrgId,@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rUpdatedUserId,sCommon.fGetDate(),@rIsOnline,@rIsOffline,@rServiceId 		)
		 SELECT 1 AS Result			
	END	
 
ELSE
	 BEGIN	 
	    UPDATE  [sAppointment].[tTimeSlotSetup]
	    SET
			Code=@rCode,	         			Title=@rTitle,	 			SourceTypeId= @rSourceTypeId, 			MainTypeId=@rMainTypeId, 			SetupId=@rSetupId, 			DoctorEmployeeId=@rDoctorEmployeeId,      			UpdatedUserId=@rUpdatedUserId, 			UpdatedDateTime=sCommon.fGetDate(),						
			IsObsolete=@rIsObsolete,
			IsOnline = @rIsOnline,	      
			IsOffline = @rIsOffline,
			ServiceId = @rServiceId
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
 
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		SELECT ERROR_MESSAGE() AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sAppointment].[pTimeSlotSetupGet]...';


GO

CREATE OR ALTER PROCEDURE [sAppointment].[pTimeSlotSetupGet]	 	
	@rOrgId int,
	@rStoreLocationId int,
	@rId int,
	@rCode nvarchar(100)=null,
	@rTitle nvarchar(100)=null,	
	@rSourceTypeId int=0,
	@rMainTypeId int,
	@rSetupId int=0,	    
	@rDoctorEmployeeId bigint=0		 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 		
		TSS.Id,	
		TSS.Code,	
		TSS.Title,
		Isnull(MT.Title,'') ExaminationType,
		Isnull(MT.Id,0) ExaminationTypeId,
		Isnull(SM.Title,'') AS Round,
		Isnull(SM.Id,0) SetupID,		
		TSS.SourceTypeID,
		case when TSS.SourceTypeID=16 then 'Appointment'
		when TSS.SourceTypeID=10171 then 'Wellness Appointment'
		when TSS.SourceTypeID=10172 then 'Wellness Patient Register' 
		else 'Patient Register' end SourceType,
		Isnull(TSS.DoctorEmployeeId,0)DoctorEmployeeId,
		Isnull(TSS.IsObsolete,0) as IsObsolete,
		TSS.StoreLocationId
	FROM 
		[sAppointment].[tTimeSlotSetup] TSS 
		Left join sExamination.tMainTypeMaster MT on MT.Id=TSS.MainTypeId 
		Left Join sExamination.tSetupMaster SM On SM.ID=TSS.SetupId
	where TSS.orgid=@rOrgId and (TSS.SetupId = @rSetupId or (@rSetupId=0))
	and (TSS.Id=@rId or (@rId=0))
	and (TSS.MainTypeId=@rMainTypeId or @rMainTypeId =0)
	and TSS.StorelocationID=@rStoreLocationId
	and (TSS.Code like '%'+Isnull(@rCode,'')+'%' or Isnull(@rCode,'')='')
	and (TSS.Title like '%'+Isnull(@rTitle,'')+'%' or Isnull(@rTitle,'')='')
	and (TSS.SourceTypeId=@rSourceTypeId or @rSourceTypeId=0)
END
GO
PRINT N'Altering Procedure [sAudit].[pArchiveAuditLogHistoryDocumentListGet]...';


GO
CREATE OR ALTER PROCEDURE [sAudit].[pArchiveAuditLogHistoryDocumentListGet]
(
    @rDeletePermission BIT = 0,
    @rOrgId INT,
    @rConfVal INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @res VARCHAR(MAX) = '',
            @delmessage VARCHAR(100) = '''Are you sure to delete this item?''';

    -- Local Drive / Different Drive
    IF (@rConfVal IN (1,2))
    BEGIN
       SELECT @res = @res +
'<tr>
    <td>' + FileName + '</td>
    <td>
        <a attrcode="0"
           onclick="downloadthis(this,' + CAST(OrgId AS VARCHAR) + ',''AuditLogHistory'',''' + FileName + ''');"
           style="cursor:pointer;">Download</a>
    </td>' +

    CASE 
        WHEN @rDeletePermission = 1 THEN
            '<td>
                <a href="javascript:;"
                   onclick="if (!confirm(' + @delmessage + '))
                   { false } else { deletethis(' + CAST(Id AS VARCHAR) + ',this) }">
                   Delete
                </a>
             </td>'
        ELSE
            ''
    END +

'</tr>'
FROM [sAudit].[tArchiveAuditLogHistoryDocuments]
WHERE OrgId = @rOrgId
  AND ConfigurationTypeId = @rConfVal;
  end
    -- Azure
    ELSE IF (@rConfVal = 3)
    BEGIN
        SELECT @res = @res +
'<tr>
    <td>' + FileName + '</td>
    <td>
        <a style="cursor:pointer"
           onclick="DownloadAzure(this);"
           attrOrgId="' + CAST(OrgId AS VARCHAR) + '"
           attrName="' + FileName + '">
            Download
        </a>
    </td>' +

    CASE 
        WHEN @rDeletePermission = 1 THEN
            '<td>
                <a href="javascript:;"
                   onclick="if (!confirm(' + @delmessage + '))
                   { false } else { deletethis(' + CAST(Id AS VARCHAR) + ',this) }">
                   Delete
                </a>
             </td>'
        ELSE
            ''   -- ❌ no empty <td>
    END +

'</tr>'
FROM [sAudit].[tArchiveAuditLogHistoryDocuments]
WHERE OrgId = @rOrgId
  AND ConfigurationTypeId = @rConfVal;
  end
    SELECT @res AS res;
END
GO
PRINT N'Altering Procedure [sCommon].[pEmployeeSearchGet]...';


GO

CREATE OR ALTER PROCEDURE [sCommon].[pEmployeeSearchGet]
@rOrgId [int],
@rEmployeeCode [nvarchar](20) = '',
@rFirstName [nvarchar](30) = '',
@rMobileNumber [nvarchar](20) = '',
@rDOB [datetime] = '1/1/1900',
@rEmployeeLocationId int,
@rLastName [nvarchar](30) = '',
@rParticipantSourceTypeId int = 0,
@rDepartmentId int = 0,
@rEmployeeId bigint = 0,
@rEmployeeStoreLocationId int=0,
@rMiddleName varchar(200) = null,
@rIsIndividualWithOpd bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	declare @lLocationId int
	select @lLocationId = LocationId from sIp.tStoreLocationMaster where Id = @rEmployeeStoreLocationId
	select @lLocationId = isnull(@lLocationId,0)
	IF(@rParticipantSourceTypeId = 95 OR @rParticipantSourceTypeId = 0)
	BEGIN
		 
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
		 
		Select * from
		(
			SELECT distinct EM.OrgID,EM.Id,EM.EmployeeId,EM.Code,
			FirstName,MiddleName,LastName,
			EmployeeName,GenderId,DateOfBirth,
			DateOfJoining,G.Title AS Gender,StatusId,
			EM.IsObsolete,PhoneNoCompany,CompanyEmail,
			ExtensionNo,DepartmentId,DepartmentCode,
			DepartmentName,ISNULL (MobileNumber,0) AS MobileNumber,
			EmployeeJobTitleId,EmployeeTypeId,EmployeeJobTitle,
			EmployeeLocationId, EmployeeStoreLocationId,isnull(DATEDIFF(yy,DateOfBirth,sCommon.fGetDate()),0) AS Age,
			DesignationId,ProcessTypeId,EM.ParticipantSourceTypeId,'Employee' as 'TypeName',
			EM.EmployeeCompanyId,
			EM.TargetGroupId,
			ISNULL(LDT.IsonSugarMedication, 0) IsonSugarMedication,
			ISNULL(LDT.IsonBPMedication, 0) IsonBPMedication,
			(Case When ISNULL(LDT.RiskCategoryId, 0) = 1 Then 1 Else 0 END) RiskCategoryChecked,
			em.CompanyEmail as Email, ISNULL(PM.Title,'') as ProgramName
			FROM sHrm.vEmployeeDetail EM   -- changed view, DT- 11/01/2024; Mantis id =28791; Nidhi Pandey 
			LEFT JOIN sExamination.tLSDTrackerEmployee LDT ON LDT.ParticipantSourceId = EM.EmployeeId and LDT.ParticipantSourceTypeId = 95
			LEFT JOIN sCommon.tGenderMaster G ON EM.GenderId = G.Id
			LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.EmployeeId and MS.EmployeeSourceTypeId = 95
			LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId
			WHERE ((EM.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
			AND ((EM.FirstName Like  @rFirstName)  OR (ISNULL(@rFirstName,'') = ''))
			AND ((EM.LastName Like  @rLastName)  OR (ISNULL(@rLastName,'') = ''))
			AND ((EM.MiddleName Like  @rMiddleName)  OR (ISNULL(@rMiddleName,'') = ''))
			AND ((EM.MobileNumber Like @rMobileNumber) OR(ISNULL(@rMobileNumber,'') = ''))
			AND EM.IsObsolete = 0 AND EM.OrgId = @rOrgId
			AND ((EM.EmployeeLocationId = @rEmployeeLocationId) OR (ISNULL(@rEmployeeLocationId,0) = 0))
			AND ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		) as a
	END
	ELSE IF(@rParticipantSourceTypeId = 1001)
	BEGIN
		SELECT distinct EFD.OrgId,EFD.DependentId,EFD.EmployeeCode AS Code,
		EFD.EmployeeId AS Id,EFD.Name AS EmployeeName,EFD.DateOfBirth,EFD.AGE,
		0 AS GenderId,EFD.DepartmentId,EFD.DepartmentName,0 AS MobileNumber,
		EFD.DesignationId,'' AS FirstName,'' AS LastName,
		1001 AS ParticipantSourceTypeId,'' as 'TypeName',0 as EmployeeCompanyId,EJD.EmployeeStoreLocationId
		FROM sHrm.vExtEmployeeFamilyDetail EFD
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EFD.EmployeeId
		Where (EFD.EmployeeCode Like @rEmployeeCode) AND EFD.DependentId = @rEmployeeId
		AND EFD.OrgId = @rOrgId AND (EFD.EmployeeLocationId = @rEmployeeLocationId or @rEmployeeLocationId = 0)
	END
	ELSE IF(@rParticipantSourceTypeId = 1009)
	BEGIN
		IF(@rIsIndividualWithOpd = 0)
		BEGIN
			SELECT distinct ECB.OrgId,EmployeeId AS Id,EmployeeId,ECB.Code,ECB.FirstName,
			ECB.LastName,ECB.EmployeeName,G.Title AS Gender,ECB.GenderId,ISNULL(ECB.DateOfBirth,'') AS DateOfBirth,
			'' AS DepartmentName,1009 AS ParticipantSourceTypeId,0 AS  DepartmentId,0 AS DesignationId,
			ISNULL(DATEDIFF(yy,ECB.DateOfBirth,sCommon.fGetDate()),0) AS Age,DATEDIFF(mm, ECB.DateOfBirth, sCommon.fGetDate()) % 12 as [Month],
			0 AS ProcessTypeId,ECB.OrgId,ECB.LocationId, ISNULL(CB.MobileNo,'') AS MobileNumber,'Other' as 'TypeName',0 as EmployeeCompanyId, 
			CB.MobileNo, CB.UIDNumber, ECB.CSRBenefiterTypeId, ECB.LocationId as EmployeeLocationId
			FROM sHrm.vExtCsrBenefiterMaster as ECB
			Inner Join sHrm.tCsrBenefiterMaster CB ON CB.Id = ECB.EmployeeId
			LEFT JOIN [sCommon].[tGenderMaster] G ON ECB.GenderId = G.Id
			WHERE (ECB.Code Like @rEmployeeCode) AND ECB.OrgId = @rOrgId
			AND (ECB.LocationId = @rEmployeeLocationId or @rEmployeeLocationId = 0)
			AND (ECB.LocationId = @lLocationId or @lLocationId = 0)
		END
		Else
		BEGIN
			SELECT distinct ECB.OrgId,EmployeeId AS Id,EmployeeId,ECB.Code,ECB.FirstName,
			ECB.LastName,ECB.EmployeeName,G.Title AS Gender,ECB.GenderId,ISNULL(ECB.DateOfBirth,'') AS DateOfBirth,
			'' AS DepartmentName,1009 AS ParticipantSourceTypeId,0 AS  DepartmentId,0 AS DesignationId,
			ISNULL(DATEDIFF(yy,ECB.DateOfBirth,sCommon.fGetDate()),0) AS Age,DATEDIFF(mm, ECB.DateOfBirth, sCommon.fGetDate()) % 12 as [Month],
			0 AS ProcessTypeId,ECB.OrgId,ECB.LocationId, ISNULL(CB.MobileNo,'') AS MobileNumber,'Other' as 'TypeName',0 as EmployeeCompanyId, 
			CB.MobileNo, CB.UIDNumber, ECB.CSRBenefiterTypeId, ECB.LocationId as EmployeeLocationId
			FROM sHrm.vExtCsrBenefiterMaster as ECB
			Inner Join sHrm.tCsrBenefiterMaster CB ON CB.Id = ECB.EmployeeId
			LEFT Join sHrm.tCsrBenefiterTypeMaster CBTM ON CBTM.Id = ECB.CSRBenefiterTypeId
			LEFT JOIN [sCommon].[tGenderMaster] G ON ECB.GenderId = G.Id
			WHERE (ECB.Code Like @rEmployeeCode) AND ECB.OrgId = @rOrgId
			AND (ECB.LocationId = @rEmployeeLocationId or @rEmployeeLocationId = 0)
			AND (ECB.LocationId = @lLocationId or @lLocationId = 0) and CBTM.IsOtherId = 1
		END
	END	
END
GO
PRINT N'Altering Procedure [sCommon].[pRangeDetailsGet]...';


GO


CREATE OR ALTER PROCEDURE [sCommon].[pRangeDetailsGet] @rRangeTableId int,@rOrgId int=1
AS
BEGIN

	Declare @lBPRangeCalculationVal nvarchar(10);

	select @lBPRangeCalculationVal = sConfig.fConfigurationValueGet('Examination.BPRangeCalculation',@rOrgId,0,0,0)

    DECLARE @TableOne TABLE (
        tId int IDENTITY (1, 1),
		Id int,
        FromRange nvarchar(100),
        ToRange nvarchar(100),
        Code nvarchar(100),
        Title nvarchar(100),
        IsObsolete nvarchar(100),
		Recommendation nvarchar(max)
    )

	 DECLARE @TableTwo TABLE (
        tId int IDENTITY (1, 1),
		Id int,
        SystolicmmHg nvarchar(100),
        DiastolicmmHg nvarchar(100),
        BloodPressureCategory nvarchar(100),
        Recommendation nvarchar(max),
        IsObsolete nvarchar(100)
    )

    IF (@rRangeTableId IN (1, 2, 3))
    BEGIN
        IF (@rRangeTableId = 1 AND @lBPRangeCalculationVal = 'Diastolic')
        BEGIN
            INSERT INTO @TableOne
                SELECT Id, FromRange, ToRange, Code, Title, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END, Recommendation
                FROM sExamination.tBloodPressureRangeMaster
                ORDER BY id
        END
		ELSE IF (@rRangeTableId = 1 AND @lBPRangeCalculationVal = 'AHA')
        BEGIN
            INSERT INTO @TableTwo
                SELECT Id, SystolicmmHg, DiastolicmmHg, BloodPressureCategory, Recommendation, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END
                FROM sExamination.tBloodPressureAHARangeMaster
                ORDER BY id
        END
		ELSE IF (@rRangeTableId = 1 AND @lBPRangeCalculationVal = 'IND')
        BEGIN
            INSERT INTO @TableTwo
                SELECT Id, SystolicmmHg, DiastolicmmHg, BloodPressureCategory, Recommendation, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END
                FROM sExamination.tBloodPressureINDRangeMaster
                ORDER BY id
        END
        ELSE
        IF (@rRangeTableId = 2)
        BEGIN
            INSERT INTO @TableOne
                SELECT Id, FromRange, ToRange, Code, Title, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END, Recommendation
                FROM sExamination.tBMIRangeMaster
                ORDER BY id
        END
        ELSE
        IF (@rRangeTableId = 3)
        BEGIN
            INSERT INTO @TableOne
                SELECT Id, FromRange, ToRange, Code, Title, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END, Recommendation
                FROM sExamination.tAudiometryRangeMaster
                ORDER BY id
        END

		IF (@rRangeTableId = 1 AND (@lBPRangeCalculationVal = 'AHA' OR @lBPRangeCalculationVal = 'IND'))
		BEGIN
			--SELECT RangeDetails = '
			--					<td>    ' + CONVERT(varchar, tId) + '			</td>
			--					<td>    ' + ISNULL(FromRange, '') + '			</td>
			--					<td>    ' + ISNULL(ToRange, '') + '			</td>
			--					<td>    ' + ISNULL(Title, '') + '			</td>
			--					<td><input type="text" class="form-control" value="' + ISNULL(Recommendation, '') + '" id="Recommendation_' + CONVERT(NVARCHAR(10), Id) + '" />
			--					</td>
			--					' FROM @TableTwo
			SELECT RangeDetails = '<thead class="thead-light">
									<tr style="background-color: #f9f9f9;">
										<th align="left" scope="col" style="width: 10%;">Sr No</th>
										<th align="left" scope="col" style="width: 20%;">SYSTOLIC&nbsp;mm&nbsp;Hg&nbsp;(upper&nbsp;number)</th>
										<th align="left" scope="col" style="width: 20%;">DIASTOLIC&nbsp;mm&nbsp;Hg&nbsp;(lower&nbsp;number)</th>
										<th align="left" scope="col" style="width: 20%;">BLOOD&nbsp;PRESSURE&nbsp;CATEGORY</th>
										<th align="left" scope="col" style="width: 30%;">Recommendation</th>
									</tr>
								</thead>
								<tbody id="tblBloodPressureReadings">' 
								+ STUFF((
									SELECT 
										'</tr><tr>
											<td hidden>' + CONVERT(VARCHAR, Id) + '</td>
											<td>' + CONVERT(VARCHAR, tId) + '</td>
											<td>' + Systolic + '</td>
											<td>' + Diastolic + '</td>
											<td>' + Category + '</td>
											<td><input type="text" class="form-control" value="' + ISNULL(Recommendation, '') + '" id="Recommendation_' + CONVERT(NVARCHAR(10), Id) + '" /></td>
										</tr>'
									FROM (
										SELECT tId, Id, SystolicmmHg as Systolic, DiastolicmmHg as Diastolic, BloodPressureCategory as Category, Recommendation from @TableTwo
									) AS BPReadings
									ORDER BY Tid
									FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 5, '') 
								+ '</tbody>'
		END
		ELSE
		BEGIN
			SELECT RangeDetails = '
								<td hidden>' + CONVERT(VARCHAR, Id) + '</td>
								<td>    ' + CONVERT(varchar, tId) + '			</td>
								<td>    ' + ISNULL(FromRange, '') + '			</td>
								<td>    ' + ISNULL(ToRange, '') + '			</td>
								<td>    ' + ISNULL(Title, '') + '			</td>
								<td><input type="text" class="form-control" value="' + ISNULL(Recommendation, '') + '" id="Recommendation_' + CONVERT(NVARCHAR(10), Id) + '" />
								</td>
								' FROM @TableOne
			ORDER BY Tid
		END
        SELECT *
        FROM @TableOne
    END
    ELSE
    IF (@rRangeTableId IN (4))
    BEGIN
		Declare @lIsPulmonaryCalculationVal nvarchar(10);

		select @lIsPulmonaryCalculationVal = sConfig.fConfigurationValueGet('Examination.IsPulmonaryCalculation',@rOrgId,0,0,0)

        DECLARE @tPulmonaryObserved nvarchar(max) = ''
        DECLARE @tPulmonaryPredicting nvarchar(max) = ''
        DECLARE @tPulmonaryRangeMaster nvarchar(max) = ''

        SELECT @tPulmonaryObserved = @tPulmonaryObserved + '
		<tr><td>' + CONVERT(varchar, id) + '</td>
		<td>' + ISNULL(Title, '') + '</td>
		<td>' + ISNULL(Formula, '') + '</td></tr>'

        FROM sExamination.tPulmonaryObserved
        ORDER BY id

        SELECT @tPulmonaryPredicting = @tPulmonaryPredicting + '<tr>
			<td>' + CONVERT(varchar, ROW_NUMBER() OVER (Order by Id ASC)) + '</td>
			<td>' + CONVERT(varchar, ISNULL(Title, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(AgeFrom, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(AgeTo, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(HightFrom, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(HightTo, '')) + '</td>
			<td>' + CASE
            WHEN CONVERT(varchar, ISNULL(GenderId, '1')) = '1' THEN 'Male'
            ELSE 'Female'
        END + '</td>
			<td>' + CONVERT(nvarchar(max), ISNULL(Formula, '')) + '</td>
			</tr>'
        FROM sExamination.tPulmonaryPredicting
		Where (Config = @lIsPulmonaryCalculationVal or @lIsPulmonaryCalculationVal = '')
        ORDER BY id
        SELECT @tPulmonaryRangeMaster = @tPulmonaryRangeMaster + '<tr>
				<td>' + CONVERT(varchar, ROW_NUMBER() OVER (Order by Id) ) + '</td>
				<td>' + ISNULL(Condition, '') + '</td>
				<td>' + ISNULL(ConditionDetail, '') + '</td>
				<td>' + ISNULL(IntensityCondition, '') + '</td>
				<td>' + ISNULL(Intensity, '') + '</td>
				<td>' + ISNULL(Status, '') + '</td>
				</tr>'
        FROM sExamination.tPulmonaryRangeMaster
		Where (OrgId=case when @rOrgId=3001 then @rOrgId else 1 end)
        ORDER BY id

        DECLARE @TableExport nvarchar(max) = '<tr><td colspan="8">Pulmonary Observed Details:</td></tr>
                                              <tr>
												<td colspan="2">Sr No</td>
                                                <td colspan="3">Title</td>
                                                <td colspan="3">Formula</td>
                                              </tr>'



        SELECT @TableExport = @TableExport + '<tr><td colspan="2">' + CONVERT(varchar, id) + '</td>
		<td colspan="3">' + ISNULL(Title, '') + '</td><td colspan="3">' + ISNULL(Formula, '') + '</td></tr>'
        FROM sExamination.tPulmonaryObserved
        ORDER BY id


        SELECT @TableExport = @TableExport + '<tr><td colspan="8"></td></tr>
                                            <tr><td colspan="8"></td></tr>
                                            <tr><td colspan="8">Pulmonary Predicting Details:</td></tr>
											<tr><td>Sr No</td><td>Title</td><td>Age From</td><td>Age To</td>
                                            <td>Hight From</td><td>Hight To</td><td>Gender</td><td>Formula</td></tr>'

        SELECT @TableExport = @TableExport + '<tr>
					<td>' + CONVERT(varchar, ISNULL(Id, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(Title, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(AgeFrom, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(AgeTo, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(HightFrom, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(HightTo, '')) + '</td>
					<td>' + CASE
            WHEN CONVERT(varchar, ISNULL(GenderId, '1')) = '1' THEN 'Male'
            ELSE 'Female'
        END + '</td>
					<td>' + CONVERT(varchar, ISNULL(Formula, '')) + '</td>
					</tr>'
        FROM sExamination.tPulmonaryPredicting
        ORDER BY id

        SELECT @TableExport = @TableExport + '<tr><td colspan="8"></td></tr><tr><td colspan="8">
		</td></tr><tr><td colspan="8">Pulmonary Range Details:</td></tr><tr><td>Sr No</td><td colspan="2">Condition</td>
		<td>Condition Detail</td><td colspan="2">Intensity Condition</td><td>Intensity</td><td>Status</td></tr>'

        SELECT @TableExport = @TableExport + ' <tr> <td>' + CONVERT(varchar, ROW_NUMBER() OVER (Order by Id)) + '</td>
				<td colspan="2">' + ISNULL(Condition, '') + '</td>
				<td>' + ISNULL(ConditionDetail, '') + '</td>
				<td colspan="2">' + ISNULL(IntensityCondition, '') + '</td>
				<td>' + ISNULL(Intensity, '') + '</td>
				<td>' + ISNULL(Status, '') + '</td> </tr>'
        FROM sExamination.tPulmonaryRangeMaster
		Where (OrgId=case when @rOrgId=3001 then @rOrgId else 1 end)
        ORDER BY id
        SELECT PulmonaryObserved = @tPulmonaryObserved, PulmonaryPredicting = @tPulmonaryPredicting, PulmonaryRangeMaster = @tPulmonaryRangeMaster, TableExport = @TableExport, LEN(@TableExport)
    END
    ELSE
    IF (@rRangeTableId IN (0))
    BEGIN
        SELECT RangeDetails = ''
    END
END
GO
PRINT N'Altering Procedure [sExamination].[pArchieveExaminationDetaileGet]...';


GO

  -- exec [sExamination].[pArchieveExaminationDetaileGet] 9999000000831,8  
CREATE OR ALTER PROCEDURE [sExamination].[pArchieveExaminationDetaileGet]
@rId bigint,  
@rMainTyepId int  
AS  
SET NOCOUNT ON  
BEGIN  
 Declare @lPreviousDate datetime = '1900/01/01',@lExaminationDate datetime  
 Declare @lCriteriaGroupId int,@lTargetGroupId int  
 Declare @lEmployeeId bigint  
 SET @lCriteriaGroupId = (SELECT CriteiraGroupId FROM sExamination.tExamination Where Id = @rId)  
 SET @lTargetGroupId = (SELECT TargetGroupId FROM sExamination.tExamination Where Id = @rId)  
 SET @lEmployeeId = (SELECT ParticipantSourceId FROM sExamination.tExamination Where Id = @rId)  
 SET @lExaminationDate = (SELECT ExaminationDate FROM sExamination.tExamination Where Id = @rId)  
 SET @lPreviousDate =   
 (  
  SELECT ExaminationDate FROM   
  (  
   SELECT ExaminationDate,ROW_NUMBER() OVER(ORDER BY ExaminationDate desc) As RowNum  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId  
   INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId  
   where STM.MainTypeId = 1 AND E.ParticipantSourceId = @lEmployeeId  AND ExaminationDate < @lExaminationDate  
  ) As A  
  WHERE A.RowNum =1  
 )  
 IF((@rMainTyepId != 7) AND (@rMainTyepId != 8))  
 BEGIN  
  SELECT E.Id AS ExaminationId,  
  E.OrgId,  
  ST.MainTypeId,  
  MT.Title AS MainTypeName,  
  E.StoreLocationId,  
  SLM.Title AS StoreLocationName,  
  SLM.LocationId,  
  LM.Title AS LocationName,  
  OrganizationDepartmentId,  
  OD.Title AS DepartmentName,  
  E.SetupId,  
  SM.RoundNumber,  
  E.StatusId,  
  ExaminationDate,  
  ParticipantSourceTypeId,  
  ParticipantSourceId,  
  ISNULL(DoctorEmployeeId,0) AS DoctorEmployeeId,  
  ParticipantCode = CASE E.ParticipantSourceTypeId   
  WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
  ParticipantName =   
  CASE E.ParticipantSourceTypeId   
  WHEN 1009 THEN  
  (case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end)   
  WHEN 95 THEN EM.FirstName + ' ' + EM.LastName   
  WHEN 1001 THEN EFD.Name END,  
    
  RelationName = CASE E.ParticipantSourceTypeId WHEN  95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other' END,  
  GenderId = CASE E.ParticipantSourceTypeId WHEN 95 THEN EPD.GenderId  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN BM.GenderId END,  
  Gender = CASE E.ParticipantSourceTypeId WHEN 95 THEN GM.Title  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN GM2.Title END,  
  DateOfBirth = CASE E.ParticipantSourceTypeId WHEN 95 THEN ISNULL(EPD.DateOfBirth,'')  
  WHEN 1001 THEN ISNULL(EFD.DateOfBirth,'')  
  WHEN 1009 THEN ISNULL(BM.DateOfBirth,'') END,  
  Age = CASE E.ParticipantSourceTypeId  
  WHEN 95 THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1001 THEN ISNULL(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1009 THEN ISNULL(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) END,  
  isnull(EmployeeDesignationId,0) as EmployeeDesignationId,  
  isnull(E.ProcessTypeId,0) as ProcessTypeId,  
  SM.Title AS Setup,    
  isnull(Height,0) as Height,  
  EC.MobileNumber,  
  CompanyEmail,  
  SSM.Title as StatusName,  
  ISNULL(@lPreviousDate,'1900/01/01') AS PreviousDate,  
  ISNULL(@lCriteriaGroupId,0) AS CriteriaGroupId,  
  isnull(@lTargetGroupId,0) AS TargetGroupId  
  FROM sExamination.tArchieveExamination E  
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
  INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id  
  INNER JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id  
  INNER JOIN sIp.tStoreLocationMaster SLM on E.StoreLocationId = SLM.Id  
  INNER JOIN sCommon.tLocationMaster LM on SLM.LocationId = LM.Id  
  LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id  
  LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009  
  LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
  LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id  
  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId  
  LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on E.OrganizationDepartmentId = OD.Id  
  LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId  
  LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId  
  LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId  
  LEFT JOIN sExamination.tStatusMaster SSM on E.StatusId = SSM.Id  
  LEFT JOIN sExamination.tVital V on V.SourceId = E.Id   
  WHERE E.Id = @rId   
 END  
 ELSE  
 BEGIN  
  SELECT E.Id AS ExaminationId,  
  E.OrgId,  
  ST.MainTypeId,  
  MT.Title AS MainTypeName,  
  E.StoreLocationId,  
  SLM.Title AS StoreLocationName,  
  SLM.LocationId,  
  LM.Title AS LocationName,  
  OrganizationDepartmentId,  
  OD.Title AS DepartmentName,  
  E.SetupId,  
  SM.RoundNumber,  
  E.StatusId,  
  ExaminationDate,  
  ParticipantSourceTypeId,  
  ParticipantSourceId,  
  ISNULL(DoctorEmployeeId,0) AS DoctorEmployeeId,  
  ParticipantCode = CASE E.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
  ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN  
  (case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end)   
  WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,  
  RelationName = CASE E.ParticipantSourceTypeId WHEN  95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other' END,  
  GenderId = CASE E.ParticipantSourceTypeId WHEN 95 THEN EPD.GenderId  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN BM.GenderId END,  
  Gender = CASE E.ParticipantSourceTypeId WHEN 95 THEN GM.Title  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN GM2.Title END,  
  DateOfBirth = CASE E.ParticipantSourceTypeId WHEN 95 THEN ISNULL(EPD.DateOfBirth,'')  
  WHEN 1001 THEN ISNULL(EFD.DateOfBirth,'')  
  WHEN 1009 THEN ISNULL(BM.DateOfBirth,'') END,  
  Age = CASE E.ParticipantSourceTypeId  
  WHEN 95 THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1001 THEN ISNULL(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1009 THEN ISNULL(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) END,  
  isnull(EmployeeDesignationId,0) as EmployeeDesignationId,  
  isnull(E.ProcessTypeId,0) as ProcessTypeId,  
  SM.Title AS Setup,    
  isnull(Height,0) as Height,  
  EC.MobileNumber,  
  CompanyEmail,  
  SSM.Title as StatusName,  
  ISNULL(@lPreviousDate,'1900/01/01') AS PreviousDate,  
  ISNULL(@lCriteriaGroupId,0) AS CriteriaGroupId,  
  isnull(@lTargetGroupId,0) AS TargetGroupId  
  FROM sExamination.tArchieveExamination E  
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
  INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id  
  INNER JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id  
  INNER JOIN sIp.tStoreLocationMaster SLM on E.StoreLocationId = SLM.Id  
  INNER JOIN sCommon.tLocationMaster LM on SLM.LocationId = LM.Id  
  LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id  
  LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009  
  LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
  LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id  
  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId  
  LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on E.OrganizationDepartmentId = OD.Id  
  LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId  
  LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId  
  LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId  
  LEFT JOIN sExamination.tStatusMaster SSM on E.StatusId = SSM.Id  
  LEFT JOIN sExamination.tVital V on V.SourceId = E.Id   
  WHERE E.Id = @rId  
 END  
END
GO
PRINT N'Altering Procedure [sExamination].[pExaminationStatusDetail]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pExaminationStatusDetail]
	@rStoreLocationId int = 0,
	@rParticipantTypeId int = 0 ,
	@rCaseCauseId int = 0,
	@rLocationId int = 0,
	@rFunctionId int = 0,
	@rDepartmentGroupId int = 0,
	@rDepartmentId int = 0,
	@rGradeId int = 0,
	@rDesignationId int = 0,
	@rJobTitleId int=0,
	@rCompanyId int=0,
	@rContractorId int = 0,
	@rGenderId smallint=0,
	@rStatusId smallint=0,
	@rAgeFrom int=0,
	@rAgeTo int=100,
	@rFromDate date = null,
	@rToDate date = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rUserId bigint = 0,
	@rSectorId bigint = 0,
	@rVerticalId bigint = 0,
	@rCompnayGroupId bigint = 0,
	@rRoundGroupId bigint = 0,
	@rRoundId bigint = 0,
	@rEmployeeTypeGoupId bigint = 0,
	@rEmployeeTypeId bigint = 0,
	@rEmployeeSubTypeId bigint = 0,
	@rTargetGroupId int=0,

	--@rHealthIndexParameterId NVARCHAR(MAX) = '',
	@rHealthIndicatorId INT = 0,
	@rLocationMainGroupId INT = 0,
	@rLocationSubGroupId INT = 0,
	@rFromPercentage DEcimal(10,2)= -1,
	@rToPercentage DEcimal(10,2) = -1,
	@rMaINTypeId int = 1,
	@rCompanyGroupId int = 0,
	@rEmployeeCompanyId int = 0,
	@PageIndex int = 1
AS
BEGIN	
	
	IF OBJECT_ID('tempdb..#TEMPTableMain') IS NOT NULL
	DROP TABLE #TEMPTableMain

	Create TABLE #TEMPTableMain  (tid int Identity(1,1), StorelocationId int, Storelocation nvarchar(200),TotalFeezCnt int,TotalInProgressCnt int,TotalCompletedCnt int,TotalClosedCnt int,TotalNotStartedCnt int
	 ,OrgId int,VeryPoor decimal(10,2),Poor decimal(10,2),Fair decimal(10,2),Good decimal(10,2),Excellent decimal(10,2),Generated int,NotGenerated int,IndicatorName nvarchar(200),Percentage decimal(10,2),ClassicWell decimal(10,2),
	 ColorCode nvarchar(50), ColorCode1 nvarchar(50), ColorCode2 nvarchar(50), ColorCode3 nvarchar(50), ColorCode4 nvarchar(50), ColorCode5 nvarchar(50), ColorCode6 nvarchar(50))

	INSERT INTO #TEMPTableMain (StorelocationId,Storelocation,TotalFeezCnt,TotalInProgressCnt,TotalCompletedCnt,TotalClosedCnt,TotalNotStartedCnt)
	select SLM.Id,SLM.Title ,		
	isnull(a.TotalFeezCnt,0),
	isnull(b.[TotalInProgressCnt],0) ,
	isnull(c.[TotalCompletedCnt],0) ,
	isnull(d.[TotalClosedCnt],0)  ,
	isnull(f.[TotalNotStartedCnt],0)	
	
	from sIp.tStoreLocationMaster SLM
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SLM.Id and UL.UserId = @rUserId
	left join(	
	(select SL.ID,count(*) as TotalFeezCnt 
	from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	left join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	left join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) a on a.id = SLM.Id
	left join(
	(select SL.ID,count(*) as TotalInProgressCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	inner join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	E.StatusId = 1 and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as b on b.Id = SLM.Id
	left join(
	(select SL.ID,count(*) as TotalCompletedCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	inner join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	E.StatusId in (3,4) and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as c on c.Id = SLM.id
	left join(
	(select SL.ID,count(*) as TotalClosedCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	inner join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	E.StatusId in (5,6) and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as d on d.Id = SLM.id
	left join(
	(select SL.ID,count(*) as TotalNotStartedCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	left join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	( E.Id is null or E.StatusId=101) and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as f on f.Id = SLM.id
	
	where (SLM.Id = @rStoreLocationId or @rStoreLocationId = 0) and
	SLM.IsObsolete=0 and SLM.IsActiveHealth='1' and SLM.OrgId=@rOrgId

	---------------------------------------------------------START------------------------------------------------------------------

	--SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)

   IF OBJECT_ID('tempdb..#HealthIndicatorStatus') IS NOT NULL
	DROP TABLE #HealthIndicatorStatus

   IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
	DROP TABLE #TableOne


        DECLARE @count int = 0

        DECLARE @HealthIndicatorId TABLE (HealthIndicatorId int, OrgId int, ColorCode nvarchar(50))

        DECLARE @HealthIndicatorCount TABLE (Id int IDENTITY (1, 1),OrgId int)

        Create TABLE #HealthIndicatorStatus  (OrgId int,VeryPoor int,Poor int,Fair int,Good int,Excellent int,ClassicWell int,
		ColorCode1 nvarchar(50), ColorCode2 nvarchar(50), ColorCode3 nvarchar(50), ColorCode4 nvarchar(50), ColorCode5 nvarchar(50), ColorCode6 nvarchar(50))

        INSERT INTO @HealthIndicatorId
		Select t.HealthIndicatorId, t.Id, HIM.ColorCode from (
            SELECT (SELECT id FROM [sExamination].[tHealthIndicatorMaster]
            WHERE RangeTo >= CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints))))
            AND CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints)))) > RangeFrom)
            AS HealthIndicatorId,
            SLM.Id
            FROM sExamination.tExamination AS EXM
            INNER JOIN [sExamination].[tDiagnosis] AS DIA ON EXM.Id = DIA.SourceId
            INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
            INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
            INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID = EXM.ParticipantSourceId
            INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id = EXM.StoreLocationId
            INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id = SLM.LocationId
            INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID = EMP.OrgId
            INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
			--Change By Nidhi Pandey due to Health index location wise count mismatch; dt - 18/04/2022  (make below joins from INNER -> LEFT)
            LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId = EMP.ID
            LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId
            LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EXM.EmployeeCompanyId
            LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId
            LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId
            LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId
            LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
            LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id = DPT.DepartmentGroupId
            LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id = DPG.FunctionId
            LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId	  	     
			WHERE EXM.ParticipantSourceTypeId = 95
            AND EXM.OrgId = @rOrgId
            AND DIA.TotalHealthPoints > 0
            AND SSM.MainTypeId in (1,2)
			AND UL.UserId=@rUserId
            AND ((STM.SetupGroupId = @rRoundGroupId) OR (@rRoundGroupId = 0))
            AND ((EXM.SetupId = @rRoundId) OR (@rRoundId = 0))
            AND ((VTM.SectorId = @rSectorId) OR (@rSectorId = 0))
            AND ((CGM.VerticalId = @rVerticalId) OR (@rVerticalId = 0))
            AND ((ECM.CompanyGroupId = @rCompnayGroupId) OR (@rCompnayGroupId = 0))
            AND ((EJD.EmployeeCompanyId = @rCompanyId) OR (@rCompanyId = 0))
            --AND ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
            AND ((EXM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
            AND ((DPG.FunctionId = @rFunctionId) OR (@rFunctionId = 0))
            AND ((DPT.DepartmentGroupId = @rDepartmentGroupId) OR (@rDepartmentGroupId = 0))
            AND ((EXM.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
            AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
			AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))                                    
			AND ((EPD.GenderId = @rGenderId) OR (@rGenderId = 0))			                                    
            AND ((EXM.GradeId = @rGradeId) OR (@rGradeId = 0))			                                    
			AND ((EXM.TargetGroupId = @rTargetGroupId) OR (@rTargetGroupId = 0))			                                    
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR @rEmployeeTypeId = 0)
			AND ((EJD.EmployeeGroupId = @rEmployeeTypeGoupId) OR (@rEmployeeTypeGoupId = 0))
			AND ((EJD.EmployeeSubTypeId = @rEmployeeSubTypeId) OR (@rEmployeeSubTypeId = 0))
			GROUP BY EMP.ID, SLM.Id
			) t
			INNER JOIN [sExamination].[tHealthIndicatorMaster] HIM ON HIM.Id = t.HealthIndicatorId
			option(Recompile)
        INSERT INTO @HealthIndicatorCount 
		SELECT OrgId FROM @HealthIndicatorId GROUP BY OrgId

        SELECT @count = COUNT(0) FROM @HealthIndicatorCount

        WHILE (@count <> 0)
        BEGIN
            DECLARE @myOrgId bigint = 0
            SELECT @myOrgId = OrgId
            FROM @HealthIndicatorCount
            WHERE id = @count
            INSERT INTO #HealthIndicatorStatus

                SELECT @myOrgId, (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 1 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 2 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 3 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 4 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 5 AND OrgId = @myOrgId)
				, (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 6 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 1 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 2 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 3 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 4 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 5 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 6 AND OrgId = @myOrgId)

            SET @count = @count - 1
        END


        Create TABLE #TableOne (tid int IDENTITY (1, 1),RowID nvarchar(50),OrgId bigint,OrganizationName nvarchar(250),TotalPoints decimal(10, 2),EarnedPoints decimal(10, 2),Percentage decimal(10, 2),IndicatorName nvarchar(250),TotalEmployee int, ColorCode nvarchar(50))
        INSERT INTO #TableOne
		select P.RowID, P.OrgId, P.OrganizationName, P.TotalPoints, P.EarnedPoints, P.Percentage, 
		(CASE WHEN ISNULL(HIM.HealthIndicatorLabel, '') != '' and HIM.IsObsolete = 0 THEN HIM.HealthIndicatorLabel ELSE HIM.Title END) as IndicatorName, 
		P.TotalEmployee, HIM.ColorCode from (
            SELECT CONVERT(nvarchar(50), REPLACE(NEWID(), '-', '')) AS RowID
            , SLM.Id AS OrgId
            , SLM.Title AS OrganizationName
            , SUM(DIA.TotalHealthPoints) TotalPoints
            , SUM(DIA.EarnedHealthPoints) EarnedPoints
            , CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints)))) AS Percentage
            , ISNULL((
				SELECT Id FROM [sExamination].[tHealthIndicatorMaster] 
				WHERE RangeTo >= CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints))))
				AND CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints)))) > RangeFrom
				),'')
            AS IndicatorId
            , COUNT(0) AS TotalEmployee
            FROM sExamination.tExamination AS EXM
            INNER JOIN [sExamination].[tDiagnosis] AS DIA ON EXM.Id = DIA.SourceId
            INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
            INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
            INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID = EXM.ParticipantSourceId
            INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id = EXM.StoreLocationId
            INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id = SLM.LocationId
            INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID = EMP.OrgId
			INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
			--Change By Nidhi Pandey due to Health index location wise count mismatch; dt - 18/04/2022  (make below joins from INNER -> LEFT)
            LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId = EMP.ID
            LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId
            LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EXM.EmployeeCompanyId
            LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId
            LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId
            LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId
            LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
            LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id = DPT.DepartmentGroupId
            LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id = DPG.FunctionId
            LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId	  	 
			WHERE EXM.ParticipantSourceTypeId = 95
            AND EXM.OrgId = @rOrgId
            AND DIA.TotalHealthPoints > 0
            AND SSM.MainTypeId in (1,2)
			AND UL.UserId=@rUserId
            AND ((STM.SetupGroupId = @rRoundGroupId) OR (@rRoundGroupId = 0))
            AND ((EXM.SetupId = @rRoundId) OR (@rRoundId = 0))
            AND ((VTM.SectorId = @rSectorId) OR (@rSectorId = 0))
            AND ((CGM.VerticalId = @rVerticalId) OR (@rVerticalId = 0))
            AND ((ECM.CompanyGroupId = @rCompnayGroupId) OR (@rCompnayGroupId = 0))
            AND ((EJD.EmployeeCompanyId = @rCompanyId) OR (@rCompanyId = 0))
            --AND ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
            AND ((EXM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
            AND ((DPG.FunctionId = @rFunctionId) OR (@rFunctionId = 0))
            AND ((DPT.DepartmentGroupId = @rDepartmentGroupId) OR (@rDepartmentGroupId = 0))
            AND ((EXM.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
            AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
            AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
			AND ((EPD.GenderId = @rGenderId) OR (@rGenderId = 0))			                                    
            AND ((EXM.GradeId = @rGradeId) OR (@rGradeId = 0))	
			AND ((EXM.TargetGroupId = @rTargetGroupId) OR (@rTargetGroupId = 0))
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR @rEmployeeTypeId = 0)
			AND ((EJD.EmployeeGroupId = @rEmployeeTypeGoupId) OR (@rEmployeeTypeGoupId = 0))
			AND ((EJD.EmployeeSubTypeId = @rEmployeeSubTypeId) OR (@rEmployeeSubTypeId = 0))			                                    
			GROUP BY SLM.Id, SLM.Title
			) P
			INNER JOIN [sExamination].[tHealthIndicatorMaster] HIM ON HIM.Id = P.IndicatorId
            ORDER BY P.OrgId
			option(Recompile)

			--select * from #TableOne
			--select * from #HealthIndicatorStatus
  --      DECLARE @lReslutGridOrganization varchar(max) = ''

		--SELECT @lReslutGridOrganization = @lReslutGridOrganization + '<tr>
		--	<td style="width: 20%;">' + ISNULL(OrganizationName, '') + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(TotalEmployee, 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(Percentage, 0)) + '</td>
		--	<td style="width: 10%; ">' + ISNULL(IndicatorName, '') + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Excellent * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Good * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Fair * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Poor * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.VeryPoor * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	</tr>'
  --      FROM #TableOne AS t 
		--INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId
		--order by OrganizationName
		--option(Recompile)


		--IF (@lReslutGridOrganization <> '')
		--BEGIN
			
		--	Declare @Header nvarchar(max)=' <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 98%; border-collapse: collapse;"><thead>
  --                                          <tr>
  --                                              <td>Sub Location</td>
  --                                              <td style="text-align: right;">Total Employee</td>
  --                                              <td style="text-align: right;">Health Index (%)</td>
  --                                              <td>Indicator</td>
  --                                              <td style="text-align: right;">Very Healthy (%)</td>
  --                                              <td style="text-align: right;">Healthy (%)</td>
  --                                              <td style="text-align: right;">Low Risk (%)</td>
  --                                              <td style="text-align: right;">Moderate Risk (%)</td>
  --                                              <td style="text-align: right;">High Risk (%)</td>
  --                                          </tr></thead>'
			


		--	SELECT @Header+''+@lReslutGridOrganization +'</table>' AS ResultGrid
		--END
		--ELSE
		--BEGIN
		--	SELECT '' AS ResultGrid
		--END
		
		--DECLARE @MainCount int = (Select count(*) from #TEMPTableMain)
		--Declare @lStoreLocationId int = '';
		--While(@MainCount < 0)
		--BEGIN
		--	Select @lStoreLocationId = StoreLocationId from #TEMPTableMain where tid = @MainCount

		--	if Exists(Select 1 from #TableOne AS t
		--	INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId where t.OrgId = @lStoreLocationId)
		--	BEGIN
		--		Update #TEMPTableMain set  
				
		--		Excellent = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Excellent * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		Good = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Good * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		Fair = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Fair * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		Poor = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Poor * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		VeryPoor = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.VeryPoor * 100) / CONVERT(decimal(18, 2), TotalEmployee))
		--		FROM #TableOne AS t
		--		INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId where t.OrgId  = @lStoreLocationId
		--	END
			

		--	Set @MainCount = @MainCount - 1
		--END

		Update #TEMPTableMain
		Set Excellent = ISNULL(tExcellent,0), Good = ISNULL(tGood,0) , Fair = ISNULL(tFair,0), Poor = ISNULL(tPoor,0), VeryPoor = ISNULL(tVeryPoor,0),
		IndicatorName = ISNULL(t1.IndicatorName,''),Percentage = ISNULL(t1.Percentage,0),OrgId = ISNULL(t1.OrgId,0),ClassicWell = ISNULL(t1.tClassicWell,0),
		ColorCode = ISNULL(t1.ColorCode,0), ColorCode1 = ISNULL(t1.ColorCode1,0), ColorCode2 = ISNULL(t1.ColorCode2,0), ColorCode3 = ISNULL(t1.ColorCode3,0), 
		ColorCode4 = ISNULL(t1.ColorCode4,0), ColorCode5 = ISNULL(t1.ColorCode5,0), ColorCode6 = ISNULL(t1.ColorCode6,0)
		From (
		Select t.*, CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Excellent * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tExcellent,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Good * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tGood,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Fair * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tFair ,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Poor * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tPoor ,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.VeryPoor * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tVeryPoor,				 
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.ClassicWell * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tClassicWell,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode1, '')) as ColorCode1,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode2, '')) as ColorCode2,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode3, '')) as ColorCode3,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode4, '')) as ColorCode4,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode5, '')) as ColorCode5,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode6, '')) as ColorCode6
				FROM #TableOne AS t
				INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId ) as t1 where t1.OrgId  = #TEMPTableMain.StoreLocationId

	    

        --option(Recompile)
			
  Drop table #HealthIndicatorStatus   
  Drop table #TableOne


	--------------------------------------------------------- END -------------------------------------------------------------------
	
	
	--------------------------------------------------------- Start -------------------------------------------------------------------

	

	IF(@rToDate='')
	BEGIN
		SET @rToDate='01/06/2050'
	END
	

	DECLARE @EmployeeCode nVarchar(100)=''
	DECLARE @lReslutGridOrganization varchar(max)='',@lpaging varchar(max)=''
	DECLARE	@PageSize INT=50

	Select Distinct EXM.ID,EXM.SetupId,EXM.ParticipantSourceId,EXM.EmployeeCompanyId,EXM.StoreLocationId,
	EXM.OrganizationDepartmentId,EXM.ParticipantSourceTypeId,EXM.OrgId,EXM.ExaminationDate,EXM.GradeId
	 INto #tmp 
	FROM sExamination.tExamination AS EXM
	INNER JOIN sExamination.tHealthIndex AS HI ON HI.ExaminationId=EXM.Id
	--INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIP ON HIP.ID = HI.HealthIndexParameterId	
	INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId
	INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId
	INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	CROSS APPLY (
		SELECT TOP 1 HIM.Id
		FROM sExamination.tHealthIndicatorMaster AS HIM
		WHERE (HI.EarnedPoints * 100.0 / NULLIF(HI.TotalPoints,0)) > HIM.RangeFrom
			AND (HI.EarnedPoints * 100.0 / NULLIF(HI.TotalPoints,0)) <= HIM.RangeTo
	) AS HIA
	WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId
	AND HI.TotalPoints>0 AND SSM.MaINTypeId=@rMaINTypeId
	--AND (((SELECT Id FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	--AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) =@rHealthIndicatorId) OR (@rHealthIndicatorId=0))
	AND (HIA.Id = @rHealthIndicatorId OR @rHealthIndicatorId=0)
	AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	--AND ((HIP.ID in ((select Item from dbo.fSplitStr(@rHealthIndexParameterId,',') where Item <> ''))) OR (@rHealthIndexParameterId=''))
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rCompanyId) OR (@rCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code LIKE @rEmployeeCode) OR (@rEmployeeCode  = ''))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) >= @rFromPercentage) OR (@rFromPercentage = -1))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) <= @rToPercentage) OR (@rToPercentage = -1))
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	AND UL.UserId = @rUserId 
	--AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	--AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)

	DECLARE @GeneratedCountSQL NVARCHAR(MAX) = N'';

	SET @GeneratedCountSQL = N'
	UPDATE TM
	SET Generated = t.GeneratedCount
	FROM #TEMPTableMain AS TM
	INNER JOIN (
		SELECT 
			COUNT(1) AS GeneratedCount,
			SLM.Id AS StoreLocationId
		FROM #tmp AS EXM
		INNER JOIN sExamination.tHealthIndex AS HI 
			ON HI.ExaminationId = EXM.Id
		CROSS APPLY (
			SELECT 
				CAST(
					(CAST(HI.EarnedPoints AS DECIMAL(18,2)) * 100.0) /
					NULLIF(CAST(HI.TotalPoints AS DECIMAL(18,2)),0)
				AS DECIMAL(18,2)) AS Percentage
		) AS P
		INNER JOIN sExamination.tSetupMaster AS STM 
			ON STM.ID = EXM.SetupId
		INNER JOIN sExamination.tSetupGroupMaster AS SGM 
			ON SGM.Id = STM.SetupGroupId
		INNER JOIN sExamination.tSubTypeMaster AS SSM 
			ON SSM.Id = STM.SubTypeId
		INNER JOIN sHrm.tEmployeeMaster AS EMP 
			ON EMP.ID = EXM.ParticipantSourceId
		INNER JOIN sHrm.tEmployeeJobDetail AS EJD 
			ON EJD.EmployeeId = EMP.ID
		INNER JOIN sHrm.tEmployeePersonalDetail AS EPD 
			ON EMP.Id = EPD.EmployeeId
		LEFT JOIN sHrm.tEmployeeCompanyMaster AS ECM 
			ON ECM.Id = EXM.EmployeeCompanyId
		LEFT JOIN sHrm.tCompanyGroupMaster AS CGM 
			ON CGM.Id = ECM.CompanyGroupId
		LEFT JOIN sHrm.tVerticalMaster AS VTM 
			ON VTM.ID = CGM.VerticalId
		LEFT JOIN sHrm.tSectorMaster AS SCT 
			ON SCT.Id = VTM.SectorId
		LEFT JOIN sCommon.tCompanyInformation AS CMP 
			ON CMP.ID = SCT.OrgId
		LEFT JOIN sIp.tStoreLocationMaster AS SLM 
			ON SLM.Id = EXM.StoreLocationId
		LEFT JOIN sCommon.tLocationMaster AS LMN 
			ON LMN.Id = SLM.LocationId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster AS DPT 
			ON DPT.Id = EXM.OrganizationDepartmentId
		LEFT JOIN sCommon.tDepartmentGroupMaster AS DPG 
			ON DPG.Id = DPT.DepartmentGroupId
		LEFT JOIN sCommon.tFunctionMaster AS FCN 
			ON FCN.Id = DPG.FunctionId
		LEFT JOIN sCommon.tLocationSubGroupMaster AS LSG 
			ON LSG.Id = LMN.LocationSubGroupId
		LEFT JOIN sCommon.tLocationMainGroupMaster AS LMG 
			ON LMG.Id = LSG.LocationMainGroupId
		LEFT JOIN sHrm.tGradeMaster AS GRD 
			ON EJD.GradeId = GRD.Id
		INNER JOIN sSecurity.tUserLocation AS UL 
			ON EXM.StoreLocationId = UL.StoreLocationId
		LEFT JOIN sExamination.tHealthIndicatorMaster AS HIM
			ON P.Percentage BETWEEN HIM.RangeFrom AND HIM.RangeTo
		WHERE ((EXM.ParticipantSourceTypeId = 0) OR (0=0))  
		  AND EXM.OrgId = @rOrgId
		  AND HI.TotalPoints > 0 
		  AND SSM.MainTypeId = @rMainTypeId';

	-- Only add filters if parameters are set
	IF @rHealthIndicatorId <> 0
		SET @GeneratedCountSQL += ' AND HIM.Id = @rHealthIndicatorId';

	IF @rRoundGroupId <> 0
		SET @GeneratedCountSQL += ' AND STM.SetupGroupId = @rRoundGroupId';

	IF @rRoundId <> 0
		SET @GeneratedCountSQL += ' AND EXM.SetupId = @rRoundId';

	IF @rSectorId <> 0
		SET @GeneratedCountSQL += ' AND VTM.SectorId = @rSectorId';

	IF @rVerticalId <> 0
		SET @GeneratedCountSQL += ' AND CGM.VerticalId = @rVerticalId';

	IF @rCompanyGroupId <> 0
		SET @GeneratedCountSQL += ' AND ECM.CompanyGroupId = @rCompanyGroupId';

	IF @rEmployeeCompanyId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeCompanyId = @rEmployeeCompanyId';

	IF @rLocationId <> 0
		SET @GeneratedCountSQL += ' AND SLM.LocationId = @rLocationId';

	IF @rStoreLocationId <> 0
		SET @GeneratedCountSQL += ' AND EXM.StoreLocationId = @rStoreLocationId';

	IF @rFunctionId <> 0
		SET @GeneratedCountSQL += ' AND DPG.FunctionId = @rFunctionId';

	IF @rDepartmentGroupId <> 0
		SET @GeneratedCountSQL += ' AND DPT.DepartmentGroupId = @rDepartmentGroupId';

	IF @rDepartmentId <> 0
		SET @GeneratedCountSQL += ' AND EXM.OrganizationDepartmentId = @rDepartmentId';

	IF @rEmployeeCode <> ''
		SET @GeneratedCountSQL += ' AND EMP.Code = @rEmployeeCode';

	IF @rFromPercentage <> -1
		SET @GeneratedCountSQL += ' AND P.Percentage >= @rFromPercentage';

	IF @rToPercentage <> -1
		SET @GeneratedCountSQL += ' AND P.Percentage <= @rToPercentage';

	IF @rLocationSubGroupId <> 0
		SET @GeneratedCountSQL += ' AND LSG.Id = @rLocationSubGroupId';

	IF @rLocationMainGroupId <> 0
		SET @GeneratedCountSQL += ' AND LMG.Id = @rLocationMainGroupId';

	IF ISNULL(@rFromDate,'') <> ''
		SET @GeneratedCountSQL += ' AND EXM.ExaminationDate >= @rFromDate';

	IF ISNULL(@rToDate,'') <> ''
		SET @GeneratedCountSQL += ' AND EXM.ExaminationDate <= @rToDate';

	IF @rGradeId <> 0
		SET @GeneratedCountSQL += ' AND EXM.GradeId = @rGradeId';

	IF @rGenderId <> 0
		SET @GeneratedCountSQL += ' AND EPD.GenderId = @rGenderId';

	IF @rEmployeeTypeId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeTypeId = @rEmployeeTypeId';

	IF @rEmployeeTypeGoupId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeGroupId = @rEmployeeTypeGoupId';

	IF @rEmployeeSubTypeId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeSubTypeId = @rEmployeeSubTypeId';

	SET @GeneratedCountSQL += '
		  AND UL.UserId = @rUserId
		GROUP BY SLM.Id
	) AS t
	ON TM.StoreLocationId = t.StoreLocationId
	';

	-- Execute
	EXEC sp_executesql 
    @GeneratedCountSQL,
    N'@rStoreLocationId INT, @rParticipantTypeId INT, @rCaseCauseId INT, 
      @rLocationId INT, @rFunctionId INT, @rDepartmentGroupId INT, 
      @rDepartmentId INT, @rGradeId INT, @rDesignationId INT, 
      @rJobTitleId INT, @rCompanyId INT, @rContractorId INT, 
      @rGenderId SMALLINT, @rStatusId SMALLINT, 
      @rAgeFrom INT, @rAgeTo INT, @rFromDate DATE, @rToDate DATE, 
      @rOrgId INT, @rEmployeeCode NVARCHAR(50), 
      @rUserId BIGINT, @rSectorId INT, @rVerticalId INT, 
      @rCompnayGroupId INT, @rRoundGroupId INT, 
      @rRoundId INT, @rEmployeeTypeGoupId INT, 
      @rEmployeeTypeId INT, @rEmployeeSubTypeId INT, 
      @rTargetGroupId INT, @rHealthIndicatorId INT, 
      @rLocationMainGroupId INT, @rLocationSubGroupId INT, 
      @rFromPercentage DECIMAL(10,2), @rToPercentage DECIMAL(10,2), 
      @rMaINTypeId INT, @rCompanyGroupId INT, 
      @rEmployeeCompanyId INT, @PageIndex INT',
    @rStoreLocationId, @rParticipantTypeId, @rCaseCauseId, 
    @rLocationId, @rFunctionId, @rDepartmentGroupId, 
    @rDepartmentId, @rGradeId, @rDesignationId, 
    @rJobTitleId, @rCompanyId, @rContractorId, 
    @rGenderId, @rStatusId, 
    @rAgeFrom, @rAgeTo, @rFromDate, @rToDate, 
    @rOrgId, @rEmployeeCode, 
    @rUserId, @rSectorId, @rVerticalId, 
    @rCompnayGroupId, @rRoundGroupId, 
    @rRoundId, @rEmployeeTypeGoupId, 
    @rEmployeeTypeId, @rEmployeeSubTypeId, 
    @rTargetGroupId, @rHealthIndicatorId, 
    @rLocationMainGroupId, @rLocationSubGroupId, 
    @rFromPercentage, @rToPercentage, 
    @rMaINTypeId, @rCompanyGroupId, 
    @rEmployeeCompanyId, @PageIndex;

	

	--update #TEMPTableMain set 
	--Generated = t.GeneratedCount from (
	--Select Count(1) as GeneratedCount,SLM.Id as StoreLocationId 
	--FROM #tmp AS EXM
	----INNER JOin #tmp E On E.id=EXM.id
	--INNER JOIN sExamination.tHealthIndex AS HI ON HI.ExaminationId=EXM.Id
	----INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIP ON HIP.ID = HI.HealthIndexParameterId	
	--INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId
	--INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId
	--INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
	--INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	--INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	--INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	--LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	--LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	--LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	--LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	--LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	--LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	--LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	--LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	--LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	--LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	--LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	--LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	--LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	--INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	--WHERE ((EXM.ParticipantSourceTypeId = 0) OR (0=0))  AND EXM.OrgId=@rOrgId
	--AND HI.TotalPoints>0 AND SSM.MaINTypeId=@rMaINTypeId
	--AND (((SELECT Id FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	--AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) =@rHealthIndicatorId) OR (@rHealthIndicatorId=0))
	--AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	--AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	--AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	--AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	----AND ((HIP.ID in ((select Item from dbo.fSplitStr(@rHealthIndexParameterId,',') where Item <> ''))) OR (@rHealthIndexParameterId=''))
	--AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	--AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	--AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	--AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	--AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	--AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	--AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	--AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	--AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) >= @rFromPercentage) OR (@rFromPercentage = -1))
	--AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) <= @rToPercentage) OR (@rToPercentage = -1))
	--AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	--AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	
	--AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	--AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))	
	--AND(EXM.GradeId=@rGradeId OR @rGradeId=0)
	--AND(EPD.GenderId = @rGenderId OR @rGenderId=0)
	--AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	--AND (EJD.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	--AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	--AND UL.UserId = @rUserId
	--Group By SLM.Id
	--) as t where #TEMPTableMain.StorelocationId = t.StorelocationId
	----Group by SLM.Id, SLM.Title

	Drop Table #tmp

	--------------------------------------------------------- END -------------------------------------------------------------------		
	
	
	--------------------------------------------------------- Start -------------------------------------------------------------------		
	

	DECLARE @GeneralCols varchar(max) = '', @GeneralCols1 varchar(max) = '', @lQueryExisting varchar(max), @GeneralCols2 varchar(max)
    SELECT @GeneralCols = STUFF((SELECT
        ',' + QUOTENAME(sCommon.fGetIntIdForOrg(Id, @rOrgId))
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    FOR xml PATH (''), TYPE)
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')


	print '1'

    SELECT @GeneralCols1 = STUFF((SELECT
        ',' + QUOTENAME(Code) + ' varchar(300)'
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    FOR xml PATH (''), TYPE)
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')


	print '1'

    SELECT @GeneralCols2 = STUFF((SELECT
        ',' + QUOTENAME(Code)
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    FOR xml PATH (''), TYPE)
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')

    DECLARE @Header nvarchar(max) = '<tr style="background-color: #f9f9f9;"><th>Code</th><th>Name</th><th>Grade</th><th>Total Points</th><th>Earned Points</th><th>HealthIndex</th><th>Indicator</th>'
    SELECT @Header = @Header + '<th>' + code + '</th>'
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE Id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    SELECT @Header = @Header + '</tr>'


    IF OBJECT_ID('tempdb..#tblExamination') IS NOT NULL
        DROP TABLE #tblExamination


    CREATE TABLE #tblExamination (tid int IDENTITY (1, 1),ExaminationId bigint,EarnedPoints int,HealthIndexParameterId int,Code varchar(100))

    INSERT INTO #tblExamination
        SELECT H.ExaminationId, EarnedPoints, HealthIndexParameterId, HM.Code
        FROM sExamination.tHealthIndexPartial H
        INNER JOIN sExamination.tHealthIndexParameterMaster HM ON H.HealthIndexParameterId = HM.Id
        INNER JOIN sExamination.tStaticHealthIndexParameterMaster AS s ON s.Id = hm.StaticHealthIndexParameterId
        INNER JOIN sExamination.tExamination AS EXM ON H.ExaminationId = EXM.Id
        INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
        INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id = STM.SetupGroupId
        INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
        INNER JOIN sExamination.tDiagnosisPartial AS DIA ON EXM.Id = DIA.ExaminationId
        INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	
        WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId
	AND SSM.MaINTypeId=@rMaINTypeId	
	AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023
	AND UL.UserId = @rUserId 
        AND s.Id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
	


    IF OBJECT_ID('tempdb..##tblMainTableStatus') IS NOT NULL
        DROP TABLE ##tblMainTableStatus

    SELECT @lQueryExisting = 'create table ##tblMainTableStatus(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'
    EXEC (@lQueryExisting)

    SELECT @lQueryExisting = '
    insert into ##tblMainTableStatus	
	select ExaminationId,' + @GeneralCols2 + '
	from
	(
		select ExaminationId,EarnedPoints,Code from #tblExamination
	) src 
	pivot
	(
	  max(EarnedPoints) for Code in (' + @GeneralCols2 + ')
	) piv;'

	print @lQueryExisting
    EXEC (@lQueryExisting)

	UPDATE #TEMPTableMain set 
	NotGenerated = ISNULL(t.NotGeneratedCount,0)
	from 
	(Select Count(1) as NotGeneratedCount,SLM.Id as StoreLocationId 
	
    FROM ##tblMainTableStatus AS m
    INNER JOIN sExamination.tExamination AS EXM ON m.d_ExamId = EXM.Id
    INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
    INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id = STM.SetupGroupId
    INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
    INNER JOIN [sExamination].[tDiagnosisPartial] AS DIA ON EXM.Id = DIA.ExaminationId
    INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId	
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
    LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId
    WHERE ((EXM.ParticipantSourceTypeId = 0) OR (0=0))
    --AND SSM.MaINTypeId=@rMaINTypeId	
	AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	
	AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(EXM.GradeId=@rGradeId OR @rGradeId=0)
	AND(EPD.GenderId = @rGenderId OR @rGenderId=0)
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (EJD.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)	
	AND UL.UserId = @rUserId 
    Group By SLM.Id) as t where #TEMPTableMain.StorelocationId = t.StorelocationId

	DECLARE @sql NVARCHAR(MAX);
	Declare @rHighRiskLabel nvarchar(20), @rModerateRiskLabel nvarchar(20), @rLowRiskLabel nvarchar(20), 
	@rHealthyLabel nvarchar(20), @rVeryHealthyLabel nvarchar(20), @rClassicWellLabel nvarchar(20);
	set @rHighRiskLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '1') + ' (%)'
	set @rModerateRiskLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '2') + ' (%)'
	set @rLowRiskLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '3') + ' (%)'
	set @rHealthyLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '4') + ' (%)'
	set @rVeryHealthyLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '5') + ' (%)'
	set @rClassicWellLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '6') + ' (%)'

	SET @sql = N'
    SELECT  
        Storelocation AS [Sub Location],
        TotalFeezCnt AS [Total Freezed Employee],
        TotalInProgressCnt AS [InProgress],
        TotalCompletedCnt AS Completed,
        TotalClosedCnt AS Closed,
        TotalNotStartedCnt AS [Not Started],
        Generated,
        NotGenerated AS [Not Generated],
        Percentage AS [Health Index (%)],
        IndicatorName AS Indicator,
        ClassicWell AS ' + QUOTENAME(@rClassicWellLabel) + ',
        Excellent AS ' + QUOTENAME(@rVeryHealthyLabel) + ',
        Good AS ' + QUOTENAME(@rHealthyLabel) + ',
        Fair AS ' + QUOTENAME(@rLowRiskLabel) + ',
        Poor AS ' + QUOTENAME(@rModerateRiskLabel) + ',
        VeryPoor AS ' + QUOTENAME(@rHighRiskLabel) + N'
    FROM #TEMPTableMain;';

	EXEC sp_executesql @sql;

	 Select ColorCode,
	 ColorCode1,
	 ColorCode2,
	 ColorCode3,
	 ColorCode4,
	 ColorCode5,
	 ColorCode6
	 from #TEMPTableMain

	Drop table #TEMPTableMain
	IF OBJECT_ID('tempdb..##tblMainTableStatus') IS NOT NULL
        DROP TABLE ##tblMainTableStatus
	--------------------------------------------------------- END -------------------------------------------------------------------		
END
GO
PRINT N'Altering Procedure [sExamination].[pGetWellnessVisitPurposeDropdown]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetWellnessVisitPurposeDropdown]
@rOrgId int
AS
BEGIN
	select Id,Title from sWellness.tWellnessVisitPurposeMaster
	where IsObsolete = 0 and OrgId = @rOrgId
END
GO
PRINT N'Altering Procedure [sExamination].[pRptOpdPrescriptionList]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pRptOpdPrescriptionList]
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rReportId int,
@rStoreLocationId int,
@rParticipantTypeId int,
@rCaseCauseId int,
@rLocationId int,
@rFunctionId int,
@rDepartmentGroupId int,
@rDepartmentId int,
@rGradeId int,
@rDesignationId int,
@rJobTitleId int,
@rEmployeeTypeId int,
@rCompanyId int,
@rContractorId int,
@rGenderId smallint,
@rStatusId int,
@rAgeFrom int=0,
@rAgeTo int=100,
@rFromDate date = null,
@rToDate datetime = null,
@rOrgId int,
@rEmployeeCode nvarchar(50)='',
@rEmployeeTypeGroupId int=0,
@rEmployeeSubTypeId int=0,
@rEmployeeGroupId int=0,
@rOtherTypeId int=0,
@rExaminationId bigint=0,
@rLogo bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN 

	-- Validate @rEmployeeCode entries
    IF EXISTS 
    (
        SELECT SplitValues.item
        FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
        WHERE NOT EXISTS 
        (
            SELECT 1 FROM sHrm.tEmployeeMaster EM WHERE EM.Code = SplitValues.item
            UNION
            SELECT 1 FROM sHrm.tCsrBenefiterMaster BM WHERE BM.Code = SplitValues.item
        )
    )
    BEGIN
        RAISERROR('One or more Employee Codes are invalid / Not Exists.', 16, 1);
        RETURN;
    END

	select @rAgeTo = case when @rAgeTo = '' or @rAgeTo = 100 then 1000 end
	select @rAgeFrom = case when @rAgeFrom = '' then 0 end	

	Declare @rConfig varchar(10), @rConfig1 varchar(10);

	Set @rConfig = (select sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius',@rOrgId,0,0,0))

	Set @rConfig1 = (case @rConfig When 'true' Then '°C' Else '°F' END)

	--DECLARE @TestTable TABLE (TestName varchar(200))
	--declare @results varchar(Max) 

	--INSERT INTO @TestTable
	--select TPM.Title from sExamination.tTestRequest TR
	--inner join sOrderEntry.tTestDetail OTD on TR.TestId = OTD.TestId
	--inner join sExamination.tTestRequestDetail TD on TR.Id = TD.TestRequestId and TD.TestDetailId = OTD.Id
	--inner join  sOrderEntry.tTestParameterMaster TPM on TPM.Id = OTD.TestParameterId 
	--where  TR.OrgId = @rOrgId and sourceid = @rExaminationId
	--Order by TPM.Title

	--select @results = coalesce(@results + ', ', '') +  convert(varchar(200),TestName) from @TestTable

	select EED.Id AS ExaminationId,
	EP.Id as prescriptionId,
	ParticipantCode = CASE EED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	ParticipantName = CASE EED.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	PatientCategory = CASE EED.ParticipantSourceTypeId WHEN 95 THEN isnull(ETM.Title,'') WHEN 1001 THEN isnull(RM.Title,'') WHEN 1009 THEN isnull(BTM.Title,'') END,
	--Gender = CASE EED.ParticipantSourceTypeId
	--WHEN 95 THEN GM.Title
	--WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	--WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE isnull((SELECT Title FROM sCommon.tGenderMaster where O.GenderId = Id),'') END END,
	Gender = CASE EED.ParticipantSourceTypeId
	WHEN 95 THEN GM.Title
	WHEN 1001 THEN ISNULL(GM3.Title,'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE isnull((SELECT Title FROM sCommon.tGenderMaster where O.GenderId = Id),'') END END,
	
	--EED.CreatedDateTime as ExaminationDate,
	
	case when isnull(O.OPDTime,'')='' then convert(varchar,EED.CreatedDateTime,103) else convert(varchar,EED.CreatedDateTime,103)  end as ExaminationDate,
	isnull(O.OPDOutTime,'') as OPDOutTime,
	
	Age = CASE EED.ParticipantSourceTypeId WHEN 95 THEN isnull(datediff(yy,PD.DateOfBirth,sCommon.fGetDate()),0)
	WHEN 1001 THEN isnull(datediff(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) WHEN 1009 THEN isnull(O.Age,isnull(datediff(yy,BM.DateOfBirth,sCommon.fGetDate()),0)) end,
	V.Pulse,
	convert(varchar(20),V.Temperature) + convert(varchar(20),@rConfig1) as Temperature,
	V.BloodPressureSystolic,
	V.BloodPressureDiastolic,
	R.ContactPerson,
	O.OutsideMedicine,
	O.OutsideTest,
	[sExamination].[fExistingDiseaseGet](EED.Id) AS Diagnosis,
	(select top 1 isnull(Remark,'') from sExamination.tComplaint where SourceId = EED.Id) as problems,
	case when isnull(EPD.DrugInstruction,'') = '' then SM.Title else EPD.DrugInstruction end as DrugInstruction,
	SIM.Title as Medicines,
	convert(varchar(20),EPD.Dosage) as MedicineQty,
	convert(varchar(20),EPD.DispensedQuantity)DispensedQuantity,
	convert(varchar,EPD.Duration)Duration,
	convert(varchar(20),EPD.PrescribedQuantity)PrescribedQuantity,
	EED.ParticipantSourceId,
	Isnull(SIM.Id,0) as StockId,
	SIM.DrawSize,
	DFM.Title as MedicineDosage,
	convert(varchar(20),(EPD.PrescribedQuantity-EPD.DispensedQuantity)) as RemainingQty,	
	'' as UpdatedDateTime,
	CASE 
		WHEN D.EmployeeId IS NOT NULL THEN (CASE 
                WHEN ISNULL(LTRIM(RTRIM(EM3.EmployeePrefix)), '') = '' 
                    THEN '' 
                    ELSE EM3.EmployeePrefix + ' ' 
              END) + EM3.FirstName + ' ' + EM3.LastName
		WHEN VD.Id IS NOT NULL THEN 'Dr. ' + VD.FirstName + ' ' + VD.LastName
		ELSE ''																																									
	END AS RefferedName,
	Convert(varchar,D.MedicalRegistrationNo)MedicalRegistrationNo,
	ISNULL(EED.ExaminationNumber,'') as ExaminationNumber,
	ISNULL(CM.Title,'') as CauseTitle,
	isnull(OD.Title,'') as DepartmentName,
	--ISNULL(D.DoctorSignature, CONVERT(VARBINARY(MAX), 0))AS DoctorSignature,
	D.DoctorSignature AS DoctorSignature,
	CASE WHEN @rLogo = 0 THEN null 
    ELSE CID.Logo END AS Logo,
	 isnull(LM.SmallAddress1,'') as SmallAddress1,
	isnull(LM.SmallAddress2,'') as SmallAddress2,
	CI.Title as CompanyName,
	isnull(V.Remark,'') as Advice,
	--case when Isnull(SIM.Isnotinstore,0)= 1 then 'Outside' else --commented this for adani prescription report
	isnull(O.FurtherActionRemark,'') 
	--end --commented this for adani prescription report
	as FurtherActionRemark,
	'1' orderindex,
	[sExamination].[fTestParameterGetbyExaminationId](EED.Id, @rOrgId) AS TestName,	
	ISNULL(R.ContactPerson,'') as ReferedDoctor,
	ISNULL((Select Title from sCommon.tClinicMaster CCM where CCM.Id = R.ReferToClinicId),'') as ReferedHospital,
	ISNULL((select Title from [sFinanceCommon].[tStockUomMaster] FSUM where FSUM.Id = SIM.IssueStockUomId),'') as IssueUOM,
	AP.FollowupRemark as FollowupRemark,
	V.Remark as VitalRemark,
	V.SPo2,
	(FAM.Title + ISNULL((CASE 
		WHEN FAM.CODE='REFER TO HOSPITAL'
		THEN ISNULL((SELECT CASE 
				WHEN (ISNULL(CLM.Title,'') != '') AND (ISNULL(R.ContactPerson,'') != '') THEN (' - ' + CLM.Title + ' - ' + R.ContactPerson)
				WHEN (ISNULL(CLM.Title,'') != '') OR (ISNULL(R.ContactPerson,'') != '') THEN (' - ' + ISNULL(CLM.Title,'') + ISNULL(R.ContactPerson,'')) 
				ELSE ''
				END),'') 
		WHEN FAM.CODE='109' OR FAM.CODE='110'
		THEN ' - ' + ISNULL(RTDEM.EmployeePrefix + ' ','') + RTDEM.FirstName + ' ' + RTDEM.LastName
		END),'')) AS FurtherAction,
	--( --commented this for adani prescription report
	CONVERT(varchar(10), AP.AppointmentDate, 103) 
    --+ ' and ' + CAST(DATEDIFF(DAY, EED.ExaminationDate, AP.AppointmentDate) AS varchar(10))) --commented this for adani prescription report
	AS FollowUpDate
	from sExamination.tExamination EED
	LEFT JOIN sCwb.tDoctorMaster D on EED.DoctorEmployeeId = D.EmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EM3 on D.EmployeeId = EM3.Id
	LEFT JOIN sExamination.tVital V	ON EED.Id = V.SourceId	
	LEFT JOIN sExamination.tReferral R on R.SourceId = EED.Id 
	LEFT JOIN sExamination.tOPD O on EED.Id = O.ExaminationId
	LEFT JOIN sExamination.vExtPrescription EP on EED.Id = EP.SourceId AND (EP.IsObsolete = 0)
	LEFT JOIN sExamination.vExtPrescriptionDetail EPD on EP.Id = EPD.PrescriptionId AND EPD.StoreLocationId = @rStoreLocationId AND (EPD.IsObsolete = 0)
	LEFT JOIN sIp.tStockItemMaster SIM on EPD.DrugStockItemId = SIM.Id 
	LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on EED.OrganizationDepartmentId = OD.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON OD.DepartmentGroupId = DGM.Id
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id
	LEFT JOIN sIp.tDrugDosageFrequencyMaster DFM on DFM.Id=EPD.DrugDosageFrequencyid
	LEFT JOIN sIp.tDrugScheduleMaster SM on SM.Id = EPD.DrugDosageScheduleId	
	LEFT JOIN sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id and EED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EED.ParticipantSourceId = EFD.Id and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tRelationshipMaster RM on RM.Id = EFD.RelationshipId and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on BM.Id = EED.ParticipantSourceId and EED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CSRBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sHrm.tEmployeePersonalDetail PD on EM.Id = PD.EmployeeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = PD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sCommon.tGenderMaster GM3 ON GM3.Id = EFD.GenderId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 ON EM2.Id = EJD2.EmployeeId	
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sAppointment.tVisitingDoctorMaster VD on EED.DoctorEmployeeId = VD.Id
	LEFT JOIN sExamination.tCauseMaster CM on CM.Id = EED.CauseId 
	INNER JOIN sExamination.tSetupMaster SSM on EED.SetupId = SSM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SSM.SubTypeId = ST.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = EED.StoreLocationId
	INNER JOIN sCommon.tLocationMaster LM ON SLM.LocationId = LM.Id
	INNER JOIN sCommon.tCompanyInformation CI ON LM.OrgId = CI.Id	
	INNER JOIN sCommon.tCompanyInformationDetail CID on ci.ID = CID.orgid
	LEFT JOIN sAppointment.tAppointment AP on AP.ReferSourceId = EED.Id
	LEFT JOIN sSafety.tFurtherActionMaster FAM ON O.FurtherActionId = FAM.Id
	LEFT JOIN sCommon.tClinicMaster CLM ON R.ReferToClinicId = CLM.Id
	LEFT JOIN sHrm.tEmployeeMaster RTDEM ON O.ReferToDoctorId = RTDEM.Id
	WHERE (EED.Id = @rExaminationId OR @rExaminationId = 0)
	AND ST.MainTypeId = 8 and isnull(EED.Iscancel,0) = 0
	AND (EED.StoreLocationId = @rStoreLocationId)	
	AND 
	(
		ISNULL(@rEmployeeCode, '') = ''
		OR EXISTS 
		(
			SELECT 1
			FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
			WHERE 
			(
				CHARINDEX(',', @rEmployeeCode) = 0 
				AND 
				(
					(EM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1009)
				)
			)
			OR
			(
				CHARINDEX(',', @rEmployeeCode) > 0 
				AND 
				(
					(EM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1009)
				)
			)
		)
	)
	AND (EED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
	AND (EED.GradeId = @rGradeId OR @rGradeId=0)	
	AND (EED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EED.ParticipantSourceTypeId = 95)
		OR (EJD2.EmployeeJobTitleId = @rJobTitleId AND EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId and EED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rEmployeeTypeId and EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(
		(EJD.ContractorId = @rContractorId and EED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rContractorId and EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rContractorId = 0
	)	
	AND (EED.EmployeeCompanyId = @rCompanyId OR @rCompanyId=0)	
	AND
	(
		(PD.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 95)
		OR (EFD.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 1001)
		OR (BM.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)		
	AND (EED.EmployeeStatusId = @rStatusId OR @rStatusId=0) 	
	AND
	(
		(DATEDIFF(yy,PD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo AND EED.ParticipantSourceTypeId = 95)
		OR (DATEDIFF(yy,isnull(EFD.DateOfBirth,'2050-01-01'),sCommon.fGetDate()) <= @rAgeTo AND EED.ParticipantSourceTypeId = 1001)
		OR (DATEDIFF(yy,isnull(BM.DateOfBirth,'2050-01-01'),sCommon.fGetDate()) <= @rAgeTo AND EED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(DATEDIFF(yy,PD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 95)
		OR (DATEDIFF(yy,isnull(EFD.DateOfBirth,'1900-12-31'),sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 1001)
		OR (DATEDIFF(yy,isnull(BM.DateOfBirth,'1900-12-31'),sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeFrom,0)=0
	)
		
	AND ((EED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))	
	AND ((EED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (SLM.LocationId = @rLocationId) 	
	AND (EED.StoreLocationId = @rStoreLocationId) 	
	AND (EED.OrgId = @rOrgId)	
	AND (EED.CauseId = @rCaseCauseId or @rCaseCauseId=0)	
	AND (EED.ParticipantSourceTypeId = @rParticipantTypeId or @rParticipantTypeId=0)	
	AND (ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId=0)	
	AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId or @rEmployeeSubTypeId=0)	
	AND (EJD.EmployeeGroupId = @rEmployeeGroupId or @rEmployeeGroupId=0)	
	AND (BM.CsrBenefiterTypeId = @rOtherTypeId or @rOtherTypeId=0)
	
	union

	select EED.Id AS ExaminationId,
	OSP.id as prescriptionId,
	'' as ParticipantCode,
	'' as ParticipantName,
	'' as PatientCategory,	
	'' as Gender,
	'' as ExaminationDate,
	'' as OPDOutTime,	
	0 as Age,
	'' Pulse,
	'0' Temperature,
	'' BloodPressureSystolic,
	'' BloodPressureDiastolic,
	'' ContactPerson,
	'' OutsideMedicine,
	'' OutsideTest,
	'' AS Diagnosis,
	'' as problems,
	Isnull(DSM.Title,'') as DrugInstruction,
	Isnull(OSPD.StockItemName,'') as Medicines,
	Isnull(OSPD.DrugInstruction,'0.00') as MedicineQty,
	'0.00' DispensedQuantity,
	Isnull(OSPD.Duration,'') Duration,
	case when Isnull(OSPD.PrescribedQuantity,'')='' then '0' else Isnull(OSPD.PrescribedQuantity,'0') end PrescribedQuantity,
	EED.ParticipantSourceId,
	OSPD.id as StockId,
	0 DrawSize,
	DFM.Title as MedicineDosage,
	case when Isnull(OSPD.PrescribedQuantity,'')='' then '0' else Isnull(OSPD.PrescribedQuantity,'0') end  as RemainingQty,	
	GetDate() as UpdatedDateTime,
	'' as RefferedName,
	'' MedicalRegistrationNo,
	ISNULL(EED.ExaminationNumber,'') as ExaminationNumber,
	'' as CauseTitle,
	'' as DepartmentName,	
	convert(varbinary,'0') AS DoctorSignature,
	convert(varbinary,'0') Logo,
	'' as SmallAddress1,
	'' as SmallAddress2,
	'' as CompanyName,
	'' as Advice,
	'Outside' as FurtherActionRemark,
	'2' orderindex,
	[sExamination].[fTestParameterGetbyExaminationId](EED.Id, @rOrgId) AS TestName,	
	'' as ReferedDoctor,
	'' as ReferedHospital,
	'' as IssueUOM,
	'' as FollowupRemark,
	'' as VitalRemark,
	0 as SPo2,
	'' as FurtherAction,
	'' as FollowUpDate

	from sExamination.tExamination EED
	inner join sExamination.tOutSidePrescription OSP on OSP.Sourceid=EED.Id
	inner join sExamination.tOutSidePrescriptionDetail OSPD on OSPD.OutSidePrescriptionId=OSP.id
	left join sIp.tDrugDosageFrequencyMaster DFM on DFM.id=OSPD.DrugDosageFrequencyId
	left join sIp.tDrugScheduleMaster DSM on DSM.id=OSPD.DrugDosageScheduleId
	LEFT JOIN sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id and EED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EED.ParticipantSourceId = EFD.Id and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on BM.Id = EED.ParticipantSourceId and EED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id

	WHERE (EED.Id = @rExaminationId OR @rExaminationId = 0)
	and isnull(EED.Iscancel,0) = 0
	AND (EED.StoreLocationId = @rStoreLocationId)		
	AND (EED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
	AND (EED.GradeId = @rGradeId OR @rGradeId=0)	
	AND (EED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)		
	AND (EED.EmployeeCompanyId = @rCompanyId OR @rCompanyId=0)			
	AND (EED.EmployeeStatusId = @rStatusId OR @rStatusId=0) 		
	AND ((EED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))	
	AND ((EED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))			
	AND (EED.OrgId = @rOrgId)	
	AND (EED.CauseId = @rCaseCauseId or @rCaseCauseId=0)	
	AND (EED.ParticipantSourceTypeId = @rParticipantTypeId or @rParticipantTypeId=0)		
	AND 
	(
		ISNULL(@rEmployeeCode, '') = ''
		OR EXISTS 
		(
			SELECT 1
			FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
			WHERE 
			(
				CHARINDEX(',', @rEmployeeCode) = 0 
				AND 
				(
					(EM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1009)
				)
			)
			OR
			(
				CHARINDEX(',', @rEmployeeCode) > 0 
				AND 
				(
					(EM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1009)
				)
			)
		)
	)
	order by orderindex
	OPTION(RECOMPILE)
end
GO
PRINT N'Altering Procedure [sExamination].[pRptPrescription]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pRptPrescription]
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rReportId int,
@rStoreLocationId int,
@rParticipantTypeId int,
@rCaseCauseId int,
@rLocationId int,
@rFunctionId int,
@rDepartmentGroupId int,
@rDepartmentId int,
@rGradeId int,
@rDesignationId int,
@rJobTitleId int,
@rEmployeeTypeId int,
@rCompanyId int,
@rContractorId int,
@rGenderId smallint,
@rStatusId smallint,
@rAgeFrom int=0,
@rAgeTo int=100,
@rFromDate date = null,
@rToDate datetime = null,
@rOrgId int,
@rEmployeeCode nvarchar(50)='',
@rEmployeeTypeGroupId int=0,
@rEmployeeSubTypeId int=0,
@rEmployeeGroupId int=0,
@rOtherTypeId int=0,
@rExaminationId bigint=0,
@rLogo bit = true
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
   -- Validate @rEmployeeCode entries
    IF EXISTS 
    (
        SELECT SplitValues.item
        FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
        WHERE NOT EXISTS 
        (
            SELECT 1 FROM sHrm.tEmployeeMaster EM WHERE EM.Code = SplitValues.item
            UNION
            SELECT 1 FROM sHrm.tCsrBenefiterMaster BM WHERE BM.Code = SplitValues.item
        )
    )
    BEGIN
        RAISERROR('One or more Employee Codes are invalid / Not Exists.', 16, 1);
        RETURN;
    END

	SELECT ROW_NUMBER() OVER(PARTITION BY P.Id ORDER BY SIM.Title ASC) as Number,
	EED.Id,
	EmployeeName = CASE EED.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ParticipantCode = CASE EED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	PatientCategory = CASE EED.ParticipantSourceTypeId WHEN 95 THEN isnull(ETM.Title,'') WHEN 1001 THEN isnull(RM.Title,'') WHEN 1009 THEN isnull(BTM.Title,'') END,
	SIM.Title AS ItemName,
	case when isnull(PD.DrugInstruction,'') = '' then DSM.Title else PD.DrugInstruction end as DrugInstruction,
	PD.Remark,
	CASE WHEN convert(varchar(20),PD.Dosage) = '0.01' THEN '-' ELSE convert(varchar(20),PD.Dosage) END as Dosage,
	convert(varchar(20),PD.Duration)Duration,
	convert(varchar(20),PD.PrescribedQuantity)PrescribedQuantity,
	EED.ExaminationDate,
	LM.Title AS CompanyName,
	isnull(EM3.FirstName,'') + ' ' + isnull(EM3.LastName,'') AS DoctorName,
	case when isnull(PD.DrugInstruction,'') = '' then DSM.Title else PD.DrugInstruction end as DrugInstruction,
	LM.Title AS LocationName,
	LM.SmallAddress1,
	LM.SmallAddress2,
	ISGM.Title AS DosageFrom,	
	Age = CASE EED.ParticipantSourceTypeId WHEN 95 THEN isnull(datediff(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)
	WHEN 1001 THEN isnull(datediff(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) WHEN 1009 THEN isnull(O.Age,isnull(datediff(yy,BM.DateOfBirth,sCommon.fGetDate()),0)) end,	
	V.Pulse,
	V.Temperature,
	[sExamination].[fExistingDiseaseGet](EED.Id) AS Diagnosis,
	(select top 1 isnull(Remark,'') from sExamination.tComplaint where SourceId = EED.Id) as problems,
	Gender = CASE EED.ParticipantSourceTypeId
	WHEN 95 THEN GM.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE isnull((SELECT Title FROM sCommon.tGenderMaster where O.GenderId = Id),'') END END,
	V.BloodPressureSystolic,
	V.BloodPressureDiastolic,
	SIM.DrawSize,
	DFM.Title as MedicineDosage,	
	case when D.EmployeeId is not null then EM3.FirstName + ' ' + EM3.LastName else
	case when VD.Id is not null then VD.FirstName + ' ' + VD.LastName else '' end end as RefferedName,	
	EM3.EmployeePrefix AS RefferedNamePrefix,
	D.MedicalRegistrationNo,
	ISNULL(EED.ExaminationNumber,'') as ExaminationNumber,
	ISNULL(CM.Title,'') as CauseTitle,
	[sExamination].[fTestParameterGetbyExaminationId](EED.Id, @rOrgId) AS TestName,
	O.OutsideMedicine,
	O.OutsideTest,
	'1' orderindex,
	CASE  --Mantis: 28685 by- Shivam (07-11-2023)
        WHEN SIM.IsNotInstore = 0 THEN 'Available'
        ELSE 'Not Available'
    END AS Availability
	 ,isnull(EI.EmployeeSign,0x) as EmployeeSignature
	 ,isnull(D.DoctorSignature,0x) AS DoctorSignature
	 ,[sExamination].[fHistoryGet_new](EED.ParticipantSourceId) AS History
	 ,EC.MobileNumber as EmployeeMobileNumber
	 ,EC.CompanyEmail as EmployeeCompanyEmail
	,ISNULL(EC.PresentStreetOne, '') + ' ' + ISNULL(EC.PresentStreetTwo, '') + ' ' + ISNULL(EC.PresentStreetThree, '') + ' ' + ISNULL(EC.PresentCity, '') + ' ' + ISNULL(EC.PresentState,'') + ' - ' + ISNULL(EC.PresentZipCode, '') AS EmployeeAddress
	,P.Remark as OtherRemark
	,pt.DrugAllergy
	,V.BMI
	,A.FollowupRemark
	,CAST(A.AppointmentDate AS DATE) AS FollowupDate
	,V.Remark as VitalRemark
	,V.SPo2
	,isnull(O.OPDTime,'') as OPDInTime
	,isnull(O.OPDOutTime,'') as OPDOutTime
	FROM sExamination.tExamination EED
	LEFT JOIN sCwb.tDoctorMaster D on EED.DoctorEmployeeId = D.EmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EM3 on D.EmployeeId = EM3.Id
	LEFT JOIN sExamination.tPrescription P ON EED.Id = P.SourceId and P.IsObsolete = 0	
	LEFT JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId = P.Id and PD.IsObsolete = 0	
	LEFT JOIN sIp.tStockItemMaster SIM ON SIM.Id = PD.StockItemId and SIM.LocationId = @rLocationId
	LEFT JOIN sCommon.tLocationMaster LM ON LM.Id = SIM.LocationId	
	LEFT JOIN sIp.tItemSubGroupMaster ISGM On ISGM.Id = SIM.ItemSubGroupId	
	LEFT JOIN sExamination.tVital V	ON EED.Id = V.SourceId	
	LEFT JOIN sExamination.tReferral R on R.SourceId = EED.Id 	
	LEFT JOIN sExamination.tOPD O on EED.Id = O.ExaminationId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on EED.OrganizationDepartmentId = OD.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON OD.DepartmentGroupId = DGM.Id 	
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id	
	LEFT JOIN sIp.tDrugDosageFrequencyMaster DFM on DFM.Id=PD.DrugDosageFrequencyid	
	LEFT JOIN sIp.tDrugScheduleMaster DSM on DSM.Id = PD.DrugDosageScheduleId	
	LEFT JOIN sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id and EED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EED.ParticipantSourceId = EFD.Id and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tRelationshipMaster RM on RM.Id = EFD.RelationshipId and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on BM.Id = EED.ParticipantSourceId and EED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CSRBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 ON EM2.Id = EJD2.EmployeeId	
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sAppointment.tVisitingDoctorMaster VD on EED.DoctorEmployeeId = VD.Id
	LEFT JOIN sExamination.tCauseMaster CM on CM.Id = EED.CauseId 
	INNER JOIN sExamination.tSetupMaster SM on EED.SetupId = SM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = EED.StoreLocationId
	LEFT JOIN sHrm.tEmployeeImages EI on EI.EmployeeId=EM.Id
	LEFT JOIN sHrm.tEmployeeCommunications EC on EC.EmployeeId = EM.Id
	LEFT JOIN sExamination.tPrompt pt on pt.ParticipantId = EM.Id
	LEFT JOIN sAppointment.tAppointment A on A.ReferSourceId = EED.Id
		
	
	WHERE (EED.Id = @rExaminationId OR @rExaminationId = 0)
	AND ST.MainTypeId = 8 AND isnull(EED.IsCancel,0) = 0
	AND (EED.StoreLocationId = @rStoreLocationId)	
	AND 
	(
		ISNULL(@rEmployeeCode, '') = ''
		OR EXISTS 
		(
			SELECT 1
			FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
			WHERE 
			(
				CHARINDEX(',', @rEmployeeCode) = 0 
				AND 
				(
					(EM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1009)
				)
			)
			OR
			(
				CHARINDEX(',', @rEmployeeCode) > 0 
				AND 
				(
					(EM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1009)
				)
			)
		)
	)
	AND (EED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
	AND (EED.GradeId = @rGradeId OR @rGradeId=0)	
	AND (EED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EED.ParticipantSourceTypeId = 95)
		OR (EJD2.EmployeeJobTitleId = @rJobTitleId AND EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId and EED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rEmployeeTypeId and EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(
		(EJD.ContractorId = @rContractorId and EED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rContractorId and EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rContractorId = 0
	)	
	AND (EED.EmployeeCompanyId = @rCompanyId OR @rCompanyId=0)	
	AND
	(
		(EPD.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 95)
		OR (EFD.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 1001)
		OR (BM.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)
	AND (EED.EmployeeStatusId = @rStatusId OR @rStatusId=0) 	
	AND
	(		
		(ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EED.ParticipantSourceTypeId = 95)
		OR (ISNULL(DATEDIFF(yy,isnull(EFD.DateOfBirth,'2050-01-01'),sCommon.fGetDate()),0) <= @rAgeTo AND EED.ParticipantSourceTypeId = 1001)
		OR (ISNULL(DATEDIFF(yy,isnull(BM.DateOfBirth,'2050-01-01'),sCommon.fGetDate()),0) <= @rAgeTo AND EED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 95)
		OR (DATEDIFF(yy,isnull(EFD.DateOfBirth,'1900-12-31'),sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 1001)
		OR (DATEDIFF(yy,isnull(BM.DateOfBirth,'1900-12-31'),sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeFrom,0)=0
	)
	AND ((EED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))	
	AND ((EED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (SLM.LocationId = @rLocationId) 	
	AND (EED.StoreLocationId = @rStoreLocationId) 	
	AND (EED.OrgId = @rOrgId)	
	AND (EED.CauseId = @rCaseCauseId or @rCaseCauseId=0)	
	AND (EED.ParticipantSourceTypeId = @rParticipantTypeId or @rParticipantTypeId=0)	
	AND (ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId=0)	
	AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId or @rEmployeeSubTypeId=0)	
	AND (EJD.EmployeeGroupId = @rEmployeeGroupId or @rEmployeeGroupId=0)	
	AND (BM.CsrBenefiterTypeId = @rOtherTypeId or @rOtherTypeId=0)

	union

	SELECT ROW_NUMBER() OVER(PARTITION BY OSP.Id ORDER BY OSPD.StockItemname ASC) as Number,
	EED.Id,
	'' EmployeeName,
	'' ParticipantCode,
	'' PatientCategory,
	OSPD.StockItemname AS ItemName,
	Isnull(DSM.Title,'') DrugInstruction,
	'' Remark,
	CASE WHEN convert(varchar(20),OSPD.DrugInstruction) = '0.01' THEN '-' ELSE convert(varchar(20),Isnull(OSPD.DrugInstruction,'0.00')) END AS Dosage,
	Isnull(OSPD.Duration,'0') Duration,
	case when Isnull(OSPD.PrescribedQuantity,'')='' then '0' else Isnull(OSPD.PrescribedQuantity,'0') end PrescribedQuantity,
	EED.ExaminationDate,
	'' AS CompanyName,
	'' AS DoctorName,
	Isnull(DSM.Title,'') DrugInstruction,
	'' AS LocationName,
	'' SmallAddress1,
	'' SmallAddress2,
	'' AS DosageFrom,	
	0 as Age,	
	'' Pulse,
	0 Temperature,
	'' AS Diagnosis,
	'' as problems,
	'' Gender,
	'' BloodPressureSystolic,
	'' BloodPressureDiastolic,
	0 DrawSize,
	DFM.Title as MedicineDosage,	
	'' RefferedName,	
	'' AS RefferedNamePrefix,
	'' MedicalRegistrationNo,
	ISNULL(EED.ExaminationNumber,'') as ExaminationNumber,
	'' as CauseTitle,
	[sExamination].[fTestParameterGetbyExaminationId](EED.Id, @rOrgId) AS TestName,
	'' OutsideMedicine,
	'' OutsideTest,
	'2' orderindex,
	'Not Available' Availability
	,0x as EmployeeSignature
	 ,0x AS DoctorSignature
	 ,'' AS History
	 ,'' as EmployeeMobileNumber
	 ,'' as EmployeeCompanyEmail
	 ,'' as EmployeeAddress
	 ,'' as Remark
	 ,'' as DrugAllergy
	 ,convert(varchar(20),0) as BMI
	 ,'' as FollowupRemark
	 ,'' as FollowupDate
	 ,'' as VitalRemark
	 ,convert(varchar(20),0) as SPo2
	 ,'' as OPDInTime
	 ,'' as OPDOutTime

	FROM sExamination.tExamination EED
	inner join sExamination.tOutSidePrescription OSP on OSP.Sourceid=EED.Id
	inner join sExamination.tOutSidePrescriptionDetail OSPD on OSPD.OutSidePrescriptionId=OSP.id
	left join sIp.tDrugDosageFrequencyMaster DFM on DFM.id=OSPD.DrugDosageFrequencyId
	left join sIp.tDrugScheduleMaster DSM on DSM.id=OSPD.DrugDosageScheduleId
	Left JOIN sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id and EED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EED.ParticipantSourceId = EFD.Id and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on BM.Id = EED.ParticipantSourceId and EED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id

	WHERE (EED.Id = @rExaminationId OR @rExaminationId = 0)
	AND isnull(EED.IsCancel,0) = 0
	AND (EED.StoreLocationId = @rStoreLocationId)		
	AND (EED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
	AND (EED.GradeId = @rGradeId OR @rGradeId=0)	
	AND (EED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)				
	AND (EED.EmployeeCompanyId = @rCompanyId OR @rCompanyId=0)		
	AND (EED.EmployeeStatusId = @rStatusId OR @rStatusId=0) 		
	AND ((EED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))	
	AND ((EED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))		
	AND (EED.StoreLocationId = @rStoreLocationId) 	
	AND (EED.OrgId = @rOrgId)	
	AND (EED.CauseId = @rCaseCauseId or @rCaseCauseId=0)	
	AND (EED.ParticipantSourceTypeId = @rParticipantTypeId or @rParticipantTypeId=0)	
	AND 
	(
		ISNULL(@rEmployeeCode, '') = ''
		OR EXISTS 
		(
			SELECT 1
			FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
			WHERE 
			(
				CHARINDEX(',', @rEmployeeCode) = 0 
				AND 
				(
					(EM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1009)
				)
			)
			OR
			(
				CHARINDEX(',', @rEmployeeCode) > 0 
				AND 
				(
					(EM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1009)
				)
			)
		)
	)
	order by orderindex
	OPTION(RECOMPILE)
END
GO
PRINT N'Altering Procedure [sExamination].[pSaveClinicalTests]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pSaveClinicalTests]
@rId varchar(max),
@rOrgId int
as
begin
	declare @tbltmpTests table(tid int identity(1,1),t_StaticTestId int,t_TestId int)
	insert into @tbltmpTests
	select Item,sCommon.fGetIntIdForOrg(Item,@rOrgId) from dbo.fSplitStr(@rId,',') where Item <> ''
	
	delete from sExamination.tGeneralTemplateMaster where OrgId = @rOrgId
	delete from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId
	delete from sExamination.tGeneralTemplateParameterList where OrgId = @rOrgId
	delete from sExamination.tGeneralTemplateParameterRange where OrgId = @rOrgId
		
	declare @lFromNumber int
	select @lFromNumber = max(Id) from sExamination.tGeneralTemplateMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sExamination.tGeneralTemplateMaster AS Target USING 
	(
		SELECT t_StaticTestId,t_TestId,SG.Code,SG.Title,SG.GeneralTemplateGroupId,SG.IsObsolete,SG.CreatedUserId,
		SG.CreatedDateTime,SG.UpdatedUserId,SG.UpdatedDateTime,SG.OrderIndex
		--ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		--(
		--	SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateMaster t
		--) as maxid
		
		FROM @tbltmpTests TT inner join sExamination.tStaticGeneralTemplateMaster SG on TT.t_StaticTestId = SG.Id
		LEFT JOIN sExamination.tGeneralTemplateMaster T ON TT.t_TestId = T.Id
	) AS Source ON Target.Id = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Code,Title,GeneralTemplateGroupId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,
			OrgId,OrderIndex,StaticGeneralTemplateId
		)
		VALUES
		(
			t_TestId,Code,Title,GeneralTemplateGroupId,IsObsolete,CreatedUserId,
			CreatedDateTime,UpdatedUserId,UpdatedDateTime,@rOrgId,OrderIndex,t_StaticTestId
		);
	
	select @lFromNumber = max(Id) from sOrderEntry.tServiceMaster
	select @lFromNumber = isnull(@lFromNumber,0)
				
	MERGE sOrderEntry.tServiceMaster AS Target USING 
	(
		SELECT t_StaticTestId,t_TestId,SG.Code,SG.Title,SG.GeneralTemplateGroupId,SG.IsObsolete,SG.CreatedUserId,
		SG.CreatedDateTime,SG.UpdatedUserId,SG.UpdatedDateTime,SG.OrderIndex
		--ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		--(
		--	SELECT MAX(T.Id) FROM sOrderEntry.tServiceMaster t
		--) as maxid
		
		FROM @tbltmpTests TT inner join sExamination.tStaticGeneralTemplateMaster SG on TT.t_StaticTestId = SG.Id
		LEFT JOIN sOrderEntry.tServiceMaster T ON TT.t_TestId = T.Id
	) AS Source ON Target.Id = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Code,Title,ServiceSubGroupId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgId
		)
		VALUES
		(
			t_TestId,Code,Title,scommon.fGetIntIdForOrg(GeneralTemplateGroupId,@rOrgId),IsObsolete,CreatedUserId,
			CreatedDateTime,UpdatedUserId,UpdatedDateTime,@rOrgId
		);
	
	select @lFromNumber = max(Id) from sExamination.tAreaMaster
	select @lFromNumber = isnull(@lFromNumber,0)
			
	MERGE sExamination.tAreaMaster AS Target USING 
	(
		SELECT t_StaticTestId,t_TestId,SG.Title,SG.IsObsolete,SG.OrderIndex
		--,ROW_NUMBER()OVER(ORDER BY T.Id) as rno,
		--(
		--	SELECT MAX(T.Id) FROM sExamination.tAreaMaster t
		--) as maxid
		
		FROM @tbltmpTests TT inner join sExamination.tStaticGeneralTemplateMaster SG on TT.t_StaticTestId = SG.Id
		LEFT JOIN sExamination.tAreaMaster T ON TT.t_TestId = T.Id AND AreaTypeId = 3
	) AS Source ON Target.Id = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,Title,Remark,AreaTypeId,AreaGroupId,IsObsolete,PagePath,OrderIndex,ImagePath,OrgId,StaticAreaId
		)
		VALUES
		(
			t_TestId,Title,'p',3,2,IsObsolete,'~/Pages/Examination/GeneralTemplateExamination.aspx?GeneralTemplateId=' + convert(varchar,t_TestId),
			OrderIndex,'~/Images/Icon 16x16/icon_general.gif',@rOrgId,t_StaticTestId
		);
	
	select @lFromNumber = max(Id) from sExamination.tAreaOrganizationMaster
	select @lFromNumber = isnull(@lFromNumber,0)
	
	MERGE sExamination.tAreaOrganizationMaster AS Target USING 
	(
		SELECT TT.tid,t_StaticTestId,t_TestId,SG.Title,SG.IsObsolete,SG.CreatedUserId,SG.CreatedDateTime,
		SG.UpdatedUserId,SG.UpdatedDateTime
		--,ROW_NUMBER()OVER(ORDER BY T.Id) as rno,
		--(
		--	SELECT MAX(T.Id) FROM sExamination.tAreaOrganizationMaster t
		--) as maxid
		
		FROM @tbltmpTests TT inner join sExamination.tStaticGeneralTemplateMaster SG on TT.t_StaticTestId = SG.Id
		LEFT JOIN sExamination.tAreaOrganizationMaster T ON TT.t_TestId = T.AreaId
		LEFT JOIN sExamination.tAreaMaster AM on T.AreaId = AM.Id AND TT.t_TestId = AM.Id AND AM.AreaTypeId = 3
	) AS Source ON Target.AreaId = Source.t_TestId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,OrgId,AreaId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
		VALUES
		(
			@lFromNumber + tid,@rOrgId,t_TestId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		);
		
	declare @tbltmpParameters table(pid int identity(1,1),p_StaticParamId int,p_ParamId int,p_TestId int)
	insert into @tbltmpParameters
	select Id,sCommon.fGetIntIdForOrg(Id,@rOrgId),t_TestId from sExamination.tStaticGeneralTemplateParameter P
	inner join @tbltmpTests on P.StaticGeneralTemplateId = t_StaticTestId
	
	select @lFromNumber = max(Id) from sExamination.tGeneralTemplateParameter
	select @lFromNumber = isnull(@lFromNumber,0)
			
	MERGE sExamination.tGeneralTemplateParameter AS Target USING 
	(
		SELECT p_ParamId,p_StaticParamId,p_TestId,SP.Title,SP.ParameterValueTypeId,SP.NumericFormat,
		SP.UOM,SP.IsObsolete,SP.OrderIndex,SP.CreatedUserId,SP.CreatedDateTime,SP.UpdatedUserId,SP.UpdatedDateTime
		--ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		--(
		--	SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateParameter t
		--) as maxid
		
		FROM @tbltmpParameters TT INNER JOIN sExamination.tStaticGeneralTemplateParameter SP
		ON TT.p_StaticParamId = SP.Id LEFT JOIN sExamination.tGeneralTemplateParameter T
		ON TT.p_ParamId = T.Id	AND TT.p_TestId = T.GeneralTemplateId
	) AS Source ON Target.Id = Source.p_ParamId AND Target.GeneralTemplateId = Source.p_TestId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			[Id],Title,GeneralTemplateId,ParameterValueTypeId,UOM,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,
			UpdatedDateTime,OrgId,StaticGeneralTemplateParameterId,OrderIndex
		)
		VALUES
		(
			p_ParamId,Title,p_TestId,ParameterValueTypeId,UOM,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,
			UpdatedDateTime,@rOrgId,p_StaticParamId,OrderIndex
		);
	
	declare @tbltmpParameterList table(tid int identity(1,1),l_StaticParamId int,l_ParamId int,l_StaticId int,l_Id int)
	insert into @tbltmpParameterList
	select p_StaticParamId,p_ParamId,Id,sCommon.fGetIntIdForOrg(Id,@rOrgId)
	from sExamination.tStaticGeneralTemplateParameterList L inner join @tbltmpParameters P
	on L.StaticGeneralTemplateParameterId = P.p_StaticParamId
	
	select @lFromNumber = max(Id) from sExamination.tGeneralTemplateParameterList
	select @lFromNumber = isnull(@lFromNumber,0)
	
	insert into sExamination.tGeneralTemplateParameterList
	(
		Id,GeneralTemplateParameterId,Title,IsObsolete,IsNormal,Diagnosis,Recommendation,OrgId,StaticGeneralTemplateParameterListId
	)
	select l_Id,l_ParamId,Title,IsObsolete,IsNormal,Diagnosis,Recommendation,@rOrgId,l_StaticId
	from sExamination.tStaticGeneralTemplateParameterList S inner join @tbltmpParameterList L
	on S.Id = L.l_StaticId
	
	declare @tbltmpParameterRange table(tid int identity(1,1),r_StaticParamId int,r_ParamId int,r_StaticId int,r_Id int)
	insert into @tbltmpParameterRange
	select  p_StaticParamId,p_ParamId,Id,sCommon.fGetIntIdForOrg(Id,@rOrgId)
	from sExamination.tStaticGeneralTemplateParameterRange R inner join @tbltmpParameters P
	on R.StaticGeneralTemplateParameterId = P.p_StaticParamId
	
	select @lFromNumber = max(Id) from sExamination.tGeneralTemplateParameterRange
	select @lFromNumber = isnull(@lFromNumber,0)

	MERGE sExamination.tGeneralTemplateParameterRange AS Target USING 
	(
		SELECT tt.tid,r_StaticParamId,r_ParamId,r_StaticId,r_Id,SP.GenderId,SP.AgeFrom,SP.AgeTo,SP.Minimum,SP.Maximum,
		SP.Remark,SP.IsObsolete,SP.IsNormal,SP.Diagnosis,SP.Recommendation
		--ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		--(
		--	SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateParameterRange t
		--) as maxid
		
		FROM @tbltmpParameterRange TT 
		INNER JOIN sExamination.tStaticGeneralTemplateParameterRange SP ON TT.r_StaticId = SP.Id
		--LEFT JOIN sExamination.tGeneralTemplateParameterRange T
		--ON TT.r_ParamId = T.GeneralTemplateParameterId
	) AS Source ON Target.Id = Source.r_Id
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,GeneralTemplateParameterId,GenderId,AgeFrom,AgeTo,Minimum,Maximum,Remark,IsObsolete,IsNormal,Diagnosis,Recommendation,OrgId
		)
		VALUES
		(
			r_Id,r_ParamId,GenderId,AgeFrom,AgeTo,Minimum,Maximum,Remark,IsObsolete,IsNormal,Diagnosis,Recommendation,@rOrgId
		);
end
GO
PRINT N'Altering Procedure [sExamination].[pSetupGroupStatusGet]...';


GO
-- EXEC [sExamination].[pSetupGroupStatusGet] 9999,0,0
-- DROP PROC [sExamination].[pSetupGroupStatusGet]
CREATE OR ALTER PROCEDURE [sExamination].[pSetupGroupStatusGet] 
	@OrgId int,
	@MainTypeId int,
	@SetupGroupId int,
	@rUserId bigint
AS
BEGIN
	DECLARE @ResultString nvarchar(max) = ''

	DECLARE @TableOne TABLE
	(
		tId int IDENTITY (1, 1),StoreLocationId nvarchar(250),
		StoreLocationName nvarchar(250),SetupId nvarchar(250),
		SetupName nvarchar(250),EmployeeCount nvarchar(250),
		CompletedCount nvarchar(250),
		PendingCount nvarchar(250),
		IsClosed nvarchar(250),IsPublishSetup nvarchar(250),
		IsDiagnosisTrackerUpdated nvarchar(250),
		IsHealthIndexUpdated nvarchar(250),
		IsEmployeeHistoryUpdated nvarchar(250),
		HealthIndexCount nvarchar(250),
		DiagnosisTrackerCount nvarchar(250)
	)

	INSERT INTO @TableOne
	SELECT Distinct StoreLocationId = ISNULL(SLM.Id,'0'),
	StoreLocationName = ISNULL(SLM.Title,'0'),
	SetupId = ISNULL(STP.Id,'0'),
	SetupName = ISNULL(STP.Title,'0'),
	EmployeeCount = ISNULL(Emp.EmployeeCount, '0'),
	CompletedCount = ISNULL(Emp1.EmployeeCount, '0'),
	PendingCount = ISNULL(Emp2.EmployeeCount, '0'),
	IsClosed = ISNULL(STP.IsClosed,'0'),
	IsPublishSetup = ISNULL(STP.IsPublishSetup,'0'),
	IsDiagnosisTrackerUpdated  = ISNULL(STP.IsDiagnosisTrackerUpdated,'0'),
	IsHealthIndexUpdated = ISNULL(STP.IsHealthIndexUpdated,'0'),
	IsEmployeeHistoryUpdated = ISNULL(STP.IsEmployeeHistoryUpdated,'0'),
	HealthIndexCount = ISNULL(HealthIndex.HealthIndexCount,'0'),
	DiagnosisTrackerCount = ISNULL(DiagnosisTracker.DignosisTracker,'0')
	FROM sExamination.tSetupMaster STP
	Inner join sExamination.tExamination AS EXM On EXM.SetupId=STP.id
	INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
	INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = EXM.StoreLocationId
	INNER JOIN sSecurity.tUserLocation AS USR on USR.StoreLocationId=SLM.Id
	LEFT JOIN
	(
		SELECT StoreLocationId = SLM.Id,SetupId = STP.Id,EmployeeCount = COUNT(0)
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tSetupMaster STP ON EXM.SetupId = STP.id
		INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
		INNER JOIN sIp.tStoreLocationMaster SLM ON 
		--SLM.Id = STP.StoreLocationId AND 
		SLM.Id =EXM.StoreLocationId
		INNER JOIN sSecurity.tUserLocation AS USR on USR.StoreLocationId=SLM.Id
		WHERE STP.OrgId = @OrgId
		AND ParticipantSourceTypeId = 95
		AND STP.IsObsolete = 0
		AND (MainTypeId = @MainTypeId OR @MainTypeId = 0)
		AND (SetupGroupId = @SetupGroupId)
		AND USR.UserId=@rUserId
		GROUP BY SLM.Id, STP.Id
	) AS Emp ON Emp.StoreLocationId = SLM.Id AND Emp.SetupId = STP.Id
	LEFT JOIN
	(
		SELECT StoreLocationId = SLM.Id,SetupId = STP.Id,EmployeeCount = COUNT(0)
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tSetupMaster STP ON EXM.SetupId = STP.id
		INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
		INNER JOIN sIp.tStoreLocationMaster SLM ON 
		--SLM.Id = STP.StoreLocationId AND 
		SLM.Id =EXM.StoreLocationId
		INNER JOIN sSecurity.tUserLocation AS USR on USR.StoreLocationId=SLM.Id
		WHERE STP.OrgId = @OrgId
		AND ParticipantSourceTypeId = 95
		AND STP.IsObsolete = 0
		AND (MainTypeId = @MainTypeId OR @MainTypeId = 0)
		AND (SetupGroupId = @SetupGroupId)
		AND USR.UserId=@rUserId AND EXM.StatusId = 4
		GROUP BY SLM.Id, STP.Id
	) AS Emp1 ON Emp1.StoreLocationId = SLM.Id AND Emp1.SetupId = STP.Id
	LEFT JOIN
	(
		SELECT StoreLocationId = SLM.Id,SetupId = STP.Id,EmployeeCount = COUNT(0)
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tSetupMaster STP ON EXM.SetupId = STP.id
		INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
		INNER JOIN sIp.tStoreLocationMaster SLM ON 
		--SLM.Id = STP.StoreLocationId AND 
		SLM.Id =EXM.StoreLocationId
		INNER JOIN sSecurity.tUserLocation AS USR on USR.StoreLocationId=SLM.Id
		WHERE STP.OrgId = @OrgId
		AND ParticipantSourceTypeId = 95
		AND STP.IsObsolete = 0
		AND (MainTypeId = @MainTypeId OR @MainTypeId = 0)
		AND (SetupGroupId = @SetupGroupId)
		AND USR.UserId=@rUserId AND EXM.StatusId != 4
		GROUP BY SLM.Id, STP.Id
	) AS Emp2 ON Emp2.StoreLocationId = SLM.Id AND Emp2.SetupId = STP.Id
	LEFT JOIN 
	(SELECT HealthIndexCount = COUNT(DISTINCT HI.ExaminationId), StoreLocationId = SLM.Id,SetupId = STP.Id
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tHealthIndex HI ON EXM.Id = HI.ExaminationId
		INNER JOIN sExamination.tSetupMaster STP ON EXM.SetupId = STP.id
		INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = EXM.StoreLocationId
		INNER JOIN sSecurity.tUserLocation AS USR on USR.StoreLocationId=SLM.Id
		WHERE STP.OrgId = @OrgId
		AND ParticipantSourceTypeId = 95
		AND STP.IsObsolete = 0
		AND (MainTypeId = @MainTypeId OR @MainTypeId = 0)
		AND (SetupGroupId = @SetupGroupId)
		AND USR.UserId=@rUserId
		GROUP BY SLM.Id, STP.Id
	) AS HealthIndex ON HealthIndex.StoreLocationId = SLM.Id AND HealthIndex.SetupId = STP.Id
	LEFT JOIN
	(
		SELECT DignosisTracker = COUNT(EXM.Id), StoreLocationId = SLM.Id,SetupId = STP.Id
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE ON EXM.Id = DTE.ExaminationId
		INNER JOIN sExamination.tSetupMaster STP ON EXM.SetupId = STP.id
		INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = EXM.StoreLocationId
		INNER JOIN sSecurity.tUserLocation AS USR on USR.StoreLocationId=SLM.Id
		INNER JOIN [sHrm].[tEmployeeCompanyMaster] ECM ON ECM.Id = EXM.EmployeeCompanyId
		INNER JOIN [sHrm].[tCompanyGroupMaster] CGM ON CGM.Id = ECM.CompanyGroupId
		INNER JOIN [sHrm].[tVerticalMaster] VTM ON VTM.ID = CGM.VerticalId
		INNER JOIN [sHrm].[tSectorMaster] SCT ON SCT.Id = VTM.SectorId
		INNER JOIN [sCommon].[tCompanyInformation] CMP ON CMP.ID = SCT.OrgId
		INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id = SLM.LocationId
		INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
		INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id = DPT.DepartmentGroupId
		INNER JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id = DPG.FunctionId
		LEFT JOIN [sCommon].[tLocationSubGroupMaster] LSG ON LSG.Id = LMN.LocationSubGroupId AND ((LMN.LocationSubGroupId =0 ) OR (0 = 0))
		LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id = LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId = 0) OR (0 = 0))
		WHERE STP.OrgId = @OrgId
		AND ParticipantSourceTypeId = 95
		AND STP.IsObsolete = 0
		AND (MainTypeId = @MainTypeId OR @MainTypeId = 0)
		AND (SetupGroupId = @SetupGroupId)
		AND USR.UserId=@rUserId
		GROUP BY SLM.Id, STP.Id
	)  AS DiagnosisTracker ON DiagnosisTracker.StoreLocationId = SLM.Id AND DiagnosisTracker.SetupId = STP.Id
	WHERE STP.OrgId = @OrgId
	AND STP.IsObsolete = 0
	AND (MainTypeId = @MainTypeId OR @MainTypeId = 0)
	AND (SetupGroupId = @SetupGroupId)
	AND USR.UserId=@rUserId
	--ORDER BY SLM.Title, STP.Title
	
	SELECT @ResultString = @ResultString + '<tr>
	<td><input group="Header" type="checkbox" SetupId="'+ SetupId+'"  StoreLocationId="'+ StoreLocationId+'"  onclick="checkUncheckOne(this);" tabindex="'+CONVERT(varchar, tId+3)+'" /></th></td>
	<td>' + CONVERT(varchar, tId) + '</th></td><td>' + StoreLocationName + '</th></td><td>' + SetupName + '</th></td>
	<td align="center" class="text-info cursor-pointer"'+ case when EmployeeCount > 0 then 'onclick="myfunction1(''EmployeeCount'',this,'''+replace(convert(varchar(50),newid()),'-','')+''',''' + StoreLocationId + ''',''' + SetupId + ''');");"' else '' end  +'>' + EmployeeCount + '</th></td>
	<td align="center" class="text-info cursor-pointer"'+ case when CompletedCount > 0 then 'onclick="myfunction1(''CompletedCount'',this,'''+replace(convert(varchar(50),newid()),'-','')+''',''' + StoreLocationId + ''',''' + SetupId + ''');");"' else '' end  +'>' + CompletedCount + '</th></td>
	<td align="center" class="text-info cursor-pointer"'+ case when PendingCount > 0 then 'onclick="myfunction1(''PendingCount'',this,'''+replace(convert(varchar(50),newid()),'-','')+''',''' + StoreLocationId + ''',''' + SetupId + ''');");"' else '' end  +'>' + PendingCount + '</th></td>
	<td align="center"><input type="checkbox" disabled="disabled" group="Health" ' + case when IsHealthIndexUpdated='1' then 'checked="checked"' else '' end +'  /><span class="text-info cursor-pointer"'+ case when HealthIndexCount > 0 then 'onclick="myfunction1(''HealthIndexCount'',this,'''+replace(convert(varchar(50),newid()),'-','')+''',''' + StoreLocationId + ''',''' + SetupId + ''');");' else '' end  +'>(' + HealthIndexCount + ')</span></th></td>
	<td align="center"><input type="checkbox" disabled="disabled" group="History" ' + case when IsEmployeeHistoryUpdated='1' then 'checked="checked"' else '' end +'  /></th></td>
	<td align="center"><input type="checkbox" disabled="disabled" group="Tracker" ' + case when IsDiagnosisTrackerUpdated='1' then 'checked="checked"' else '' end +'  /><span class="text-info cursor-pointer"'+ case when DiagnosisTrackerCount > 0 then 'onclick="myfunction1(''DiagnosisTrackerCount'',this,'''+replace(convert(varchar(50),newid()),'-','')+''',''' + StoreLocationId + ''',''' + SetupId + ''');");' else '' end  +'>('+ DiagnosisTrackerCount +')</span></th></td>
	<td align="center"><input type="checkbox" disabled="disabled" group="Publish" ' + case when IsPublishSetup='1' then 'checked="checked"' else '' end +'  /></th></td>
	<td align="center"><input type="checkbox" disabled="disabled" group="Close" ' + case when IsClosed='1' then 'checked="checked"' else '' end +'  /></th></td></tr>'
	FROM @TableOne ORDER BY tId
	
	SELECT ResultString = @ResultString,len=len(@ResultString)
	SELECT * FROM @TableOne ORDER BY tId
END
GO
PRINT N'Altering Procedure [sHospitalization].[pGetDoctorHospitalizationReview]...';


GO
      
CREATE OR ALTER PROCEDURE [sHospitalization].[pGetDoctorHospitalizationReview]      
AS      
BEGIN    
    
  Select DISTINCT EM.Id,    
  ISNULL(    
    CASE      
     WHEN ISNULL(EM.EmployeePrefix, '') = ''      
     THEN EM.FirstName + ' ' + EM.LastName      
     ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName      
    END,     
   '') AS Title      
  from [sHospitalization].[tIntimationDetails]  EH      
  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.AssignedDoctorId      
  
    
  UNION     
    
  Select DISTINCT EM.Id,    
  ISNULL(    
    CASE      
     WHEN ISNULL(EM.EmployeePrefix, '') = ''      
     THEN EM.FirstName + ' ' + EM.LastName      
     ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName      
    END,     
   '') AS Title      
  from [sHospitalization].[tIntimationDetails]  EH    
  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.AssignedDoctorId      
  
    
END
GO
PRINT N'Altering Procedure [sHospitalization].[pHospitalizationAssignDoctorListGet]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pHospitalizationAssignDoctorListGet]      
  @rOrgId BIGINT,                
  @rId BIGINT = 0,      
  @rAssignTypeId BIGINT = 0,      
  @rAssignSubTypeId BIGINT = 0,      
  @rEmployeeId BIGINT = 0,      
  @rDesignationId BIGINT = 0      
AS    
BEGIN    
    SET NOCOUNT ON;    
    
    SELECT      
        LI.Id,    
        LI.AssignTypeId,    
  
        -- ✅ Static + Dynamic AssignTypeName  
        CASE   
            WHEN LI.AssignTypeId = 2010 THEN 'Organization'    
            WHEN LI.AssignTypeId = 2012 THEN 'Business'    
            WHEN LI.AssignTypeId = 1014 THEN 'Sub Location'    
            WHEN EXISTS (  
                SELECT 1   
                FROM sCommon.tStateMaster SM   
                WHERE SM.CountryId = LI.AssignTypeId  
            ) THEN 'State / Zone'  -- ✅ dynamic check  
            ELSE ''    
        END AS AssignTypeName,    
    
        LI.AssignSubTypeId,    
  
        -- ✅ Entity title logic based on type (mirroring pEntityMasterGet)  
        COALESCE(  
            CASE   
                WHEN LI.AssignTypeId = 2010 THEN CI.Title    
                WHEN LI.AssignTypeId = 2012 THEN SM.Title    
                WHEN LI.AssignTypeId = 1014 THEN SLM.Title    
                WHEN EXISTS (  
                    SELECT 1   
                    FROM sCommon.tStateMaster SMX   
                    WHERE SMX.CountryId = LI.AssignTypeId  
                ) THEN SM2.Title   -- ✅ pull from tStateMaster dynamically  
                ELSE ''    
            END, ''  
        ) AS AssignSubTypeName,    
    
        LI.DoctorEmployeeId,     
        LI.DesignationId,    
  
        -- ✅ Doctor designation mapping  
        CASE LI.DesignationId    
            WHEN 1 THEN 'Business Doctor'    
            WHEN 2 THEN 'Central Doctor'    
            WHEN 3 THEN 'Site Doctor'    
            WHEN 4 THEN 'Zonal Doctor'    
            ELSE ''    
        END AS DesignationName,    
    
        LI.IsObsolete,    
        LI.CreatedUserId,    
        LI.CreatedDateTime,    
        LI.UpdatedUserId,    
        LI.UpdatedDateTime,    
        LI.OrgId,    
        EM.Code AS EmployeeCode,    
        ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName  ,  
  CASE   
    WHEN LI.IsObsolete = 0 THEN 'Active'  
    WHEN LI.IsObsolete = 1 THEN 'Inactive'  
     END AS IsActive    
    
    FROM [sHospitalization].[tIntimationAssignedDoctor] LI    
    INNER JOIN sHrm.tEmployeeMaster EM   
        ON EM.Id = LI.DoctorEmployeeId    
          
    
    LEFT JOIN sCommon.tCompanyInformation CI ON CI.Id = LI.AssignSubTypeId    
    LEFT JOIN sHrm.tEmployeeCompanyMaster ODS ON ODS.Id = LI.AssignSubTypeId    
    LEFT JOIN sHrm.tSectorMaster SM ON SM.Id = LI.AssignSubTypeId    
    LEFT JOIN sHrm.tVerticalMaster VM ON VM.Id = LI.AssignSubTypeId    
    LEFT JOIN sHrm.tCompanyGroupMaster CGM ON CGM.Id = LI.AssignSubTypeId    
    LEFT JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = LI.AssignSubTypeId    
    LEFT JOIN sCommon.tFunctionMaster FM ON FM.Id = LI.AssignSubTypeId    
    LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON DGM.Id = LI.AssignSubTypeId    
    LEFT JOIN sCommon.tOrganizationDepartmentMaster ODGM ON ODGM.Id = LI.AssignSubTypeId    
    LEFT JOIN sHrm.tGradeMaster GM ON GM.Id = LI.AssignSubTypeId    
    LEFT JOIN sCommon.tAgeGroupMaster AGM ON AGM.Id = LI.AssignSubTypeId    
    LEFT JOIN sCommon.tStateMaster SM2 ON SM2.Id = LI.AssignSubTypeId   
    
    WHERE   
        (@rAssignTypeId = 0 OR LI.AssignTypeId = @rAssignTypeId)    
        AND (@rAssignSubTypeId = 0 OR LI.AssignSubTypeId = @rAssignSubTypeId)    
        AND (@rEmployeeId = 0 OR LI.DoctorEmployeeId = @rEmployeeId)    
        AND (@rDesignationId = 0 OR LI.DesignationId = @rDesignationId)    
        AND (@rOrgId = 0 OR LI.OrgId = @rOrgId)  
        AND (@rId = 0 OR LI.Id = @rId);   
END;
GO
PRINT N'Altering Procedure [sHospitalization].[ptIntimationAssignedDoctorAdd]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[ptIntimationAssignedDoctorAdd]      
    @rId                INT,      
    @rOrgId             INT,      
    @rAssignTypeId      BIGINT,      
    @rAssignSubTypeId   BIGINT,      
    @rDoctorEmployeeId  BIGINT,      
    @rDesignationId     INT,      
    @rIsObsolete        BIT,      
    @rCreatedUserId     BIGINT,      
    @rUpdatedUserId     BIGINT       
AS      
BEGIN      
    SET NOCOUNT ON;      
      
    BEGIN TRY      
        -- If new record      
        IF @rId = 0      
        BEGIN      
            -- Check for duplicates      
            IF EXISTS (      
                SELECT 1      
                FROM sHospitalization.tIntimationAssignedDoctor      
                WHERE OrgId = @rOrgId      
                  AND AssignTypeId = @rAssignTypeId      
                  AND AssignSubTypeId = @rAssignSubTypeId      
                  AND DoctorEmployeeId = @rDoctorEmployeeId      
                 -- AND IsObsolete = 0   -- optional: only consider active records      
            )      
            BEGIN      
                SELECT 11 AS RESULT;  -- duplicate exists      
                RETURN;      
            END      
      
            DECLARE @lNextNumber INT;      
      
            EXEC sCommon.pTableRowIdGet       
                @rOrgId,      
                'sHospitalization.tIntimationAssignedDoctor',      
                0, 1, 1,      
                @outNextNumber = @lNextNumber OUTPUT;      
      
            INSERT INTO sHospitalization.tIntimationAssignedDoctor      
            (      
                Id,      
                AssignTypeId,      
                AssignSubTypeId,      
                DoctorEmployeeId,      
                DesignationId,      
                IsObsolete,      
                CreatedUserId,      
                CreatedDateTime,      
                OrgId      
            )      
            VALUES      
            (      
                @lNextNumber,      
                @rAssignTypeId,      
                @rAssignSubTypeId,      
                @rDoctorEmployeeId,      
                @rDesignationId,      
                @rIsObsolete,      
                @rCreatedUserId,      
                sCommon.fGetDate(),      
                @rOrgId      
            );      
      
            SELECT @lNextNumber AS RESULT;      
        END      
        ELSE      
        BEGIN      
		 IF EXISTS (      
                SELECT 1      
                FROM sHospitalization.tIntimationAssignedDoctor      
                WHERE OrgId = @rOrgId      
                  AND AssignTypeId = @rAssignTypeId      
                  AND AssignSubTypeId = @rAssignSubTypeId      
                  AND DoctorEmployeeId = @rDoctorEmployeeId      
                 -- AND IsObsolete = 0   -- optional: only consider active records      
            )      
            BEGIN      
                SELECT 11 AS RESULT;  -- duplicate exists      
                RETURN;      
            END      
      
            -- Update existing record      
            UPDATE sHospitalization.tIntimationAssignedDoctor      
            SET      
                AssignTypeId     = @rAssignTypeId,      
                AssignSubTypeId  = @rAssignSubTypeId,      
                DoctorEmployeeId = @rDoctorEmployeeId,      
                DesignationId    = @rDesignationId,      
                IsObsolete       = @rIsObsolete,      
                UpdatedUserId    = @rUpdatedUserId,      
                UpdatedDateTime  = sCommon.fGetDate()      
            WHERE Id = @rId;      
      
            SELECT @rId AS RESULT;      
        END      
    END TRY      
    BEGIN CATCH      
         SELECT       
            -1 AS RESULT,      
            ERROR_NUMBER() AS ErrorNumber,      
            ERROR_SEVERITY() AS ErrorSeverity,      
            ERROR_STATE() AS ErrorState,      
            ERROR_LINE() AS ErrorLine,      
            ERROR_MESSAGE() AS ErrorMessage;      
    END CATCH      
END;
GO
PRINT N'Altering Procedure [sHrm].[pMobEmployeeMasterListingGet]...';


GO
CREATE OR ALTER PROCEDURE [sHrm].[pMobEmployeeMasterListingGet]

(

	@rOrgId INT,

	@rSetupGroupId INT,

	@rCode VARCHAR(20) = '',

	@rName VARCHAR(200) = '',	

	@rSurName VARCHAR(200) = '',

	@rEmployeeId BIGINT = 0,

	@rHealthIndicatorId INT=0,

	@rCodeLike VARCHAR(200) = ''

)

AS
 
	IF(@rSurName IS NULL)	

		SET @rSurName = ''

	IF(@rCode IS NULL)	

		SET @rCode = ''	

	IF(@rName IS NULL)	

		SET @rName = ''	

	SET NOCOUNT ON

	BEGIN

	SET @rName = sCommon.fSearchStringGet(@rName)

	SET @rSurName = sCommon.fSearchStringGet(@rSurName)

	DECLARE @lCondition1 VARCHAR(MAX)='',

			@lCondition2 VARCHAR(MAX)='',

			@lCondition3 VARCHAR(MAX)='',

			@lCondition4 VARCHAR(MAX)=''

	DECLARE @lCondition VARCHAR(MAX) = '',

			@lQuery VARCHAR(MAX)=''

	SELECT @lCondition1 = @lCondition1 + CASE WHEN EntitySourceTypeId = 2012 THEN

	CASE WHEN @lCondition1 = '' THEN ' and SCT.Id = ' + convert(VARCHAR,EntitySourceId)	

	ELSE ' or SCT.Id = ' + convert(VARCHAR,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead WHERE HeadEmployeeId = @rEmployeeId AND EntitySourceTypeId = 2012

	SELECT @lCondition2 = @lCondition2 + CASE EntitySourceTypeId WHEN 2013 THEN

	CASE WHEN @lCondition2 = '' THEN ' and VTM.Id = ' + CONVERT(VARCHAR,EntitySourceId)

	ELSE ' or VTM.Id = ' + convert(VARCHAR,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead WHERE HeadEmployeeId = @rEmployeeId and EntitySourceTypeId = 2013

	SELECT @lCondition3 = @lCondition3 + case EntitySourceTypeId WHEN 1014 THEN

	CASE WHEN @lCondition3 = '' THEN ' and E.StoreLocationId = ' + CONVERT(VARCHAR,EntitySourceId)

	ELSE ' or E.StoreLocationId = ' + convert(varchar,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead WHERE HeadEmployeeId = @rEmployeeId AND EntitySourceTypeId = 1014

	SELECT @lCondition4 = @lCondition4 + case EntitySourceTypeId WHEN 2016 THEN

	CASE WHEN @lCondition4 = '' THEN ' and DGM.FunctionId = ' + CONVERT(VARCHAR,EntitySourceId)

	ELSE ' or DGM.FunctionId = ' + CONVERT(VARCHAR,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead where HeadEmployeeId = @rEmployeeId and EntitySourceTypeId = 2016

	IF CHARINDEX(' or ',@lCondition1) > 0

	BEGIN

		SELECT @lCondition1 = REPLACE(@lCondition1,'and','and (')

		SELECT @lCondition1 = @lCondition1 + ') '

	END	

	IF CHARINDEX(' or ',@lCondition2) > 0

	BEGIN	

		SELECT @lCondition2 = REPLACE(@lCondition2,'and','and (')

		SELECT @lCondition2 = @lCondition2 + ') '

	END	

	IF CHARINDEX(' or ',@lCondition3) > 0

	BEGIN

		SELECT @lCondition3 = REPLACE(@lCondition3,'and','and (')

		SELECT @lCondition3 = @lCondition3 + ') '

	end

	IF CHARINDEX(' or ',@lCondition4) > 0

	BEGIN

		SELECT @lCondition4 = REPLACE(@lCondition4,'and','and (')

		SELECT @lCondition4 = @lCondition4 + ') '

	END

	SELECT @lCondition =  CASE WHEN isnull(@lCondition1,'') = '' THEN '' ELSE @lCondition1 END

	+ CASE WHEN isnull(@lCondition2,'') = '' THEN '' ELSE @lCondition2 END

	+ CASE WHEN isnull(@lCondition3,'') = '' THEN '' ELSE @lCondition3 END

	+ CASE WHEN isnull(@lCondition4,'') = '' THEN '' ELSE @lCondition4 END

	--select @lCondition

	SELECT @lQuery = 'SELECT EM.Id AS EmployeeId,S.Id as SetupId,S.Title as SetupName,E.StoreLocationId,SLM.Title as StoreLocationName,

	CASE WHEN EM.IsTemporary = 0 THEN EM.Code ELSE EM.TemporaryCode END AS Code,

	ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS EmployeeName,SCT.Id as SectorId, MTM.Id AS MainTypeId, S.SubTypeId AS SubTypeId

	FROM sHrm.tEmployeeMaster EM

	inner join sExamination.tExamination E on EM.Id=ParticipantSourceId and ParticipantSourceTypeId=95 and isnull(E.IsPublish,0) = 1   

	inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StoreLocationId

	inner join sExamination.tsetupMaster S on E.SetupId = S.Id	

	inner join sExamination.tMainTypeMaster MTM ON MTM.Id = s.SubTypeId

	left JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=E.EmployeeCompanyId

	left JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId

	left JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId

	left JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId	

	left join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id=E.OrganizationDepartmentId

	left join sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id

	left JOIN sExamination.tDiagnosis AS DIA ON    E.Id=DIA.SourceId

	left join [sExamination].[tHealthIndicatorMaster] HIM on HIM.Id=DIA.HealthIndicatorId

	WHERE EM.OrgId = ' + CONVERT(VARCHAR,@rOrgId) + '	

	AND (EM.Code = ''' + @rCode + ''' OR ''' + @rCode + ''' = '''')

	AND (EM.FirstName like ''' + @rName + '%'' OR ''' + @rName + ''' = '''')

	AND (EM.LastName like ''' + @rSurName + '%'' OR ''' + @rSurName + ''' = '''')

	AND (S.SetupGroupId = ' + CONVERT(VARCHAR,@rSetupGroupId) + ' OR ' + CONVERT(VARCHAR,@rSetupGroupId) + ' = 0)

	AND (DIA.HealthIndicatorId = ' + CONVERT(VARCHAR,@rHealthIndicatorId) + ' or ' + CONVERT(VARCHAR,ISNULL(@rHealthIndicatorId,0)) + ' = 0) 

	AND E.StatusId = 4 '

	+ @lCondition + 

	CASE WHEN LEN(@rCodeLike) > 0 THEN ' AND EXISTS (SELECT 1 FROM sCommon.fnSplit(''' + @rCodeLike + ''', '','') AS SPLIT WHERE SPLIT.item = EM.Code) ' ELSE '' 

	END

	+  'Order By EM.Code'

	EXEC (@lQuery)

END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGet]...';


GO

CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGet]        
 @rUserId [bigint],        
 @rMenuId int = 0,        
 @rResourceTypeId int= 0,        
 @rOrgId int,        
 @rflg bit = 0         
         
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
        
BEGIN        
declare @result varchar(15)='False'        
Select @result = [dbo].[fPHIPermissionUserwise](@rUserId,@rOrgId)        
        
if(@rflg=0)        
         
 begin        
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
  BEGIN        
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else         
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,        
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermissionUser P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
      where p.userid= @rUserId 
	  AND T.Id not in (20834,20853)            
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId               
      WHERE         
      (Menu.IsObsolete = 0)         
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
              
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
  ORDER BY         
   ParentMenuID          
  END        
         
 ELSE         
  BEGIN        
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else        
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
 case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,       
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete        
            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermission P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
       INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
      --WHERE         
      -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
	  WHERE T.Id not in (20834,20853)        
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
      WHERE         
      (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
      --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
           
           
             
  ORDER BY         
   ParentMenuID        
        
   --SELECT DISTINCT Menu.Id AS MenuID,         
  --  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
  --  Menu.Title AS MenuTitle,         
  --  Menu.TitleResourceKeyId AS MenuResourceKey,         
  --  Screen.Title AS ScreenTitle,        
  --  Screen.TitleResourceKeyId AS ScreenResourceKey,        
  --  Screen.Page AS PageURL        
  --FROM sSecurity.tMenu Menu        
  --LEFT OUTER JOIN sSecurity.tScreen Screen        
  -- ON Menu.ScreenId = Screen.Id        
  --LEFT OUTER JOIN sSecurity.tPermission Permission        
  -- ON Screen.TaskId = Permission.TaskId        
  --WHERE Menu.IsObsolete = 0 AND        
  --  Screen.IsObsolete = 0 AND        
  --  Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND        
  --  (Permission.Permission & 2) = 2        
  --ORDER BY ParentMenuID        
  END        
 end        
else        
 begin        
  IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
   begin        
    SELECT        
        MenuID,        
        ModuleId,        
        ParentMenuID,        
        MenuTitle,          
        ScreenTitle,           
        case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else  PageURL end PageURL,       
        ScreenId,        
        Permission,        
        OrderNumber,          
        TaskId,          
        PageURL  AS PagePath,        
        MenuIsObsolete,        
        Icon          
          FROM        
           (        
           SELECT Menu.Id AS MenuID,         
		  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
          Menu.Title AS MenuTitle,           
          ISNULL(Screen.Title, '') AS ScreenTitle,            
          --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
          ISNULL(Screen.Page, '') AS PageURL,        
          ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(OrderNumber, 0) AS OrderNumber,        
          ISNULL(Screen.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          case when Menu.Id=18 then 'fa fa-wrench'         
         when Menu.Id=35 then 'fa fa-support'         
         when Menu.Id=15 then 'fa fa-tasks'         
         when Menu.Id=22 then 'fa fa-user'         
         when Menu.Id=34 then 'fa fa-bar-chart'        
         when Menu.Id=31 then 'icon-hourglass'        
         when Menu.Id=33 then 'fa fa-exclamation-triangle'        
         when Menu.Id=11 then 'fa fa-medkit'        
         when Menu.Id=12 then 'fa fa-hospital-o'        
         when Menu.Id=10 then 'fa fa-building-o'        
         when Menu.Id=30 then 'fa fa-book'        
         when Menu.Id=56 then 'fa fa-list'        
         when Menu.Id=3023 then 'fa fa-stethoscope'
		 when Menu.Id=191810371 then 'fa fa-heart'
		 when Menu.Id=191810373 then 'fa fa-user-md'
         else ISNULL(Screen.IconPath,'') end AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen        
          ON Menu.ScreenId = Screen.Id            
           
         LEFT OUTER JOIN (         
          SELECT         
           P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId) TBL2        
          ON         
           Screen.TaskId = TBL2.TaskId         
            LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
          WHERE         
          (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
          AND ISNULL(Screen.IsObsolete, 0) = 0        
          --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
          AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373))        
          AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
          AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         union        
           
          SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
          ISNULL(Menu.Id, 0) AS ParentMenuID,         
          Screen1.Title AS MenuTitle,           
          ISNULL(Screen1.Title, '') AS ScreenTitle,            
          ISNULL(Screen1.Page, '')  AS PageURL,        
          ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
          ISNULL(Screen1.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          ISNULL(Screen1.IconPath,'') AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
         LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
         LEFT OUTER JOIN (         
          SELECT         
         P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId        
          ) TBL2        
          ON Screen1.TaskId = TBL2.TaskId         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen1.IsObsolete, 0) = 0        
         --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) or Menu.Id in (3023))        
         AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
         )         
          MenuTable          
          --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
         WHERE         
       MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
          AND         
          ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
          AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
          AND MenuIsObsolete = 0        
          AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
         ORDER BY         
          ParentMenuID        
   end        
  else        
   begin        
    SELECT        
         MenuID,        
         ModuleId,        
         ParentMenuID,        
         MenuTitle,          
         ScreenTitle,           
         case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else PageURL end PageURL,        
         ScreenId,        
         Permission,        
         OrderNumber,          
         TaskId,          
       PageURL  AS PagePath,        
       MenuIsObsolete,        
       Icon          
        FROM        
       (        
       SELECT Menu.Id AS MenuID,         
         ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
         Menu.Title AS MenuTitle,           
         ISNULL(Screen.Title, '') AS ScreenTitle,            
         --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
         ISNULL(Screen.Page, '') AS PageURL,        
         ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(OrderNumber, 0) AS OrderNumber,        
         ISNULL(Screen.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         case when Menu.Id=18 then 'fa fa-wrench'         
        when Menu.Id=35 then 'fa fa-support'         
        when Menu.Id=15 then 'fa fa-tasks'         
        when Menu.Id=22 then 'fa fa-user'         
        when Menu.Id=34 then 'fa fa-bar-chart'        
        when Menu.Id=31 then 'icon-hourglass'        
        when Menu.Id=33 then 'fa fa-exclamation-triangle'        
        when Menu.Id=11 then 'fa fa-medkit'        
        when Menu.Id=12 then 'fa fa-hospital-o'        
        when Menu.Id=10 then 'fa fa-building-o'        
        when Menu.Id=30 then 'fa fa-book'        
        when Menu.Id=56 then 'fa fa-list'        
        when Menu.Id=3023 then 'fa fa-stethoscope'
		when Menu.Id=191810371 then 'fa fa-heart'
		when Menu.Id=191810373 then 'fa fa-user-md'
        else ISNULL(Screen.IconPath,'') end AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen        
         ON Menu.ScreenId = Screen.Id            
           
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
          sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
         --WHERE         
         -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
		 Where T.Id not in (20834,20853)        
         GROUP BY         
          P.TaskId) TBL2        
         ON         
          Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen.IsObsolete, 0) = 0        
         --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373))        
         AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,
		 191810363,191810364,191810365,191810366,191810367,191810368)       
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
              
        union        
           
         SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
         ISNULL(Menu.Id, 0) AS ParentMenuID,         
         Screen1.Title AS MenuTitle,           
         ISNULL(Screen1.Title, '') AS ScreenTitle,            
         ISNULL(Screen1.Page, '')  AS PageURL,        
         ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
         ISNULL(Screen1.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         ISNULL(Screen1.IconPath,'') AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
        LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
       sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId               
         where T.Id not in (20834,20853) 
		 GROUP BY         
          P.TaskId        
         ) TBL2        
         ON Screen1.TaskId = TBL2.TaskId         
        WHERE         
        (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
        AND ISNULL(Screen1.IsObsolete, 0) = 0        
        --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
        AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) or Menu.Id in (3023))        
        AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
        )         
         MenuTable          
         --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
        WHERE         
         MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
         AND         
         ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
         AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
         AND MenuIsObsolete = 0        
         AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
        ORDER BY         
         ParentMenuID        
   end        
        
 end        
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGetRoleWise]...';


GO

CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGetRoleWise]        
 @rUserId [bigint],        
 @rMenuId int = 0,        
 @rResourceTypeId int= 0,        
 @rOrgId int,        
 @rflg bit = 0,   
 @rRoleId int
         
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
        
BEGIN        
declare @result varchar(15)='False'        
Select @result = [dbo].[fPHIPermissionUserwise](@rUserId,@rOrgId)        
        
if(@rflg=0)        
         
 begin        
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
  BEGIN   
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else         
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,        
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermissionUser P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
      where p.userid= @rUserId 
	  AND T.Id not in (20834,20853)            
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId               
      WHERE         
      (Menu.IsObsolete = 0)         
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
              
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
  ORDER BY         
   ParentMenuID          
  END        
         
 ELSE         
  BEGIN    
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else        
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
 case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,       
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete        
            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermission P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
       INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  RoleId = @rRoleId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
      --WHERE         
      -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
	  WHERE T.Id not in (20834,20853)        
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
      WHERE         
      (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368) )         
      MenuTable          
      --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
           
           
             
  ORDER BY         
   ParentMenuID        
        
   --SELECT DISTINCT Menu.Id AS MenuID,         
  --  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
  --  Menu.Title AS MenuTitle,         
  --  Menu.TitleResourceKeyId AS MenuResourceKey,         
  --  Screen.Title AS ScreenTitle,        
  --  Screen.TitleResourceKeyId AS ScreenResourceKey,        
  --  Screen.Page AS PageURL        
  --FROM sSecurity.tMenu Menu        
  --LEFT OUTER JOIN sSecurity.tScreen Screen        
  -- ON Menu.ScreenId = Screen.Id        
  --LEFT OUTER JOIN sSecurity.tPermission Permission        
  -- ON Screen.TaskId = Permission.TaskId        
  --WHERE Menu.IsObsolete = 0 AND        
  --  Screen.IsObsolete = 0 AND        
  --  Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND        
  --  (Permission.Permission & 2) = 2        
  --ORDER BY ParentMenuID        
  END        
 end        
else        
 begin   
 
  IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
   begin 
   
    SELECT        
        MenuID,        
        ModuleId,        
        ParentMenuID,        
        MenuTitle,          
        ScreenTitle,           
        case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else  PageURL end PageURL,       
        ScreenId,        
        Permission,        
        OrderNumber,          
        TaskId,          
        PageURL  AS PagePath,        
        MenuIsObsolete,        
        Icon          
          FROM        
           (        
           SELECT Menu.Id AS MenuID,         
		  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
          Menu.Title AS MenuTitle,           
          ISNULL(Screen.Title, '') AS ScreenTitle,            
          --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
          ISNULL(Screen.Page, '') AS PageURL,        
          ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(OrderNumber, 0) AS OrderNumber,        
          ISNULL(Screen.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          case when Menu.Id=18 then 'fa fa-wrench'         
         when Menu.Id=35 then 'fa fa-support'         
         when Menu.Id=15 then 'fa fa-tasks'         
         when Menu.Id=22 then 'fa fa-user'         
         when Menu.Id=34 then 'fa fa-bar-chart'        
         when Menu.Id=31 then 'icon-hourglass'        
         when Menu.Id=33 then 'fa fa-exclamation-triangle'        
         when Menu.Id=11 then 'fa fa-medkit'        
         when Menu.Id=12 then 'fa fa-hospital-o'        
         when Menu.Id=10 then 'fa fa-building-o'        
         when Menu.Id=30 then 'fa fa-book'        
         when Menu.Id=56 then 'fa fa-list'        
         when Menu.Id=3023 then 'fa fa-stethoscope'
		 when Menu.Id=191810371 then 'fa fa-heart'
		 when Menu.Id=191810373 then 'fa fa-user-md'
         else ISNULL(Screen.IconPath,'') end AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen        
          ON Menu.ScreenId = Screen.Id            
           
         LEFT OUTER JOIN (         
          SELECT         
           P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId) TBL2        
          ON         
           Screen.TaskId = TBL2.TaskId         
            LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
          WHERE         
          (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
          AND ISNULL(Screen.IsObsolete, 0) = 0        
          --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
          AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373))        
          AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
          AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         union        
           
          SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
          ISNULL(Menu.Id, 0) AS ParentMenuID,         
          Screen1.Title AS MenuTitle,           
          ISNULL(Screen1.Title, '') AS ScreenTitle,            
          ISNULL(Screen1.Page, '')  AS PageURL,        
          ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
          ISNULL(Screen1.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          ISNULL(Screen1.IconPath,'') AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
         LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
         LEFT OUTER JOIN (         
          SELECT         
         P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId        
          ) TBL2        
          ON Screen1.TaskId = TBL2.TaskId         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen1.IsObsolete, 0) = 0        
         --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) or Menu.Id in (3023))        
         AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
         )         
          MenuTable          
          --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
         WHERE         
       MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
          AND         
          ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
          AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
          AND MenuIsObsolete = 0        
          AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
         ORDER BY         
          ParentMenuID        
   end        
  else        
   begin  
  
    SELECT        
         MenuID,        
         ModuleId,        
         ParentMenuID,        
         MenuTitle,          
         ScreenTitle,           
         case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else PageURL end PageURL,        
         ScreenId,        
         Permission,        
         OrderNumber,          
         TaskId,          
       PageURL  AS PagePath,        
       MenuIsObsolete,        
       Icon          
        FROM        
       (        
       SELECT Menu.Id AS MenuID,         
         ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
         Menu.Title AS MenuTitle,           
         ISNULL(Screen.Title, '') AS ScreenTitle,            
         --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
         ISNULL(Screen.Page, '') AS PageURL,        
         ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(OrderNumber, 0) AS OrderNumber,        
         ISNULL(Screen.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         case when Menu.Id=18 then 'fa fa-wrench'         
        when Menu.Id=35 then 'fa fa-support'         
        when Menu.Id=15 then 'fa fa-tasks'         
        when Menu.Id=22 then 'fa fa-user'         
        when Menu.Id=34 then 'fa fa-bar-chart'        
        when Menu.Id=31 then 'icon-hourglass'        
        when Menu.Id=33 then 'fa fa-exclamation-triangle'        
        when Menu.Id=11 then 'fa fa-medkit'        
        when Menu.Id=12 then 'fa fa-hospital-o'        
        when Menu.Id=10 then 'fa fa-building-o'        
        when Menu.Id=30 then 'fa fa-book'        
        when Menu.Id=56 then 'fa fa-list'        
        when Menu.Id=3023 then 'fa fa-stethoscope'  
		when Menu.Id=191810371 then 'fa fa-heart'
		when Menu.Id=191810373 then 'fa fa-user-md'
        else ISNULL(Screen.IconPath,'') end AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen        
         ON Menu.ScreenId = Screen.Id            
           
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
          sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  RoleId = @rRoleId and UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
         --WHERE         
         -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
		 Where T.Id not in (20834,20853)        
         GROUP BY         
          P.TaskId) TBL2        
         ON         
          Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen.IsObsolete, 0) = 0        
         --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373))        
         AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
              
        union        
           
         SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
         ISNULL(Menu.Id, 0) AS ParentMenuID,         
         Screen1.Title AS MenuTitle,           
         ISNULL(Screen1.Title, '') AS ScreenTitle,            
         ISNULL(Screen1.Page, '')  AS PageURL,        
         ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
         ISNULL(Screen1.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         ISNULL(Screen1.IconPath,'') AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
        LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
       sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE RoleId = @rRoleId and UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId               
         where T.Id not in (20834,20853) 
		 GROUP BY         
          P.TaskId        
         ) TBL2        
         ON Screen1.TaskId = TBL2.TaskId         
        WHERE         
        (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
        AND ISNULL(Screen1.IsObsolete, 0) = 0        
        --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
        AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371,191810373) or Menu.Id in (3023))        
        AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
        )         
         MenuTable          
         --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
        WHERE         
         MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
         AND         
         ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
         AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
         AND MenuIsObsolete = 0        
         AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
        ORDER BY         
         ParentMenuID        
   end        
        
 end        
END

GO
PRINT N'Altering Procedure [sSupport].[pHealthSurveyAnalysisGet]...';


GO
--exec [sSupport].[pHealthSurveyAnalysisGet] 9999,0

CREATE OR ALTER PROCEDURE [sSupport].[pHealthSurveyAnalysisGet]
(
	@rOrgId smallint,
	@rAssignSurveyId int,
	@rEmployeeCode nvarchar(100),
	@rEmployeeName nvarchar(200),
	@rDepartmentId int
 )
AS
SET NOCOUNT ON
BEGIN	
	select HSRM.Id as Id,HSRM.AssignSurveyId as AssignSurveyId,HSRM.SourceId as EmployeeId,ECS.Code as EmployeeCode,ECS.Name as EmployeeName,ASM.Title as Title,ECS.OrganizationDepartment as Department
	,ASD.EarnedPoints as EarnedPoint,ASD.TotalPoints as TotalPoint, ASD.Percentage,ASD.IndicatorName
		from sSupport.tHealthSurveyResponseMaster HSRM
		inner join sSupport.tAssignSurveyMaster ASM on ASM.Id=HSRM.AssignSurveyId
		inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId and ASD.SourceId=HSRM.SourceId
		--inner join sSupport.tHealthSurveyMaster HSM on HSM.Id=ASM.Id
		inner join sHrm.vEmployeeCustomSearch ECS on ECS.EmployeeId=HSRM.SourceId
		
		where HSRM.OrgId=@rOrgId and HSRM.AssignSurveyId=@rAssignSurveyId
				and (ECS.Code like '%'+@rEmployeeCode+'%' or isnull(@rEmployeeCode,'')='')
				and (ECS.Name like '%'+@rEmployeeName+'%' or isnull(@rEmployeeName,'')='')
				and (ECS.OrganizationDepartmentId=@rDepartmentId or isnull(@rDepartmentId,0)=0)
END
GO
PRINT N'Altering Procedure [sWellness].[pAddORUpdateProgramCustomField]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddORUpdateProgramCustomField]
(
    @rProgramId INT,
    @rUserId bigint,
    @rProgramCustomFields [sWellness].[udt_ProgramCustomFieldTableType] READONLY,
    @rResult INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    DELETE PCF
    FROM [sWellness].[tProgramCustomField] PCF
    WHERE PCF.ProgramId = @rProgramId
      AND NOT EXISTS (
            SELECT 1
            FROM @rProgramCustomFields S
            WHERE S.Id = PCF.Id
        )
	AND NOT EXISTS (
		SELECT 1 
		FROM 
			[sWellness].[tProgramCustomFieldResponse] PCFR 
		WHERE
			PCFR.ProgramCustomFieldId = PCF.Id
	)

    UPDATE T
    SET		  
        FieldTitle = s.FieldTitle, 
		FieldRemark = s.FieldRemark,
		FieldTypeId = s.FieldTypeId, 
        FieldList = s.FieldList,
        IsMandatory = s.IsMandatory,
        FieldOrderIndex = s.FieldOrderIndex,
		UpdatedUserId = @rUserId,
		UpdatedDateTime = sCommon.fGetDate()
    FROM [sWellness].[tProgramCustomField] T
    INNER JOIN @rProgramCustomFields S
        ON T.Id = S.Id
    WHERE S.Id > 0;

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    INSERT INTO [sWellness].[tProgramCustomField]
    (
         ProgramId
		,FieldTitle
		,FieldRemark
		,FieldTypeId
		,FieldList
		,IsMandatory
		,FieldOrderIndex
		,CreatedUserId
		,CreatedDatetime
    )
    SELECT 
        @rProgramId,
        PCF.FieldTitle,
		PCF.FieldRemark,
		PCF.FieldTypeId,
		PCF.FieldList,
		PCF.IsMandatory,
		PCF.FieldOrderIndex,
		@rUserId,
		sCommon.fGetDate()

    FROM @rProgramCustomFields PCF
    WHERE Id = 0;

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    SET @rResult = @ModifiedRows;
END
GO
PRINT N'Altering Procedure [sWellness].[pAddOrUpdateProgramSubTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramSubTypeMaster]
(				
	@rId INT = 0,
	@rProgramTypeMasterId INT,
	@rTitle NVARCHAR(100),
	@rCode NVARCHAR(100),
	@rIsObsolete BIT,
	@rOrgId SMALLINT,
	@rCreatedUserId BIGINT,
	@rUpdatedUserId BIGINT
)	
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT
		IF(@rId = 0)	
		BEGIN
			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE Code=@rCode AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END
			IF  EXISTS(SELECT Id FROM  [sWellness].[tProgramSubTypeMaster] WHERE Title=@rTitle AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			

			INSERT INTO [sWellness].[tProgramSubTypeMaster] (ProgramTypeMasterId, Title, Code, IsObsolete, OrgId, CreatedUserId,CreatedDateTime)
			Values (@rProgramTypeMasterId, @rTitle,@rCode,@rIsObsolete,@rOrgId,@rCreatedUserId,sCommon.fGetDate())
			SET @lNextNumber = SCOPE_IDENTITY();
			SELECT @lNextNumber AS Result
			RETURN				
		END	 
		ELSE
		BEGIN	 		
			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE Code=@rCode AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END
			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE Title=@rTitle AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			IF(@rIsObsolete = 1)
			BEGIN
				IF EXISTS(SELECT Id FROM [sWellness].[tProgramMaster] WHERE ProgramSubTypeId = @rId AND IsObsolete = 0)
				BEGIN
					SELECT -104 AS Result -- Cannot inactive parent type without making inactive sub type
					RETURN
				END
			END

			UPDATE 
				[sWellness].[tProgramSubTypeMaster]
			SET	
				ProgramTypeMasterId = @rProgramTypeMasterId,
				Title=@rTitle,
				Code=@rCode,			
				IsObsolete=@rIsObsolete,	
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			WHERE 
				Id = @rId

			SELECT @rId AS Result
			RETURN @rId
		 END     
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sWellness].[pAddOrUpdateProgramTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramTypeMaster]
(				
	@rId INT = 0,
	@rTitle NVARCHAR(100),
	@rCode NVARCHAR(100),
	@rIsObsolete BIT,
	@rOrgId SMALLINT,
	@rCreatedUserId BIGINT,
	@rUpdatedUserId BIGINT
)	
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT
		IF(@rId = 0)	
		BEGIN			
			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramTypeMaster] WHERE Code=@rCode AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END
			IF  EXISTS(SELECT Id FROM  [sWellness].[tProgramTypeMaster] WHERE Title=@rTitle AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			INSERT INTO [sWellness].[tProgramTypeMaster] (Title,Code,IsObsolete,OrgId, CreatedUserId,CreatedDateTime)
			Values (@rTitle,@rCode,@rIsObsolete,@rOrgId,@rCreatedUserId,sCommon.fGetDate())
			SET @lNextNumber = SCOPE_IDENTITY();
			SELECT @lNextNumber AS Result
			RETURN				
		END	 
		ELSE
		BEGIN	 
			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramTypeMaster] WHERE Code=@rCode AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END
			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramTypeMaster] WHERE Title=@rTitle AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END			
			IF(@rIsObsolete = 1)
			BEGIN
				IF EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE ProgramTypeMasterId = @rId AND IsObsolete = 0)
				BEGIN
					SELECT -104 AS Result -- Cannot inactive parent type without making inactive sub type
					RETURN
				END
			END

			UPDATE 
				[sWellness].[tProgramTypeMaster]
			SET			
				Title=@rTitle,
				Code=@rCode,			
				IsObsolete=@rIsObsolete,	
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			WHERE 
				Id = @rId

			SELECT @rId AS Result
			RETURN @rId
		 END     
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sWellness].[pAppointmentWellnessSchedulingAdd]...';


GO


CREATE OR ALTER PROCEDURE [sWellness].[pAppointmentWellnessSchedulingAdd]
@rId bigint,      
@rOrgId int      
,@rPatientSourceId bigint      
,@rPatientSourceTypeId smallint      
,@rAppointmentDate datetime      
,@rDoctorEmployeeId bigint      
,@rFromTime time = null      
,@rToTime time = null      
,@rIsRegister bit      
,@rIsObsolete bit      
,@rCreatedUserId bigint      
,@rReferSourceId bigint      
,@rReferSourceTypeId int      
,@rStoreLocationId int      
,@rSetupId int,      
@rCauseId int,      
@rOtherName varchar(200)=null,  
@rFollowupRemark varchar(200)=null,
@rComplaintRemark varchar(200)=null,  
@rAge int = null,      
@rMonth tinyint = null,      
@rGenderId tinyint = null,      
@rTimeslotId int = null,      
@rAppointmentType tinyint = null,      
@rEntryType tinyint = 0,      
@rApprovalStatusId int = null
AS      
BEGIN        
 DECLARE @1SubTypeId int      
 SELECT @1SubTypeId = SubTypeId From sExamination.tSetupMaster where Id = @rSetupId      
 IF EXISTS(Select 1 FROM sWellness.tAppointment Where PatientSourceId = @rPatientSourceId AND PatientSourceTypeId = @rPatientSourceTypeId AND SetupId = @rSetupId) AND @1SubTypeId != 17 AND @rId = 0      
 BEGIN      
  SELECT -101 AS RESULT      
  RETURN      
 END    
    
  IF EXISTS(Select 1 FROM sWellness.tAppointment Where TimeSlotId = @rTimeSlotId AND PatientSourceTypeId = @rPatientSourceTypeId AND ApprovalStatusId = @rApprovalStatusId) AND @rId = 0 AND @rTimeSlotId != 0     
 BEGIN      
  SELECT -102 AS RESULT      
  RETURN      
 END    
 IF @rPatientSourceTypeId != 1009    
 BEGIN    
  Declare @lAge int;    
  select @lAge = Case When @rPatientSourceTypeId = 1001 Then (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeeFamilyDetails where Id = @rPatientSourceId)    
      ELSE (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeePersonalDetail where EmployeeId = @rPatientSourceId) END    
  IF @lAge != @rAge    
  BEGIN    
   SELECT -3 AS Result    
   RETURN    
  END    
 END    
      
 IF NOT EXISTS (Select 1 FROM sWellness.tAppointment Where PatientSourceId = @rPatientSourceId       
 AND PatientSourceTypeId = @rPatientSourceTypeId AND SetupId = @rSetupId  AND @1SubTypeId != 17) AND @rId = 0      
 BEGIN      
 BEGIN TRY      
 BEGIN TRANSACTION      
  DECLARE @lNextNumber BIGINT      
  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sWellness.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output      
      
  DECLARE @loNextNumber nVarchar(20)      
  Set @rApprovalStatusId = Isnull(@rApprovalStatusId,548)    
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1022,      
  @rStoreLocationId = 0, @rNextNumber = @loNextNumber OUTPUT      
     SET @loNextNumber = ISNULL(@loNextNumber, '-300')    IF @loNextNumber = '-300'   BEGIN     SELECT -300 AS Result, '' AS Number, 0 AS Id     RETURN      
  END      
         
  INSERT INTO sWellness.tAppointment       
  (      
   Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,      
   AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,      
   IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,      
   StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,CompliantRemark,Age,Months,GenderId,TimeSlotId,AppointmentType,EntryType,ApprovalStatusId,AppointmentFlag      
  )      
  VALUES      
  (      
   @lNextNumber,@rPatientSourceId,@rPatientSourceTypeId,@rAppointmentDate,      
   @loNextNumber,@rDoctorEmployeeId,@rFromTime,@rToTime,0,@rIsObsolete,@rOrgId,      
   1,@rReferSourceId,@rReferSourceTypeId,@rStoreLocationId,@rSetupId,@rCauseId,@rOtherName,      
   @rFollowupRemark,@rComplaintRemark,@rAge,@rMonth,@rGenderId,@rTimeslotId,@rAppointmentType,@rEntryType,@rApprovalStatusId,'New Appointment'     
  )      
  COMMIT TRANSACTION        
 END TRY      
 BEGIN CATCH       
  ROLLBACK TRANSACTION      
  SELECT -101 AS RESULT      
  RETURN      
 END CATCH      
 END      
 ELSE          
 BEGIN      
  SET @lNextNumber = @rId      
  UPDATE sWellness.tAppointment SET   
  DoctorEmployeeId = @rDoctorEmployeeId,      
  FromTime = @rFromTime,ToTime = @rToTime   
  WHERE Id = @rId       
 END        
 SELECT @lNextNumber AS RESULT          
END
GO
PRINT N'Altering Procedure [sWellness].[pAssignedSurveryForWellnessList]...';


GO
CREATE OR ALTER PROCEDURE  [sWellness].[pAssignedSurveryForWellnessList]
(
	@rOrgId SMALLINT,
	@rSelectedLocation NVARCHAR(MAX)
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT
		ASM.Id AS Value,
		ASM.Title AS Text
	FROM
		[sSupport].[tAssignSurveyMaster] ASM
	INNER JOIN
		[sIp].[tStoreLocationMaster] SLM
	ON
		SLM.Id =  ASM.StoreLocationId
	WHERE 
		SurveyTypeId = 3
	AND
		ISNULL(SLM.LocationId,0) IN (SELECT CAST(item AS INT) FROM  sCommon.fnsplit(ISNULL(@rSelectedLocation,''),','))
	AND
		ASM.IsObsolete = 0
END
GO
PRINT N'Altering Procedure [sWellness].[pGetProgramDocuments]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramDocuments] 
(
    @rProgramId INT,
    @rConfVal INT,
    @rOrgId INT,
    @rReadPermission BIT,
    @rDeletePermission BIT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @res VARCHAR(MAX) = ''
    DECLARE @delmessage VARCHAR(200) = '''Are you sure to delete this item?'''

    -- Table Header
    SET @res = '
    <thead>
        <tr>
            <th scope="col">Document</th>
            <th scope="col">View</th>
            <th scope="col">Download</th>
            <th scope="col">Delete</th>
            <th scope="col">Uploaded By</th>
        </tr>
    </thead>
    <tbody>'

    -- Data Rows
    SELECT 
        @res = @res +
        '<tr>
            <td>' + ISNULL(PD.FileName,'') + '</td>

            <td>' +
                CASE 
                    WHEN @rReadPermission = 1 AND @rConfVal = 1 THEN 
                        '<a target="_blank" href="../../../../Content/' 
                        + CAST(@rOrgId AS VARCHAR) + 
                        '/WellnessProgramDocuments/' + PD.FileName + 
                        '"><i class="fa fa-eye"></i></a>'

                    WHEN @rReadPermission = 1 AND @rConfVal = 2 THEN 
                        '<a attrTitle="' + PD.FileName + 
                        '" onclick="Viewthis(this);" style="cursor:pointer;">
                        <i class="fa fa-eye"></i></a>'

                    WHEN @rReadPermission = 1 AND @rConfVal = 3 THEN 
                        '<a attrOrgId="' + CAST(@rOrgId AS VARCHAR) + 
                        '" attrName="' + PD.FileName + 
                        '" onclick="ViewAzure(this);" style="cursor:pointer;">
                        <i class="fa fa-eye"></i></a>'
                    ELSE ''
                END
            + '</td>

            <td>' +
                CASE 
                    WHEN @rReadPermission = 1 AND @rConfVal = 3 THEN 
                        '<a attrOrgId="' + CAST(@rOrgId AS VARCHAR) + 
                        '" attrName="' + PD.FileName + 
                        '" onclick="DownloadAzure(this);" style="cursor:pointer;">
                        <i class="fa fa-download"></i></a>'
                    WHEN @rReadPermission = 1 THEN 
                        '<a onclick="downloadthis(this,' 
                        + CAST(@rOrgId AS VARCHAR) + ',''' 
                        + PD.FileName + 
                        ''');" style="cursor:pointer;">
                        <i class="fa fa-download"></i></a>'
                    ELSE ''
                END
            + '</td>

            <td>' +
                CASE 
                    WHEN @rDeletePermission = 1 THEN 
                        '<a href="javascript:;" onclick="if (!confirm(' 
                        + @delmessage + 
                        ')) { return false; } else { deletethis(' 
                        + CAST(PD.Id AS VARCHAR) + 
                        ',this); }">
                        <i class="fa fa-trash"></i></a>'
                    ELSE ''
                END
            + '</td>

            <td>' + 
                ISNULL(creator.DisplayTitle,'') +
            '</td>
        </tr>'
    FROM 
		[sWellness].[tProgramDocument] PD
    INNER JOIN 
		[sSecurity].[tUser] creator 
    ON 
		creator.Id = PD.CreatedUserId
  --  LEFT JOIN 
		--[sHrm].[tEmployeeMaster] EM
  --  ON 
		--EM.Id = creator.SourceId
    WHERE 
		PD.ProgramId = @rProgramId
    AND 
		PD.ConfigurationTypeId = @rConfVal

    -- If no rows found
    IF @@ROWCOUNT = 0
    BEGIN
        SET @res = @res + 
        '<tr>
            <td colspan="5" style="text-align:center;">
                No document available
            </td>
         </tr>'
    END

    SET @res = @res + '</tbody>'

    SELECT @res AS res
END
GO
PRINT N'Altering Procedure [sWellness].[pIsProgramSubTypeMasterUsed]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pIsProgramSubTypeMasterUsed]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

    BEGIN TRY    
		SELECT 
			COUNT(*)
		FROM 
			[sWellness].[tProgramMaster] 
		WHERE 
			OrgId = @rOrgId
		AND
			ProgramSubTypeId = @rId
    END TRY
    BEGIN CATCH 
        SELECT -101 AS Result;  -- Return -101 in case of an error
    END CATCH
END
GO
PRINT N'Altering Procedure [sWellness].[pListProgram]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pListProgram]
(
    @rOrgId INT
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        Id AS Value,
        Title AS Text
    FROM 
		sWellness.tProgramMaster WITH (NOLOCK)
    WHERE 
		OrgId = @rOrgId
	AND
		IsObsolete = 0
    ORDER BY 
		Title 
END
GO
PRINT N'Altering Procedure [sWellness].[pListProgramSubTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pListProgramSubTypeMaster]
(
	@rType SMALLINT,
	@rCode NVARCHAR(100) = '',
	@rTitle NVARCHAR(100) = '',
	@rProgramTypeMasterId INT = 0,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	-- Normalize NULL values
	SET @rCode  = ISNULL(@rCode, '');
	SET @rTitle = ISNULL(@rTitle, '');
	SET @rProgramTypeMasterId = ISNULL(@rProgramTypeMasterId, 0);

	BEGIN TRY
		SELECT 
			PSTM.Id,
			PSTM.ProgramTypeMasterId,
			PTM.Title AS ProgramTypeMasterTitle,
			PTM.Code AS ProgramTypeMasterCode,
			PSTM.Code,
			PSTM.Title,
			PSTM.IsObsolete			
		FROM
			[sWellness].[tProgramSubTypeMaster] PSTM
		INNER JOIN
			[sWellness].[tProgramTypeMaster] PTM
			ON PTM.Id = PSTM.ProgramTypeMasterId
		WHERE			
			PSTM.OrgId = @rOrgId
		AND
			(@rCode = '' OR PSTM.Code LIKE '%' + @rCode + '%')
		AND
			(@rTitle = '' OR PSTM.Title LIKE '%' + @rTitle + '%')
		AND
			(@rProgramTypeMasterId = 0 OR PSTM.ProgramTypeMasterId = @rProgramTypeMasterId)
		AND
			(@rType <> 1 OR PSTM.IsObsolete = 0)
		ORDER BY
			PSTM.Id DESC
	END TRY
	BEGIN CATCH 
		SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sWellness].[pListProgramTypeMaster]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListProgramTypeMaster]
(
	@rType SMALLINT,
	@rOrgId SMALLINT,
	@rCode NVARCHAR(100) = '',
	@rTitle NVARCHAR(100) = ''
)
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRY
		SELECT 
			PTM.Id,
			PTM.Code,
			PTM.Title,
			PTM.IsObsolete			
		FROM
			[sWellness].[tProgramTypeMaster] PTM
		WHERE		
			PTM.OrgId = @rOrgId

		AND (
			@rCode IS NULL 
			OR @rCode = '' 
			OR PTM.Code LIKE '%' + @rCode + '%'
		)

		AND (
			@rTitle IS NULL 
			OR @rTitle = '' 
			OR PTM.Title LIKE '%' + @rTitle + '%'
		)

		AND (
			@rType <> 1 
			OR PTM.IsObsolete = 0
		)

		ORDER BY PTM.Id DESC
	END TRY
	BEGIN CATCH 
		SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sCommon].[pListLocationByUser]...';


GO
CREATE OR ALTER PROCEDURE [sCommon].[pListLocationByUser]
(
	@rOrgId SMALLINT,
	@rUserId BIGINT
)
AS
BEGIN
	SET NOCOUNT ON; 

	SELECT DISTINCT
		LM.Id AS Value,
		LM.Title AS Text
	FROM 
		sSecurity.tUserLocation UL
	INNER JOIN
		[sIp].[tStoreLocationMaster] SLM
	ON
		SLM.Id = UL.StoreLocationId
	INNER JOIN
		[sCommon].[tLocationMaster] LM
	ON
		LM.Id = SLM.LocationId
	WHERE 
		UserId = @rUserId
	AND
		LM.OrgId = @rOrgId
END
GO
PRINT N'Creating Procedure [sCommon].[pStaticMHICategoryIndicator]...';


GO
CREATE OR ALTER PROCEDURE [sCommon].[pStaticMHICategoryIndicator]
(
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON; 

	SELECT
		SMCI.Id AS Value,
		SMCI.Title AS Text
	FROM 
		[sWellness].[tStaticMHICategoryIndicator] SMCI	
	ORDER BY
		SMCI.Id
END
GO
PRINT N'Creating Procedure [sExamination].[pGetAdditionalFieldConsultation]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetAdditionalFieldConsultation]
@rSourceTypeId int = 3,
@rExaminationTypeId int = 17,
@rSourceId bigint = 0
as
BEGIN
	select 
		Item as Item,
		case when Upper(AdditionalFieldResponse)=Upper(Item) then ' selected' else '' end as AdditionalFieldResponse,
		InS.Id as InSId
		From sExamination.tAdditionalFieldSetup InS
		LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId and Isnull([AdditionalFieldId],0)=0
		Cross apply [sCommon].[fnSplit](FieldList,',')
		where FieldTypeId=2 and ISNULL(InS.SourceTypeId, 0) = @rSourceTypeId and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)

	IF(@rSourceId > 0 AND EXISTS (Select Id FROM [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId))
	BEGIN
		
		SELECT Id as AdditionalFieldId FROM [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId
	END
	ELSE
	BEGIN
		SELECT 0 as AdditionalFieldId
	END

	IF EXISTS (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId)
	BEGIN
		SELECT
			Isnull(convert(varchar,AFF.Id),'''''') as AFFId,
			convert(varchar,InS.Id)  as InSId,
			convert(varchar,Isnull(IsFieldMandatory,'0')) as IsFieldMandatory,
			convert(varchar,Isnull(InS.FieldTypeId,'0')) as InSFieldTypeId,
			Isnull(INS.FieldGroup,'') as FieldGroup,
			Isnull(INS.FieldRemark,'') as FieldRemark,
			convert(varchar,ISNULL([AdditionalFieldResponse],'')) as AdditionalFieldResponse,
			case when InS.FieldTypeId = 2 and @rSourceId <> 0 then [dbo].[fGetDropDownAdditionalFieldSetupNg](@rSourceId,Ins.Id)
				 else '' end as DropDownAdditionalSetup 
			FROM sExamination.tAdditionalFieldSetup InS
			LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId --and (@rSourceId <> 0 OR (@rSourceId = 0 and Isnull([AdditionalFieldId],0)=0))
			Where ISNULL(InS.SourceTypeId, 0) = @rSourceTypeId and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)
			AND ((Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId)) or (Isnull([AdditionalFieldId],0)=0))
			ORDER BY FieldOrder
	END
	ELSE
	BEGIN
			SELECT
			Isnull(convert(varchar,AFF.Id),'''''') as AFFId,
			convert(varchar,InS.Id)  as InSId,
			convert(varchar,Isnull(IsFieldMandatory,'0')) as IsFieldMandatory,
			convert(varchar,Isnull(InS.FieldTypeId,'0')) as InSFieldTypeId,
			Isnull(INS.FieldGroup,'') as FieldGroup,
			Isnull(INS.FieldRemark,'') as FieldRemark,
			convert(varchar,ISNULL([AdditionalFieldResponse],'')) as AdditionalFieldResponse,
			case when InS.FieldTypeId = 2 and @rSourceId <> 0 then [dbo].[fGetDropDownAdditionalFieldSetupNg](@rSourceId,Ins.Id)
				 else '' end as DropDownAdditionalSetup 
			FROM sExamination.tAdditionalFieldSetup InS
			LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId and Isnull([AdditionalFieldId],0)=0
			Where ISNULL(InS.SourceTypeId, 0) = @rSourceTypeId and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)
			ORDER BY FieldOrder
	END
END
GO
PRINT N'Creating Procedure [sHospitalization].[pAssignDoctorScreenDropDown]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pAssignDoctorScreenDropDown]          
 @rOrgId NVARCHAR(50),            
   @rUserId varchar(50),          
 @rIsObsolete bit            
 WITH EXECUTE AS CALLER            
AS            
SET NOCOUNT ON            
            
BEGIN              
select Id,Title as Text from sHrm.tSectorMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title            
select Id, Title as Text , SectorId  from sHrm.tVerticalMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title                     
--select Id, Title as Text ,LocationSubGroupId  from sCommon.tLocationMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title            
     
     
SELECT   
    LMT.Id,   
    LMT.Title AS Text  
  
FROM sCommon.tLocationMaster AS LMT  
INNER JOIN [sIp].[tStoreLocationMaster] LM WITH (NOLOCK)  
    ON LMT.Id = LM.LocationId  
INNER JOIN sSecurity.tUserLocation UL WITH (NOLOCK)  
    ON LM.Id = UL.StoreLocationId  
WHERE    
    LM.OrgId = @rOrgId  
    AND UL.UserId = @rUserId  
ORDER BY   
    LM.Title;      
  
  
select Id, Title as Text from sCommon.tCompanyInformation  where Code=@rOrgId order by Title           
 SELECT Id, Title as Text, LocationId  FROM [sIp].[tStoreLocationMaster] SLM WITH (NOLOCK)          
INNER JOIN sSecurity.tUserLocation UL WITH (NOLOCK)         
ON SLM.Id = UL.StoreLocationId   WHERE IsObsolete = @rIsObsolete  AND OrgId = @rOrgId  AND UL.UserId = @rUserId          
    ORDER BY SLM.Title          
END
GO
PRINT N'Creating Procedure [sHospitalization].[pAssignDoctorScreenDropDownNew]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pAssignDoctorScreenDropDownNew]      
 @rOrgId NVARCHAR(50),        
   @rUserId varchar(50),      
 @rIsObsolete bit        
 WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
        
BEGIN          
select Id,Title as Text from sHrm.tSectorMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title        
select Id, Title as Text , SectorId  from sHrm.tVerticalMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title        
select Id, Title as Text ,VerticalId  from sHrm.tCompanyGroupMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title   --not using      
select Id, Title as Text ,CompanyGroupId  from sHrm.tEmployeeCompanyMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title  --not using      
select Id, Title as Text from sCommon.tLocationMainGroupMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title  --not using      
select Id, Title as Text ,LocationMainGroupId  from sCommon.tLocationSubGroupMaster  where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title        
select Id, Title as Text ,LocationSubGroupId  from sCommon.tLocationMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title        
  SELECT LM.Id, LM.Title AS Text, LM.locationid       FROM  [sIp].[tStoreLocationMaster] LM WITH (NOLOCK)     INNER JOIN sSecurity.tUserLocation UL WITH (NOLOCK)         ON LM.locationid = UL.StoreLocationId     WHERE  LM.OrgId = @rOrgId         AND UL.
UserId = @rUserId         ORDER BY LM.Title    
select Id, Title as Text ,DepartmentGroupId  from sCommon.tOrganizationDepartmentMaster where IsObsolete = @rIsObsolete and OrgId=@rOrgId order by Title--not using       
select Id, Code as Text from sCommon.tCompanyInformation  where Code=@rOrgId order by Title       
 SELECT Id, Title as Text, LocationId  FROM [sIp].[tStoreLocationMaster] SLM WITH (NOLOCK)      
INNER JOIN sSecurity.tUserLocation UL WITH (NOLOCK)     
ON SLM.Id = UL.StoreLocationId   WHERE IsObsolete = @rIsObsolete  AND OrgId = @rOrgId  AND UL.UserId = @rUserId      
    ORDER BY SLM.Title      
END
GO
PRINT N'Creating Procedure [sHospitalization].[pGetDoctorsWithZeroCountAndOpenTickets]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pGetDoctorsWithZeroCountAndOpenTickets]      
    @OrgId INT,      
    @HoursThreshold INT = 48,      
    @DaysLookback INT = 30      
AS      
BEGIN      
    SET NOCOUNT ON;      
          
    SELECT DISTINCT      
        id.Id AS RecordId,      
       -- iad.DoctorEmployeeId AS ParticipantSourceId ,    
     U.id AS ParticipantSourceId ,    
  id.orgid as orgId    
      
    FROM sHospitalization.tIntimationDetails id      
      
   -- INNER JOIN sHospitalization.tIntimationAssignedDoctor iad       
    --    ON id.AssignedDoctorId = iad.DoctorEmployeeId      
      
    INNER JOIN sHrm.tEmployeeMaster emp       
        ON id.AssignedDoctorId = emp.Id      
        AND emp.OrgId = @OrgId      
   INNER JOIN sSecurity.tUser U ON U.SourceId=id.AssignedDoctorId     
    LEFT JOIN sHrm.tEmployeeCommunications EC       
        ON emp.Id = EC.EmployeeId      
      
    WHERE       
        id.OrgId = @OrgId      
  And emp.OrgID =  @OrgId      
        AND id.IsObsolete = 0      
        AND id.TicketStatus IN ('Open')      
        AND id.CreatedDateTime <= DATEADD(HOUR, -@HoursThreshold, GETDATE());      
      
END
GO
PRINT N'Creating Procedure [sHospitalization].[pGetNextCentralDoctor]...';


GO
CREATE OR ALTER PROCEDURE sHospitalization.pGetNextCentralDoctor
    @OrgId INT,
    @NextDoctorId BIGINT OUTPUT,
    @NextDoctorIndexId INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @LastUsedDoctorId BIGINT;
    DECLARE @LastUsedIndex INT;
    DECLARE @DoctorCount INT;
    DECLARE @TargetRowNum INT;
    
    -- Get count of active central doctors
    SELECT @DoctorCount = COUNT(*)
    FROM sHospitalization.tClaimIntimationAssignedDoctor
    WHERE OrgId = @OrgId 
        AND AssignDesignationName = 'Central Doctor'
        AND IsObsolete = 0;
    
    IF @DoctorCount = 0
    BEGIN
        RAISERROR('No central doctors configured for organization', 16, 1);
        RETURN;
    END
    
    -- Get the last used central doctor from recent intimations
    SELECT TOP 1 @LastUsedDoctorId = ad.DoctorEmployeeId
    FROM sHospitalization.tIntimationDetails d
    INNER JOIN sHospitalization.tClaimIntimationAssignedDoctor ad 
        ON d.IntimationAssignedDoctorId = ad.Id
    WHERE ad.OrgId = @OrgId 
        AND ad.AssignDesignationName = 'Central Doctor'
        AND ad.IsObsolete = 0
    ORDER BY d.CreatedDateTime DESC;
    
    -- Find the index of the last used doctor
    IF @LastUsedDoctorId IS NOT NULL
    BEGIN
        ;WITH OrderedDoctors AS (
            SELECT 
                DoctorEmployeeId,
                Id,
                ROW_NUMBER() OVER (ORDER BY AssignDoctorIndex) - 1 as RowNum
            FROM sHospitalization.tClaimIntimationAssignedDoctor
            WHERE OrgId = @OrgId 
                AND AssignDesignationName = 'Central Doctor'
                AND IsObsolete = 0
        )
        SELECT @LastUsedIndex = RowNum
        FROM OrderedDoctors
        WHERE DoctorEmployeeId = @LastUsedDoctorId;
        
        -- Next index is last used + 1 (wrap around)
        SET @TargetRowNum = (@LastUsedIndex + 1) % @DoctorCount;
    END
    ELSE
    BEGIN
        -- No previous assignments, start from 0
        SET @TargetRowNum = 0;
    END
    
    -- Get the next doctor
    ;WITH OrderedDoctors AS (
        SELECT 
            DoctorEmployeeId,
            Id,
            ROW_NUMBER() OVER (ORDER BY AssignDoctorIndex) - 1 as RowNum
        FROM sHospitalization.tClaimIntimationAssignedDoctor
        WHERE OrgId = @OrgId 
            AND AssignDesignationName = 'Central Doctor'
            AND IsObsolete = 0
    )
    SELECT 
        @NextDoctorId = DoctorEmployeeId,
        @NextDoctorIndexId = Id
    FROM OrderedDoctors
    WHERE RowNum = @TargetRowNum;
    
    -- Log the assignment (optional)
    INSERT INTO sHospitalization.tDoctorAssignmentLog (OrgId, AssignedDoctorId, AssignedDateTime)
    VALUES (@OrgId, @NextDoctorId, GETUTCDATE());
END
GO
PRINT N'Creating Procedure [sHospitalization].[pHospitalizationAssignDoctorListGetNew]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pHospitalizationAssignDoctorListGetNew]              
  @rOrgId BIGINT,                        
  @rId BIGINT = 0,              
  @rBusinessId BIGINT = 0,              
  @rSubBusinessId BIGINT = 0,              
  @rLocationId BIGINT = 0,              
  @rSubLocationId BIGINT = 0,          
  @rStateId BIGINT = 0 ,        
   @rOrganizationId BIGINT = 0 ,    
   @rDesignationId BIGINT = 0,
  @rEmployeeId BIGINT = 0            
               
AS            
BEGIN            
    SET NOCOUNT ON;            
            
    SELECT              
        LI.Id,            
        LI.BusinessId,          
        --SM.Title as BusinessName,        
  CASE     
        WHEN LI.BusinessId = 0 AND SM.Title IS NULL THEN '-ALL-'    
        ELSE SM.Title    
        END AS BusinessName,    
        LI.SubBusinessId,          
       -- VM.Title as SubBusinessName,        
     CASE     
        WHEN LI.SubBusinessId = 0 AND VM.Title IS NULL THEN '-ALL-'    
        ELSE VM.Title    
        END AS SubBusinessName,    
        LI.LocationId,          
        --loc.Title as LocationName,       
    CASE     
        WHEN LI.LocationId = 0 AND loc.Title IS NULL THEN '-ALL-'    
        ELSE loc.Title    
        END AS LocationName,    
        LI.SubLocationId,            
       -- SLM.Title as SubLocationName,        
       CASE     
        WHEN LI.SubLocationId = 0 AND SLM.Title IS NULL THEN '-ALL-'    
        ELSE SLM.Title    
        END AS SubLocationName,    
        LI.DoctorEmployeeId,             
        LI.OrganizationId,            
      --  CI.code as OrganizationName,        
     CASE     
        WHEN LI.OrganizationId = 0 AND CI.Title IS NULL THEN '-ALL-'    
        ELSE CI.Title    
        END AS OrganizationName,    
        LI.StateId,          
       -- SM2.Title as StateName,        
     CASE     
        WHEN LI.StateId = 0 AND SM2.Title IS NULL THEN '-ALL-'    
        ELSE SM2.Title    
        END AS StateName,    
        LI.IsObsolete,            
        LI.CreatedUserId,            
        LI.CreatedDateTime,            
        LI.UpdatedUserId,            
        LI.UpdatedDateTime,            
        LI.OrgId,            
        EM.Code AS EmployeeCode,            
        ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName  ,          
  CASE           
    WHEN LI.IsObsolete = 0 THEN 'Active'          
    WHEN LI.IsObsolete = 1 THEN 'Inactive'          
     END AS IsActive          ,  
  LI.AssignDesignationName as DesignationName,  
  LI.AssignDesignationId as DesignationId  
  
    FROM [sHospitalization].[tClaimIntimationAssignedDoctor] LI            
    INNER JOIN sHrm.tEmployeeMaster EM           
        ON EM.Id = LI.DoctorEmployeeId            
                  
            
    LEFT JOIN sCommon.tCompanyInformation CI ON CI.Id = LI.OrganizationId            
    LEFT JOIN sHrm.tSectorMaster SM ON SM.Id = LI.BusinessId            
    LEFT JOIN sHrm.tVerticalMaster VM ON VM.Id = LI.SubBusinessId         
    LEFT JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = LI.SubLocationId           
    LEFT JOIN sCommon.tStateMaster SM2 ON SM2.Id = LI.StateId         
    LEFT JOIN  sCommon.tLocationMaster loc on  loc.id=Li.LocationId        
         
            
    WHERE           
        (@rBusinessId = 0 OR LI.BusinessId = @rBusinessId)            
        AND (@rSubBusinessId = 0 OR LI.SubBusinessId= @rSubBusinessId)            
        AND (@rEmployeeId = 0 OR LI.DoctorEmployeeId = @rEmployeeId)            
        AND (@rLocationId = 0 OR LI.LocationId = @rLocationId)            
  AND (@rSubLocationId = 0 OR LI.SubLocationId = @rSubLocationId)        
        AND (@rStateId = 0 OR LI.StateId = @rStateId)        
  AND (@rOrganizationId = 0 OR LI.OrganizationId = @rOrganizationId)   
    AND (@rDesignationId = 0 OR LI.AssignDesignationId = @rDesignationId)   
        AND (@rOrgId = 0 OR LI.OrgId = @rOrgId)          
        AND (@rId = 0 OR LI.Id = @rId);           
END;
GO
PRINT N'Creating Procedure [sHospitalization].[pIntimationDetailsGetListNew]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsGetListNew]                
(                
    @rFromDate NVARCHAR(50) = NULL,                
    @rToDate   NVARCHAR(50) = NULL,                
    @rOrgId    INT                
)                
AS                
BEGIN                
    SET NOCOUNT ON;                
                
    DECLARE @FromDate DATETIME = NULL,                
            @ToDate   DATETIME = NULL,    
            @UseNewTable BIT = 0;                
        
    ---------------------------------------------------                
    -- Check configuration to determine which table to use    
    ---------------------------------------------------                
    SELECT @UseNewTable = CASE     
        WHEN EXISTS (      
            SELECT 1      
            FROM [sConfig].[tConfigurationMaster]      
            WHERE ItemKey = 'ClaimIntimation.HospitalizationAssignDoctorMaster'      
            AND ItemValue = 'True'      
            AND IsObsolete = 0      
        )      
        THEN 1 ELSE 0      
    END;    
        
    ---------------------------------------------------                
    -- Convert only if valid AND not blank                
    ---------------------------------------------------                
    IF (ISDATE(@rFromDate) = 1 AND LTRIM(RTRIM(@rFromDate)) <> '')                
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);                
                
    IF (ISDATE(@rToDate) = 1 AND LTRIM(RTRIM(@rToDate)) <> '')                
        SET @ToDate = CONVERT(DATETIME, @rToDate, 103);                
                
    ---------------------------------------------------                
    IF (@FromDate IS NULL)                
    BEGIN                
        SET @FromDate = '1900-01-01';  -- earliest                
        SET @ToDate = '2099-12-31';    -- latest                
    END                
    ELSE                
    BEGIN                
        -- If FromDate is valid but ToDate is blank, use today                
        IF (@ToDate IS NULL)                
            SET @ToDate = GETDATE();                
    END                
                
    ---------------------------------------------------                
    -- MAIN QUERY                
    ---------------------------------------------------                
        
  
    BEGIN    
        SELECT                
            TD.Id,                
            TD.OrgId,                
            TD.EmpCode as EmployeeCode,                
            TD.BeneficiaryName,                
            TD.DateOfIntimation,                
            CONVERT(VARCHAR(10), TD.DateOfIntimation, 103) AS DateOfIntimation1,                
            TD.DateOfAdmission,                
            TD.DateOfDischarge,                
            TD.HospitalName,                
            TD.State,                
            TD.TicketStatus as Status,                
            TD.NetworkCity,                
            TD.TypeOfIntimation,                
            TD.StatusOfIntimation,                
            TD.ClaimType,                
            TD.IntimationNumber,                
            TD.Relation,                
            TD.Age,                
            TD.ProposerName,                
            TD.Mobile1,                
            TD.EstimatedAmount,                
            TD.AdmissionType,                
            TD.NetworkStatus,                
            TD.NatureOfIllness,                
            TD.TAT,                
            TD.TAT_Godi,                
            TD.TAT_Band_Godi,                
            TD.Remarks,                
            TD.CreatedDateTime,                         
            CONVERT(VARCHAR(10), TD.CreatedDateTime, 103) AS CreatedDate,                
            TD.AssignedDoctorId,                
            EM.Code AS DoctorCode,                
            TD.IsObsolete,                
            TD.TicketNumber,       
            -- Direct from new table - if NULL, show 'Not Assigned'    
           AD.AssignDesignationName AS Designation,    
         ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignDoctor                
        FROM [sHospitalization].[tIntimationDetails] TD                
        Left JOIN [sHospitalization].[tClaimIntimationAssignedDoctor] AD                 
            ON TD.AssignedDoctorId = AD.DoctorEmployeeId    
   AND AD.ID=TD.IntimationAssignedDoctorId     
           AND AD.IsObsolete = 0                
        Left JOIN [sHrm].[tEmployeeMaster] EM                
            ON EM.Id = TD.AssignedDoctorId    
            AND EM.IsObsolete = 0                
        WHERE                         
             TD.DateOfIntimation BETWEEN @FromDate AND @ToDate                
            AND (@rOrgId = 0 OR TD.OrgId = @rOrgId)                
        ORDER BY TD.DateOfIntimation DESC;    
    END    
     
END
GO
PRINT N'Creating Procedure [sHospitalization].[ptIntimationAssignedDoctorAddNew]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[ptIntimationAssignedDoctorAddNew]      
    @rId                BIGINT,        
    @rOrgId             INT,        
    @rBusinessId        BIGINT,        
    @rSubBusinessId     BIGINT,        
    @rLocationId        BIGINT,        
    @rSubLocationId     BIGINT,        
    @rStateId           BIGINT,    
    @rOrganizationId    BIGINT,    
    @rDoctorEmployeeId  BIGINT, 
	@rDesignationId      BIGINT, 
    @rIsObsolete        BIT,        
    @rCreatedUserId     BIGINT,        
    @rUpdatedUserId     BIGINT         
AS        
BEGIN        
    SET NOCOUNT ON;        
        
    BEGIN TRY        
        

               DECLARE @lAssignDesignationId BIGINT;
               DECLARE @lDesignationName VARCHAR(100);
               
               SET @lAssignDesignationId = @rDesignationId;
			   SET @lDesignationName =
                  CASE @rDesignationId
                      WHEN 1 THEN 'Business Doctor'
                      WHEN 2 THEN 'Central Doctor'
                      WHEN 3 THEN 'Site Doctor'
                      WHEN 4 THEN 'Zonal Doctor'
                      ELSE ''
                  END;
       
        -----------------------------------------------------------
        ---- Determine AssignDesignationId based on hierarchy
        -----------------------------------------------------------
        ---- State-Zonal Doctor (Only StateId has value, others are 0)
        --IF @rStateId != 0 AND @rOrganizationId = 0 AND @rBusinessId = 0 AND @rSubBusinessId = 0 
        --   AND @rLocationId = 0 AND @rSubLocationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '1';
        --    SET @lDesignationName = 'Zonal Doctor';
        --END
        

        --ELSE IF @rOrganizationId != 0 AND @rStateId = 0 AND @rBusinessId = 0 AND @rSubBusinessId = 0 
        --        AND @rLocationId = 0 AND @rSubLocationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '2'; 
        --    SET @lDesignationName = 'Central Doctor';
        --END
        
        --ELSE IF @rBusinessId != 0 AND @rSubBusinessId = 0 AND @rLocationId = 0 
        --        AND @rSubLocationId = 0 AND @rStateId = 0 AND @rOrganizationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '3'; 
        --    SET @lDesignationName = 'Business Doctor';
        --END
        
        --ELSE IF @rBusinessId != 0 AND @rSubBusinessId != 0 AND @rLocationId = 0 
        --        AND @rSubLocationId = 0 AND @rStateId = 0 AND @rOrganizationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '3'; 
        --    SET @lDesignationName = 'Business Doctor';
        --END
        
        --ELSE IF @rBusinessId != 0 AND @rLocationId != 0 AND @rSubLocationId = 0 
        --        AND @rStateId = 0 AND @rOrganizationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '4';
        --    SET @lDesignationName = 'Site Doctor';
        --END
        
        --ELSE IF @rBusinessId != 0 AND @rLocationId != 0 AND @rSubLocationId != 0 
        --        AND @rStateId = 0 AND @rOrganizationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '4'; 
        --    SET @lDesignationName = 'Site Doctor';
        --END
        
        --ELSE IF @rBusinessId != 0 AND @rSubBusinessId != 0 AND @rLocationId != 0 
        --        AND @rSubLocationId != 0 AND @rStateId = 0 AND @rOrganizationId = 0
        --BEGIN
        --    SET @lAssignDesignationId = '4'; 
        --    SET @lDesignationName = 'Site Doctor';
        --END
        
        --ELSE
        --BEGIN
        --    SET @lAssignDesignationId = '2';
        --    SET @lDesignationName = 'Central';
        --END
    
        ---------------------------------------------------------    
        -- INSERT    
        ---------------------------------------------------------    
        IF @rId = 0        
        BEGIN        
    
            -- Duplicate check    
            IF EXISTS (        
                SELECT 1        
                FROM sHospitalization.tClaimIntimationAssignedDoctor        
                WHERE OrgId = @rOrgId        
                  AND BusinessId = @rBusinessId    
                  AND SubBusinessId = @rSubBusinessId    
                  AND LocationId = @rLocationId    
                  AND SubLocationId = @rSubLocationId    
                  AND StateId = @rStateId    
                  AND OrganizationId = @rOrganizationId    
                  AND DoctorEmployeeId = @rDoctorEmployeeId    
                  AND IsObsolete = 0    
            )        
            BEGIN        
                SELECT 11 AS RESULT;  -- duplicate exists        
                RETURN;        
            END        
    
            DECLARE @lNextNumber BIGINT;    
            DECLARE @lAssignDoctorIndex INT;    
    
            -- Get Next Primary Id    
            EXEC sCommon.pTableRowIdGet         
                @rOrgId,        
                'sHospitalization.tClaimIntimationAssignedDoctor',        
                0, 1, 1,        
                @outNextNumber = @lNextNumber OUTPUT;        
    
    
            ---------------------------------------------------------    
            -- Auto AssignDoctorIndex logic    
            -- Increment based on same Business/Location group    
            ---------------------------------------------------------    
            SELECT @lAssignDoctorIndex = ISNULL(MAX(AssignDoctorIndex),0) + 1    
            FROM sHospitalization.tClaimIntimationAssignedDoctor    
            WHERE OrgId = @rOrgId    
              AND BusinessId = @rBusinessId    
              AND SubBusinessId = @rSubBusinessId    
              AND LocationId = @rLocationId    
              AND SubLocationId = @rSubLocationId    
              AND StateId = @rStateId    
              AND OrganizationId = @rOrganizationId    
              AND IsObsolete = 0;    
    
    
            INSERT INTO sHospitalization.tClaimIntimationAssignedDoctor        
            (        
                Id,    
                OrgId,    
                BusinessId,    
                SubBusinessId,    
                LocationId,    
                SubLocationId,    
                StateId,    
                OrganizationId,    
                DoctorEmployeeId,    
                AssignDesignationId,    
                AssignDesignationName,
                AssignDoctorIndex,    
                IsObsolete,    
                CreatedUserId,    
                CreatedDateTime    
            )        
            VALUES        
            (        
                @lNextNumber,    
                @rOrgId,    
                @rBusinessId,    
                @rSubBusinessId,    
                @rLocationId,    
                @rSubLocationId,    
                @rStateId,    
                @rOrganizationId,    
                @rDoctorEmployeeId,    
                @rDesignationId, 
                @lDesignationName,     
                @lAssignDoctorIndex,    
                @rIsObsolete,    
                @rCreatedUserId,    
                sCommon.fGetDate()    
            );        
        
            -- Return the new ID and designation info
            SELECT @lNextNumber AS RESULT, 
                   @rDesignationId AS AssignDesignationId,
                   @lDesignationName AS AssignDesignationName; 
        END        
    
        ---------------------------------------------------------    
        -- UPDATE    
        ---------------------------------------------------------    
        ELSE        
        BEGIN        
    
            UPDATE sHospitalization.tClaimIntimationAssignedDoctor        
            SET        
                BusinessId              = @rBusinessId,    
                SubBusinessId           = @rSubBusinessId,    
                LocationId              = @rLocationId,    
                SubLocationId           = @rSubLocationId,    
                StateId                 = @rStateId,    
                OrganizationId          = @rOrganizationId,    
                DoctorEmployeeId        = @rDoctorEmployeeId,    
                AssignDesignationId     = @rDesignationId,
                AssignDesignationName   = @lDesignationName,
                IsObsolete              = @rIsObsolete,    
                UpdatedUserId           = @rUpdatedUserId,    
                UpdatedDateTime         = sCommon.fGetDate()    
            WHERE Id = @rId;        
        
            SELECT @rId AS RESULT, 
                   @rDesignationId AS AssignDesignationId,
                   @lDesignationName AS AssignDesignationName; 
        END        
    
    END TRY        
    BEGIN CATCH        
         SELECT         
            -1 AS RESULT,        
            ERROR_NUMBER() AS ErrorNumber,        
            ERROR_SEVERITY() AS ErrorSeverity,        
            ERROR_STATE() AS ErrorState,        
            ERROR_LINE() AS ErrorLine,        
            ERROR_MESSAGE() AS ErrorMessage;        
    END CATCH        
END;

GO
PRINT N'Creating Procedure [sSupport].[pHealthSaveUpdateSurveyProgramMapping]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pHealthSaveUpdateSurveyProgramMapping]
    @rOrgId SMALLINT,
    @rStrSetupIndicator VARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY

        DECLARE @indicatorXML XML;

        -- Direct cast (remove replace function unless absolutely needed)
        SET @indicatorXML = CAST(@rStrSetupIndicator AS XML);

        DECLARE @tblSetupIndicator TABLE
        (
            t_id INT,
            t_healthSurveyId INT,
            t_programId INT
        );

        INSERT INTO @tblSetupIndicator (t_id, t_healthSurveyId, t_programId)
        SELECT 
            T.c.value('@Id','INT'),
            T.c.value('@HealthSurveyId','INT'),
            T.c.value('@ProgramId','INT')
        FROM @indicatorXML.nodes('/IndicatorRanges/IndicatorRange') T(c);


        MERGE sSupport.tHealthSetupIndicator AS Target
        USING @tblSetupIndicator AS Source
        ON Target.Id = Source.t_id 
           AND Target.HealthSurveyId = Source.t_healthSurveyId

        WHEN MATCHED THEN
            UPDATE SET 
                Target.ProgramId = Source.t_programId

        WHEN NOT MATCHED BY TARGET THEN
            INSERT (HealthSurveyId, ProgramId)
            VALUES (Source.t_healthSurveyId, Source.t_programId);

        SELECT 1 AS StatusCode;

    END TRY
    BEGIN CATCH
        SELECT 
            ERROR_MESSAGE() AS ErrorMessage,
            -101 AS StatusCode;
    END CATCH
END

GO
PRINT N'Creating Procedure [sSupport].[pProgramMappingListGet]...';


GO
CREATE OR ALTER PROCEDURE [sSupport].[pProgramMappingListGet]
    @rOrgId SMALLINT,
    @rHealthSurveyId INT,
	@rLocationId BIGINT = 0
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @lIndicatorRange VARCHAR(MAX) = '';
    DECLARE @ProgramOptions NVARCHAR(MAX) = '';

    IF EXISTS (
        SELECT 1
        FROM sWellness.tProgramMaster P
		INNER JOIN
			[sWellness].[tProgramLocation] PL
		ON	
			P.Id = PL.ProgramId
			WHERE P.IsObsolete = 0 AND P.CategoryId = 1
		AND 
			(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
    )
    BEGIN
        SELECT @ProgramOptions =
        (
            SELECT 
                '<option value="' + CONVERT(VARCHAR, Id) + '">' 
                + Title + 
                '</option>'
            FROM sWellness.tProgramMaster P
		INNER JOIN
			[sWellness].[tProgramLocation] PL
		ON	
			P.Id = PL.ProgramId		
			WHERE P.IsObsolete = 0 AND P.CategoryId = 1
		AND 
			(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)');
    END
    
	;WITH IndicatorData AS
    (
        SELECT *
        FROM sSupport.tHealthSetupIndicator
        WHERE 
            IsObsolete = 0
            AND (
                    (OrgId = @rOrgId AND HealthSurveyId = @rHealthSurveyId)
                 OR (
                        NOT EXISTS (
                            SELECT 1 
                            FROM sSupport.tHealthSetupIndicator 
                            WHERE OrgId = @rOrgId 
                              AND HealthSurveyId = @rHealthSurveyId
                        )
                        AND OrgId = 1 
                        AND HealthSurveyId = 0
                    )
                )
    )

    SELECT 
        @lIndicatorRange = @lIndicatorRange +
        '<tr attrId="' + CONVERT(VARCHAR, Id) + 
        '" attrHealthSurveyId="' + ISNULL(CONVERT(VARCHAR, HealthSurveyId),'0') +
        '" attrCode="' + ISNULL(Code,'') + 
        '" attrTitle="' + ISNULL(Title,'') + '">' +

        '<td>' + 
            ISNULL(NULLIF(LTRIM(RTRIM(HealthIndicatorLabel)), ''), Title) + 
        '</td>' +

        '<td>' + CONVERT(VARCHAR, ISNULL(RangeFrom, 0)) + '</td>' +
        '<td>' + CONVERT(VARCHAR, ISNULL(RangeTo, 0)) + '</td>' +

        '<td>
            <select class="form-control programDropdown">
                <option value="0"' +
                    CASE WHEN ISNULL(ProgramId,0) = 0 THEN ' selected' ELSE '' END +
                '>Select</option>' +

                ISNULL(
                    REPLACE(@ProgramOptions,
                        '<option value="' + CONVERT(VARCHAR, ISNULL(ProgramId,0)) + '">',
                        '<option value="' + CONVERT(VARCHAR, ISNULL(ProgramId,0)) + '" selected>'
                    ),
                '') +

            '</select>
        </td>' +

        '</tr>'
    FROM IndicatorData;

    SELECT @lIndicatorRange AS IndicatorRange;

END

GO
PRINT N'Creating Procedure [sWellness].[GetEmployeeIdFromConsultationCode]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[GetEmployeeIdFromConsultationCode]
@code varchar(300),
@orgId int,
@ParticipantSourceTypeId int,
@StoreLocationId int
as
begin
	declare @empid bigint,@LocationId int
	select @LocationId = LocationId from sIp.tStoreLocationMaster where Id = @StoreLocationId 
	if (@ParticipantSourceTypeId = 95)
		select @empid = Id from sHrm.tEmployeeMaster where Code = @code and OrgId = @orgId 
	select @empid = isnull(@empid,0)
	if @empid = 0
	begin
		select Top 1 @empid = Id from sHrm.tCsrBenefiterMaster where Code = @code and OrgId = @orgId and LocationId = @LocationId
	end
	select @empid = isnull(@empid,0)
	select @empid as Id
end
GO
PRINT N'Creating Procedure [sWellness].[GetEmployeeMHIScoreDetail]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[GetEmployeeMHIScoreDetail]
(
    @rEmpId BIGINT,
    @rOrgId INT = 0
)
AS
BEGIN

    DECLARE 
        @lBloodPressureSystolic INT,
        @lBloodPressureDiastolic INT,
        @lBMI DECIMAL(8,2),
        @lHBA1C NVARCHAR(10),
        @lLDL DECIMAL(8,2),
        @lLatestVitalDisplayConfigVal VARCHAR(5) = 'False'

    -- Get Config Value (same logic as original SP)
    IF (@rOrgId > 0)
    BEGIN
        SELECT @lLatestVitalDisplayConfigVal = 
        sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0)
    END

    ---------------------------------------------------
    -- Get Latest BMI
    ---------------------------------------------------
    SELECT TOP 1 
        @lBMI = V.BMI
    FROM sExamination.tExamination E
    INNER JOIN sExamination.tVital V ON V.SourceId = E.Id
    INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId
    INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId
    WHERE E.ParticipantSourceId = @rEmpId
        AND E.ParticipantSourceTypeId = 95
        AND ISNULL(V.BMI,0) > 0
        AND ((@lLatestVitalDisplayConfigVal = 'True') 
             OR (@lLatestVitalDisplayConfigVal = 'False' AND STM.MainTypeId != 8))
    ORDER BY E.ExaminationDate DESC


    ---------------------------------------------------
    -- Get Latest Blood Pressure
    ---------------------------------------------------
    SELECT TOP 1 
        @lBloodPressureSystolic = V.BloodPressureSystolic,
        @lBloodPressureDiastolic = V.BloodPressureDiastolic
    FROM sExamination.tExamination E
    INNER JOIN sExamination.tVital V ON V.SourceId = E.Id
    INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId
    INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId
    WHERE E.ParticipantSourceId = @rEmpId
        AND E.ParticipantSourceTypeId = 95
        AND ISNULL(V.BloodPressureSystolic,0) > 0
        AND ISNULL(V.BloodPressureDiastolic,0) > 0
        AND ((@lLatestVitalDisplayConfigVal = 'True') 
             OR (@lLatestVitalDisplayConfigVal = 'False' AND STM.MainTypeId != 8))
    ORDER BY E.ExaminationDate DESC


    ---------------------------------------------------
    -- Get Latest HBA1C
    ---------------------------------------------------
    SELECT TOP 1 
        @lHBA1C = TRD.ServiceValue
    FROM sExamination.tTestRequestDetail TRD
    INNER JOIN sExamination.tTestRequest TR ON TRD.TestRequestId = TR.Id
    INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id
    INNER JOIN sOrderEntry.tTestParameterMaster TP ON TD.TestParameterId = TP.Id
    INNER JOIN sExamination.tExamination E ON TR.SourceId = E.Id
    WHERE E.ParticipantSourceId = @rEmpId
        AND E.ParticipantSourceTypeId = 95
        AND TP.StaticTestParameterId = 25
        AND ISNULL(TRD.ServiceValue,'') <> ''
    ORDER BY E.ExaminationDate DESC


    ---------------------------------------------------
    -- Get Latest LDL
    ---------------------------------------------------
    SELECT TOP 1 
		@lLDL = CONVERT(DECIMAL(8,2), TRD.ServiceValue)
	FROM sExamination.tTestRequestDetail TRD
	INNER JOIN sExamination.tTestRequest TR ON TRD.TestRequestId = TR.Id
	INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id
	INNER JOIN sOrderEntry.tTestParameterMaster TP ON TD.TestParameterId = TP.Id
	INNER JOIN sExamination.tExamination E ON TR.SourceId = E.Id
	WHERE E.ParticipantSourceId = @rEmpId
		AND E.ParticipantSourceTypeId = 95
		AND TP.StaticTestParameterId = 34
		AND ISNULL(TRD.ServiceValue,'') <> ''
	ORDER BY E.ExaminationDate DESC


    ---------------------------------------------------
    -- Final Output
    ---------------------------------------------------
    SELECT
        @lBloodPressureSystolic AS BloodPressureSystolic,
        @lBloodPressureDiastolic AS BloodPressureDiastolic,
        @lBMI AS BMI,
        @lHBA1C AS HBA1C,
        @lLDL AS LDL

END
GO
PRINT N'Creating Procedure [sWellness].[pActivityCategoryMasterAddUpdate]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityCategoryMasterAddUpdate]
	@rId bigint=0,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rIsObsolete bit,	
	@rOrgId smallint,
	@rCreatedUserId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN TRY

		IF  EXISTS (SELECT 1 FROM [sWellness].[tWellnessActivityCategoryMaster] WHERE  UPPER(Code) = UPPER(@rCode)  and Id<>@rId)
		BEGIN	 
			SELECT -102 AS RESULT
			return
		END
		IF  EXISTS (SELECT 1 FROM [sWellness].[tWellnessActivityCategoryMaster] WHERE UPPER(Title) = UPPER(@rTitle)  and Id<>@rId)
		BEGIN	 
			SELECT -103 AS RESULT
			return
		END
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF(@rId=0)
					BEGIN
					EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sWellness.tWellnessActivityCategoryMaster', 0, 101, 1,@outNextNumber = @lNextNumber output

					INSERT INTO [sWellness].[tWellnessActivityCategoryMaster]
							(
							Id,
							Code,
							Title,
							IsObsolete,
							CreatedUserId,
							CreatedDateTime
							)
							values
							(
							@lNextNumber,
							@rCode,
							@rTitle,
							@rIsObsolete,
							@rCreatedUserId,
							sCommon.fGetDate()
							)

					--SELECT @lNextNumber AS RESULT
	 
					END
			ELse
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sWellness].[tWellnessActivityCategoryMaster] WHERE Id=@rId)
						BEGIN	 
							SELECT -101 AS RESULT
							return
						END
						Update [sWellness].[tWellnessActivityCategoryMaster]
							Set
								Code=@rCode,
								Title =@rTitle,
								IsObsolete=@rIsObsolete,
								UpdatedUserId=@rCreatedUserId,
								UpdatedDateTime=sCommon.fGetDate()
							Where Id=@rId

							SET @lNextNumber=@rId
				END
		COMMIT TRAN
		Select @lNextNumber as Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityCategoryMasterDelete]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityCategoryMasterDelete]
	@rId int
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	if exists (select 1 from [sWellness].[tWellnessActivityCategoryMaster] where Id = @rId )
	begin	
		BEGIN TRANSACTION  
			Delete FROM [sWellness].[tWellnessActivityCategoryMaster] Where Id=@rId 			
			COMMIT TRANSACTION
			Select 1 as Result
	end
	else
	begin
		select -101 as Result
	end
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityCategoryMasterGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityCategoryMasterGet]
	@rId Int
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		
			if exists (select 1 from [sWellness].[tWellnessActivityCategoryMaster]  where Id = @rId)
	begin	

			Select Id,Code,Title,IsObsolete FROM [sWellness].[tWellnessActivityCategoryMaster]   Where Id=@rId	
	end
	else
	begin
		select -101 as Result
	end
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityCategoryMasterGetList]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityCategoryMasterGetList]
	@rCode nvarchar(50),
	@rTitle nvarchar(200)
AS

BEGIN		
			Select Id,Code,Title,
			CASE WHEN IsObsolete = 0 THEN 'Active' 
			ELSE 'InActive'
			end as Status,
			IsObsolete
			FROM [sWellness].[tWellnessActivityCategoryMaster]
			Where 
			(Code like '%'+@rCode+'%' or ISNULL(@rCode,'')='')
			and (Title like '%'+@rTitle+'%' or ISNULL(@rTitle,'')='')
			ORDER BY Id DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityDashboardDetailGet]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pActivityDashboardDetailGet]
(
@rEmployeeId BIGINT 
)
AS

BEGIN
      SELECT 
    WAM.ActivityName,
    WAM.ActivityId
    --CASE 
    --    WHEN SUM(CASE WHEN AA.Status <> 1 THEN 1 ELSE 0 END) = 0
    --        THEN 'Completed'
    --    ELSE 'Pending'
    --END AS Status
FROM sWellness.tAssignedActivity AA
--LEFT JOIN sWellness.tWellnessActivityTaskMaster WTM
--    ON WTM.Id = AA.WellnessActivityTaskId
LEFT JOIN sWellness.tWellnessActivityMaster WAM
    ON WAM.ActivityId = AA.WellnessActivityId
WHERE AA.EmployeeId = @rEmployeeId
GROUP BY 
    WAM.ActivityName,
    WAM.ActivityId
--ORDER BY 
--    CASE 
--        WHEN SUM(CASE WHEN AA.Status <> 1 THEN 1 ELSE 0 END) = 0 THEN 2
--        ELSE 1
--    END,
--    WAM.ActivityName;
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityMasterAddOrUpdate]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityMasterAddOrUpdate]
	@rActivityId int=0,
	@rActivityName nvarchar(100),
	@rActivityCategoryId int,
	@rDefaultUnitId smallint,
	@rDescription nvarchar(500),
	@rIsObsolete bit,	
	@rOrgId smallint,
	@rCreatedUserId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN TRY

		IF  EXISTS (SELECT 1 FROM [sWellness].[tWellnessActivityMaster] WHERE  UPPER(ActivityName) = UPPER(@rActivityName)  and ActivityId <> @rActivityId)
		BEGIN	 
			SELECT -102 AS RESULT
			return
		END
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF(@rActivityId=0)
					BEGIN
					EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sWellness.tWellnessActivityMaster', 0, 101, 1,@outNextNumber = @lNextNumber output

					INSERT INTO [sWellness].[tWellnessActivityMaster]
							(
							ActivityId,
							ActivityName,
							WellnessActivityCategoryId,
							DefaultUnitId,
							Description,
							IsObsolete,
							CreatedUserId,
							CreatedDateTime
							)
							values
							(
							@lNextNumber,
							@rActivityName,
							@rActivityCategoryId,
							@rDefaultUnitId,
							@rDescription,
							@rIsObsolete,
							@rCreatedUserId,
							sCommon.fGetDate()
							)

					--SELECT @lNextNumber AS RESULT
	 
					END
			ELse
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sWellness].[tWellnessActivityMaster] WHERE ActivityId = @rActivityId)
						BEGIN	 
							SELECT -101 AS RESULT
							return
						END
						Update [sWellness].[tWellnessActivityMaster]
							Set
								ActivityName=@rActivityName,
								WellnessActivityCategoryId =@rActivityCategoryId,
								DefaultUnitId = @rDefaultUnitId,
								Description = @rDescription,
								IsObsolete=@rIsObsolete,
								UpdatedUserId=@rCreatedUserId,
								UpdatedDateTime=sCommon.fGetDate()
							Where ActivityId = @rActivityId

							SET @lNextNumber= @rActivityId
				END
		COMMIT TRAN
		Select @lNextNumber as Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityMasterDelete]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityMasterDelete]
	@rActivityId int
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	if exists (select 1 from [sWellness].[tWellnessActivityMaster] where ActivityId = @rActivityId )
	begin	
		BEGIN TRANSACTION  
			Delete FROM [sWellness].[tWellnessActivityMaster] Where ActivityId = @rActivityId 			
			COMMIT TRANSACTION
			Select 1 as Result
	end
	else
	begin
		select -101 as Result
	end
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityMasterGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityMasterGet]
	@rActivityId Int
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		
			if exists (select 1 from [sWellness].[tWellnessActivityMaster]  where ActivityId = @rActivityId)
	begin	

			Select ActivityId,ActivityName,WellnessActivityCategoryId as ActivityCategoryId,DefaultUnitId,IsObsolete,Description FROM [sWellness].[tWellnessActivityMaster]   Where ActivityId = @rActivityId	
	end
	else
	begin
		select -101 as Result
	end
END
GO
PRINT N'Creating Procedure [sWellness].[pActivityMasterGetList]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pActivityMasterGetList]
	@rActivityName nvarchar(100),
	@rActivityCategoryId int
AS

BEGIN		
			Select AM.ActivityId,AM.ActivityName,
			ACM.Title as ActivityCategoryName,AM.Description,
			CASE WHEN AM.IsObsolete = 0 THEN 'Active'
			ELSE 'InActive'
			end as Status,
			AM.IsObsolete,
			CASE WHEN [DefaultUnitId] = 1 THEN 'Steps' 
					WHEN [DefaultUnitId] = 2 THEN 'Min' 
					WHEN [DefaultUnitId] = 3 THEN 'ML'
					WHEN [DefaultUnitId] = 4 THEN 'Times' 
				END AS UnitName,
			DefaultUnitId,
			ACM.Code as ActivityCode
			FROM 
			[sWellness].[tWellnessActivityMaster] AM
			INNER JOIN [sWellness].[tWellnessActivityCategoryMaster] ACM ON AM.WellnessActivityCategoryId = ACM.Id
			Where 
			(ActivityName like '%'+@rActivityName+'%' or ISNULL(@rActivityName,'')='')
			and (WellnessActivityCategoryId = @rActivityCategoryId OR (@rActivityCategoryId = 0 OR @rActivityCategoryId is null))
			ORDER BY AM.ActivityId DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateActivityTaskMaster]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateActivityTaskMaster]
(
@rId INT,
@rActivityId INT,
@rTaskName nvarchar(500),
@rTargetValue INT,
@rFrequencyTypeId SMALLINT,
@rFrequencyCount INT,
@rDurationDays INT,
@rOrgId SMALLINT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Result INT;
DECLARE @lNextNumber BIGINT = 0;
BEGIN TRY

    IF  EXISTS (SELECT 1 FROM [sWellness].[tWellnessActivityTaskMaster] WHERE  UPPER(Name) = UPPER(@rTaskName)  and ActivityId = @rActivityId and Id <> @rId)
		BEGIN	 
			SELECT -102 AS RESULT
			return
	END
	BEGIN TRANSACTION;
		IF(@rId > 0)
			BEGIN	
				UPDATE [sWellness].[tWellnessActivityTaskMaster]
				SET
					[ActivityId] = @rActivityId,
					[TargetValue] = @rTargetValue,
					[FrequencyCount] = @rFrequencyCount,
					[FrequencyTypeId] = @rFrequencyTypeId,
					[DurationDays] = @rDurationDays,
					[Name] = @rTaskName
				WHERE 
					[Id] = @rId;
				SET @Result = @rId
			END
		ELSE
			BEGIN
				EXEC sCommon.pTableRowIdGet 
                @rOrgId,
                'sWellness.tWellnessActivityTaskMaster',
                0,1,1,
                @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tWellnessActivityTaskMaster]
				   ([Id]
				   ,[ActivityId]
				   ,[TargetValue]
				   ,[FrequencyTypeId]
				   ,[FrequencyCount]
				   ,[DurationDays]
				   ,[Name])
				VALUES
				   (@lNextNumber
				   ,@rActivityId
				   ,@rTargetValue
				   ,@rFrequencyTypeId
				   ,@rFrequencyCount
				   ,@rDurationDays
				   ,@rTaskName)

				SET @Result = @lNextNumber;
			END	
	COMMIT TRANSACTION;
	SELECT @Result AS Id;
END TRY
	BEGIN CATCH

	IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        DECLARE 
            @ErrorMessage NVARCHAR(4000),
            @ErrorSeverity INT,
            @ErrorState INT;

        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();

        RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramParameters]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramParameters]
(
    @rOrgId SMALLINT,
    @rProgramId INT,
    @rUserId BIGINT,
    @rProgramParameterList [sWellness].[udt_ProgramParameterTableType] READONLY,
    @rResult INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    DELETE T
    FROM [sWellness].[tProgramParameter] T
    WHERE T.ProgramId = @rProgramId
      AND NOT EXISTS
      (
          SELECT 1
          FROM @rProgramParameterList L
          WHERE L.ParameterSourceId = T.ParameterSourceId
      )
	  AND NOT EXISTS (
		SELECT 1 
		FROM 
			[sWellness].[tProgramParameterTrack] PPT 
		WHERE
			PPT.ProgramParameterId = T.AutoID
	)

    SET @ModifiedRows += @@ROWCOUNT;

    UPDATE T
    SET
        T.ParameterTypeId = S.ParameterTypeId,
        T.ParameterSourceId = S.ParameterSourceId,
        T.OrderIndex = S.OrderIndex,
        T.ParameterSourceTypeId = ST.Id,
        T.UpdatedUserId = @rUserId,
        T.UpdatedDateTime = sCommon.fGetDate()
    FROM [sWellness].[tProgramParameter] T
    INNER JOIN @rProgramParameterList S
        ON T.ProgramId = @rProgramId
       AND T.AutoID = S.AutoID
    INNER JOIN sSystem.tTable ST
        ON ST.tableName =
            CASE S.ParameterTypeId
                WHEN 2 THEN 'sExamination_tGeneralTemplateParameter'
                WHEN 3 THEN 'sOrderEntry.tTestParameterMaster'
            END;

    SET @ModifiedRows += @@ROWCOUNT;

    INSERT INTO [sWellness].[tProgramParameter]
    (
        OrgId,
        ProgramId,
        ParameterTypeId,
        ParameterSourceTypeId,
        ParameterSourceId,
        OrderIndex,
        CreatedUserId,
        CreatedDateTime,
        UpdatedUserId,
        UpdatedDateTime
    )
    SELECT
        @rOrgId,
        @rProgramId,
        L.ParameterTypeId,
        ST.Id,
        L.ParameterSourceId,
        L.OrderIndex,
        @rUserId,
        sCommon.fGetDate(),
        @rUserId,
        sCommon.fGetDate()
    FROM @rProgramParameterList L
    INNER JOIN sSystem.tTable ST
        ON ST.tableName =
            CASE L.ParameterTypeId
                WHEN 2 THEN 'sExamination_tGeneralTemplateParameter'
                WHEN 3 THEN 'sOrderEntry.tTestParameterMaster'
            END
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM [sWellness].[tProgramParameter] T
        WHERE T.ProgramId = @rProgramId
          AND T.ParameterSourceId = L.ParameterSourceId
    );

    SET @ModifiedRows += @@ROWCOUNT;

    SET @rResult = @ModifiedRows;

END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramSessionAttendance]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramSessionAttendance]
(				
	@rId INT,
	@rProgramId INT,
	@rStoreLocationId INT,
	@rAttendedEmployee INT,
	@rAttendedDate DATE,
	@rRemark NVARCHAR(1000),
	@rUserId BIGINT
)	
AS
SET NOCOUNT ON
BEGIN
    DECLARE @lNextNumber BIGINT = 0;
    BEGIN TRY
        BEGIN TRANSACTION

        IF (@rId = 0)
        BEGIN
            INSERT INTO [sWellness].[tProgramSessionAttendance] (StoreLocationId, ProgramId, AttendedEmployee, AttendedDate, Remark, CreatedUserId, CreatedDateTime)
			Values (@rStoreLocationId, @rProgramId, @rAttendedEmployee, @rAttendedDate, @rRemark, @rUserId, sCommon.fGetDate())
			SET @lNextNumber = SCOPE_IDENTITY();
			SELECT @lNextNumber AS Result
        END
        ELSE
        BEGIN
            UPDATE 
				[sWellness].[tProgramSessionAttendance]
			SET			
				StoreLocationId = @rStoreLocationId,
				AttendedEmployee = @rAttendedEmployee,			
				AttendedDate = @rAttendedDate,	
				Remark = @rRemark,
				UpdatedUserId = @rUserId,
				UpdatedDateTime=sCommon.fGetDate()
			WHERE 
				AutoId = @rId

            SET @lNextNumber = @rId;
        END
        COMMIT TRANSACTION
        SELECT CAST(@lNextNumber AS NVARCHAR(10)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pAssignSurveyDetail]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAssignSurveyDetail]
(
	@rAssignSurveyId INT,
	@rParticipantSourceTypeId INT,
	@rParticipantSourceId BIGINT,
	@rCreatedUserId BIGINT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Result INT = 0;

	IF NOT EXISTS(Select 1 From [sSupport].[tAssignSurveyDetail] WHERE AssignSurveyId = @rAssignSurveyId AND SourceTypeId = @rParticipantSourceTypeId AND  SourceId = @rParticipantSourceId)
	BEGIN
		INSERT INTO [sSupport].[tAssignSurveyDetail]
           ([AssignSurveyId]
           ,[SourceTypeId]
           ,[SourceId]
           ,[TotalPoints]
           ,[EarnedPoints]
           ,[Percentage]
           ,[IndicatorName]
           ,[CreatedUserId]
           ,[CreatedDateTime])
		VALUES
           (@rAssignSurveyId
           ,@rParticipantSourceTypeId
           ,@rParticipantSourceId
           ,'0.0'
           ,'0.0'
           ,'0.0'
           ,'0.0'
           ,@rCreatedUserId
           ,sCommon.fGetDate())

		SET @Result = SCOPE_IDENTITY();
	END
	ELSE
	BEGIN
		SET @Result = -101;
	END
	SELECT @Result AS Id
END
GO
PRINT N'Creating Procedure [sWellness].[pBindDataEntryTemplateFromConsultation]...';


GO
  
CREATE OR ALTER PROCEDURE [sWellness].[pBindDataEntryTemplateFromConsultation]  
@rOrgId int,      
@rSourceTypeId Int = 10173,      
@rParticipantSourceTypeId Int,      
@rParticipantSourceId bigint, 
@rConsultationId bigint= 0  
AS      
  SET NOCOUNT ON      
  SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED      
  BEGIN      
      
Declare @rFlagDefault int = 0      
Declare @rDataEntryTemplateId bigint;

set @rDataEntryTemplateId = (select Top 1 Id from sExamination.tDataEntryTemplate where ExaminationTypeId = 17 and TemplateCode = 'WC')
      
  DECLARE @rAge int,@rGenderId int;
      
IF (@rParticipantSourceTypeId = 95)      
BEGIN      
   SELECT      
  @rAge = DATEDIFF(yy, DateOfBirth, GETDATE()),      
  @rGenderId = GenderId      
   FROM sHrm.vEmployeeCommonDetail      
   WHERE EmployeeId = @rParticipantSourceId      
      
   select *, @rAge as Age, (Case @rGenderId When 1 Then 'Male' When 2 Then 'Female' ELSE 'Not Known' END) as Gender      
   from sHrm.vEmployeeCommonDetail      
   Where EmployeeId = @rParticipantSourceId      
END      
ELSE      
BEGIN      
 SELECT      
  @rAge = DATEDIFF(yy, DateOfBirth, GETDATE()),      
  @rGenderId = GenderId      
   FROM sHrm.tCsrBenefiterMaster      
   WHERE Id = @rParticipantSourceId      
      
   select ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '') AS EmployeeName, *, @rAge as Age, (Case @rGenderId When 1 Then 'Male' When 2 Then 'Female' ELSE 'Not Known' END) as Gender from sHrm.tCsrBenefiterMaster      
   Where Id = @rParticipantSourceId  
END     
      
  --Vital      
  select 0 AS chkVitalChecked,    
 ISNULL(GTPM.Id,0) as GeneralTemplateParameterId,        
 ISNULL(GTEL.GeneralTemplateConsultationId,0) as GeneralTemplateConsultationId,       
 ISNULL(GTEL.GeneralTemplateConsultationDetailId,0) as GeneralTemplateConsultationDetailId,     
 ISNULL(GTM.Title,'') as GeneralTemplateMasterTitle,        
 ISNULL(GTM.Id,0) as GeneralTemplateMasterId,        
 convert(varchar,GTM.GeneralTemplateGroupId) as GeneralTemplateGroupId,      
         
 CASE WHEN ROW_NUMBER() OVER(PARTITION BY GTM.Title order by GTM.OrderIndex) = 1         
    THEN GTM.Title ELSE '' END as GeneralTemplateMasterTitleByGroup,        
   ISNULL(GTPM.Title,'') as GeneralTemplateParameterTitle,      
   ISNULL(GTPM.Id,'') as GeneralTemplateParameterId,      
         
 case when PVTM.Id = 2 then sExamination.fGetGeneralTemplateDropDownsNg(GTPM.Id,isnull(GTEL.ParameterValue,''),@rFlagDefault)        
 when PVTM.Id = 1 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end         
 when PVTM.Id = 3 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end else '' end  as GeneralTemplateDropDown,        
        
 case when PVTM.Id = 2 then sExamination.fGetGeneralTemplateDropDownSelectedTextNg(GTPM.Id,isnull(GTEL.ParameterValue,''),@rFlagDefault)        
 when PVTM.Id = 1 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end         
 when PVTM.Id = 3 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end else '' end  as SelectedTitle,        
         
 case when PVTM.Id = 2 then sExamination.fGetGeneralTemplateDropDownSelectedValueNg(GTPM.Id,isnull(GTEL.ParameterValue,''),@rFlagDefault)        
 when PVTM.Id = 1 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end         
 when PVTM.Id = 3 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end else '' end  as SelectedValue,        
       
 case when PVTM.Id = 2 then sExamination.fGetGeneralTemplateDropDownsNg(GTPM.Id,isnull(GTEL.ParameterValue,''),@rFlagDefault)        
 when PVTM.Id = 1 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end       
 when PVTM.Id = 3 then case when @rConsultationId = 0 then '' else isnull(GTEL.ParameterValue,'') end else '' end  as TemplateResult,      
       
 case when @rConsultationId = 0 then '' else isnull(GTEL.Remark,'') end as TemplateResultRemark,        
 case when isnull(TPR.Minimum,0) <> 0 and isnull(TPR.Maximum,0) <> 0 and isnull(GTPM.UOM,'') <> ''        
 then convert(varchar,TPR.Minimum) + ' - ' + convert(varchar,TPR.Maximum) + '( ' + UOM + ' )' else '' end  as RangeLabel,        
 ISNULL(PVTM.Title,'') as ParameterValueTitle,        
 *        
  from sExamination.tGeneralTemplateMaster GTM        
  left join sExamination.tStaticGeneralTemplateMaster SGM on GTM.StaticGeneralTemplateId = SGM.Id        
   inner join sExamination.tGeneralTemplateParameter GTPM on GTM.Id = GTPM.GeneralTemplateId        
   inner join sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = GTPM.Id      
   left join sOrderEntry.tParameterValueTypeMaster PVTM on PVTM.Id=GTPM.ParameterValueTypeId        
 left join        
 (        
  select GTE.GeneralTemplateId,        
  GeneralTemplateParameterId,        
  ParameterValue,        
  GTD.Remark,        
  GTE.Id as GeneralTemplateConsultationId,        
  GTD.Id as GeneralTemplateConsultationDetailId        
  from [sWellness].[tGeneralTemplateConsultation] GTE        
  inner join [sWellness].[tGeneralTemplateConsultationDetail] GTD on GTE.Id = GTD.GeneralTemplateConsultationId        
  where GTE.SourceId = @rConsultationId and GTE.OrgId = @rOrgId        
  and GTE.SourceTypeId = @rSourceTypeId        
 ) GTEL on GTEL.GeneralTemplateParameterId = GTPM.Id        
 AND GTEL.GeneralTemplateId = GTM.Id        
  left join        
   (        
    SELECT R.GeneralTemplateParameterId,R.AgeFrom,R.AgeTo,        
    R.Minimum,R.Maximum,R.IsNormal AS IsNormal        
    FROM sExamination.tGeneralTemplateParameterRange R        
    WHERE (R.AgeFrom <= @rAge or @rAge = 0) AND (R.AgeTo >= @rAge or @rAge = 0)        
    AND (R.GenderId = @rGenderId or @rGenderId = 0) AND IsNormal = 1        
   ) TPR ON GTPM.Id = TPR.GeneralTemplateParameterId AND GTPM.ParameterValueTypeId = 1        
        
   where GTM.OrgId = @rOrgId and GTM.GeneralTemplateGroupId = 4      
   and GTM.IsObsolete=0 AND DETS.SourceTemplateId = 119 AND DETS.DataEntryTemplateId = @rDataEntryTemplateId      
   order by isnull(GTPM.OrderIndex,0)      
      
  --Test      
  SELECT (case when TRR.TestRequestId > 0 then 1 else 0 end) AS chkTestChecked,      
    CONVERT(varchar, TM.Id) AS TMId,      
    CONVERT(varchar, TP.Id) AS TPId,      
    CONVERT(varchar, PVTM.Id) AS PVTMId,      
    CASE      
      WHEN ROW_NUMBER() OVER (PARTITION BY TM.Title ORDER BY TD.OrderIndex) = 1 THEN TM.Title      
      ELSE ''      
    END AS TMTitle,      
    ISNULL(TP.Title, '') AS TPTitle,     
    CASE WHEN @rConsultationId = 0 THEN ''      
          ELSE ISNULL(TRR.ServiceValue, '')      
    END AS TRRServiceValue,      
    ISNULL(sExamination.fGetTestResultsDropDowns(TP.ListValueTypeId, CASE      
      WHEN @rConsultationId = 0 THEN ''      
      ELSE ISNULL(TRR.ServiceValue, '')      
    END,      
    0, @rOrgId, 0), '') AS TestResultsDropDowns,      
    ISNULL(sExamination.fGetTestResultsDropDownsNgNew(TP.ListValueTypeId, CASE      
      WHEN @rConsultationId = 0 THEN ''      
      ELSE ISNULL(TRR.ServiceValue, '')      
    END,      
    0, @rOrgId, 0), '') AS TestResultsDropDownsData,      
    TP.ListValueTypeId AS TPListValueTypeId,      
    PVTM.Title AS PVTMTitle,      
 convert(varchar,TRR.Id)  as TRDId,    
    case when @rConsultationId = 0 then '' else isnull(TRR.Remark,'') end AS TRRRemark,      
    TP.StaticTestParameterId AS TPStaticTestParameterId,      
    [sExamination].[fGetParameterRange](TP.Id, @rAge, @rGenderId) AS ParameterRange,      
    TP.ParameterValueTypeId AS TPParameterValueTypeId,TP.Id as TestAreaId,    
 AM.AreaTypeId,TRR.IsPackageValue,    
    *,      
    LVTM.Id AS LVTMId,      
    @rAge AS age,      
    @rGenderId AS gender      
  FROM sOrderEntry.tTestMaster TM      
  INNER JOIN sOrderEntry.tTestDetail TD      
    ON TD.TestId = TM.Id      
  INNER JOIN sOrderEntry.tTestParameterMaster TP      
    ON TP.Id = TD.TestParameterId      
  INNER JOIN [sExamination].[tAreaMaster] AM ON AM.Id = TM.Id    
  INNER JOIN sExamination.tDataEntryTemplateSetup DETS on DETS.SourceParameterId = TP.Id      
  LEFT JOIN sOrderEntry.tParameterValueTypeMaster PVTM      
    ON PVTM.Id = TP.ParameterValueTypeId      
  LEFT JOIN sOrderEntry.tListValueTypeMaster LVTM      
    ON (LVTM.Id = TP.ListValueTypeId)      
    AND TP.Id = TD.TestParameterId      
  LEFT JOIN (SELECT      
      TR.Id AS TestRequestId,      
      TR.TestId,      
      TRD.Id,      
      TRD.TestDetailId,      
      TRD.ServiceValue,      
      TRD.Remark,
   case when Isnull(TR.IsPackage,0) = 0 then 'Y' else 'N' end IsPackageValue    
    FROM [sWellness].[tConsultationTestRequest] TR      
    INNER JOIN [sWellness].[tConsultationTestRequestDetail] TRD      
      ON TR.Id = TRD.TestRequestId    
    WHERE TR.SourceId = @rConsultationId      
    AND TR.SourceTypeId = @rSourceTypeId    
    AND TR.OrgId = @rOrgId      
    AND TRD.OrgId = @rOrgId) TRR      
      ON TRR.TestDetailId = TD.Id      
    AND TRR.TestId = TD.TestId    
  WHERE TM.OrgId = @rOrgId      
  AND DETS.SourceTemplateId = 118 AND DETS.DataEntryTemplateId = @rDataEntryTemplateId      
  ORDER BY ISNULL(TP.OrderIndex, 0)      
      
END
GO
PRINT N'Creating Procedure [sWellness].[pCoachCallRequestListGet]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pCoachCallRequestListGet] 
	@rEmployeeId bigint,
	@rOrgId smallint
AS
SET NOCOUNT ON

BEGIN
		 
DECLARE @Today DATE = CAST(sCommon.fGetDate() AS DATE);

SELECT
    Distinct
    AP.Id,
    AP.AppointmentNumber,
    AP.DoctorEmployeeId,
	ED.Code as EmployeeCode,
    ED.EmployeeName AS PatientName,
CASE 
    WHEN TRY_CAST(TM.FromTime AS TIME) IS NOT NULL
         AND TRY_CAST(TM.ToTime AS TIME) IS NOT NULL
         AND TRY_CAST(TM.FromTime AS TIME) <> '00:00:00'
         AND TRY_CAST(TM.ToTime AS TIME) <> '00:00:00'
    THEN 
        CONVERT(VARCHAR(8), TRY_CAST(TM.FromTime AS TIME), 100)
        + ' to ' +
        CONVERT(VARCHAR(8), TRY_CAST(TM.ToTime AS TIME), 100)
    ELSE '-'
END AS AppointmentTime,

CONVERT(VARCHAR,AP.AppointmentDate,103) AS AppointmentDateFormatted,

   ISNULL(PM.Title, 'Not Assigned') AS ProgramName

FROM [sWellness].[tAppointment] AP
INNER JOIN [sHrm].[vEmployeeDetail] ED 
    ON AP.PatientSourceId = ED.EmployeeId
LEFT JOIN [sWellness].[tMHIScore] MH
    ON AP.PatientSourceId = MH.EmployeeId
LEFT JOIN [sWellness].[tProgramMaster] PM
    ON MH.ProgramId = PM.Id
LEFT JOIN sAppointment.tTimeSlotMaster TM
ON AP.TimeSlotId = TM.Id
WHERE 
    AP.DoctorEmployeeId = @rEmployeeId
    AND AP.OrgId = @rOrgId
    AND AP.AppointmentDate >= @Today 
    AND AP.AppointmentDate < DATEADD(DAY,1,@Today)

ORDER BY AP.Id DESC;
		 
END
GO
PRINT N'Creating Procedure [sWellness].[pCoachScheduleListGet]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pCoachScheduleListGet] 
	@rEmployeeId bigint,
	@rOrgId smallint
AS
SET NOCOUNT ON

BEGIN
		 
DECLARE @Today DATE = CAST(sCommon.fGetDate() AS DATE);

SELECT
    Distinct
    AP.Id,
    AP.AppointmentNumber,
    AP.DoctorEmployeeId,
	ED.Code as EmployeeCode,
    ED.EmployeeName AS PatientName,
CASE 
    WHEN TRY_CAST(TM.FromTime AS TIME) IS NOT NULL
         AND TRY_CAST(TM.ToTime AS TIME) IS NOT NULL
         AND TRY_CAST(TM.FromTime AS TIME) <> '00:00:00'
         AND TRY_CAST(TM.ToTime AS TIME) <> '00:00:00'
    THEN 
        CONVERT(VARCHAR(8), TRY_CAST(TM.FromTime AS TIME), 100)
        + ' to ' +
        CONVERT(VARCHAR(8), TRY_CAST(TM.ToTime AS TIME), 100)
    ELSE '-'
END AS AppointmentTime,

	CONVERT(VARCHAR,AP.AppointmentDate,103) AS AppointmentDateFormatted,

  ISNULL(PM.Title, 'Not Assigned') AS ProgramName

FROM [sWellness].[tAppointment] AP
INNER JOIN [sHrm].[vEmployeeDetail] ED 
    ON AP.PatientSourceId = ED.EmployeeId
LEFT JOIN [sWellness].[tMHIScore] MH
    ON AP.PatientSourceId = MH.EmployeeId
LEFT JOIN [sWellness].[tProgramMaster] PM
    ON MH.ProgramId = PM.Id
LEFT JOIN sAppointment.tTimeSlotMaster TM
ON AP.TimeSlotId = TM.Id
WHERE 
    AP.DoctorEmployeeId = @rEmployeeId
    AND AP.OrgId = @rOrgId
    AND AP.AppointmentDate >= DATEADD(DAY,1,@Today)

ORDER BY AP.Id DESC;
		 
END
GO
PRINT N'Creating Procedure [sWellness].[pConsultationAdd]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pConsultationAdd]
@rId bigint,
@rOrgId smallint,
@rParticipantSourceTypeId smallint,
@rParticipantSourceId bigint,
@rSetupId bigint,
@rMainTypeId int,
@rConsultationDate date,
@rDoctorFlag int = null,
@rDoctorEmployeeId bigint  = NULL,
@rStatusId int,
@rStoreLocationId bigint,
@rCauseId int = null,
@rConsultationNotes nvarchar(2000) = '',
@rConsultationRemarks nvarchar(2000) = '',
@rConsultationTime nvarchar(50) = '',
@rConsultationOutTime nvarchar(50) = '',
@rCreatedUserId bigint,
@rUpdatedUserId bigint = 0
AS
SET NOCOUNT ON
BEGIN
declare @trancount int;


	BEGIN TRY		
        begin transaction
	set @trancount = @@trancount;        

		declare @exceptiondetail nvarchar(max)
		if @rCreatedUserId = 0
		begin
			SELECT -101 AS RESULT
			return
		end
		if @rParticipantSourceId = 0
		begin
			SELECT -102 AS RESULT
			return
		end
		if @rParticipantSourceTypeId = 0
		begin
			SELECT -103 AS RESULT
			return
		end	  
		  
		IF(@rDoctorEmployeeId <= 0)
			SET @rDoctorEmployeeId = NULL
			
		DECLARE @lNextNumber bigint,@lEmployeeDesignationId int

		IF (@rId = 0)
		BEGIN
			INSERT INTO [sWellness].[tWellnessConsultation] 
			(
				OrgId,ParticipantSourceTypeId,ParticipantSourceId,ConsultationDate,
				DoctorEmployeeId,SetupId,CauseId,StatusId,StoreLocationId,ConsultationNotes,ConsultationRemarks,
				ConsultationTime,ConsultationOutTime,CreatedUserId,CreatedDateTime,
				UpdatedUserId,UpdatedDateTime
			)
			VALUES
			(
				@rOrgId,@rParticipantSourceTypeId,@rParticipantSourceId,@rConsultationDate,
				@rDoctorEmployeeId,@rSetupId,@rCauseId,1,@rStoreLocationId,@rConsultationNotes,@rConsultationRemarks,
				@rConsultationTime,@rConsultationOutTime,@rCreatedUserId,sCommon.fGetDate(),
				@rUpdatedUserId,sCommon.fGetDate()
			)
			
			select @lNextNumber = SCOPE_IDENTITY()

			declare @cnt bigint = 0,@prefix varchar(100),@Title varchar(100),@cn varchar(300)

			select @Title = Title from sExamination.tSetupMaster where Id = @rSetupId

			select @cnt = Max(Right(ISNULL(ConsultationNumber,00000),13)) from [sWellness].[tWellnessConsultation] where isnull(ConsultationNumber,'') <> ''
			and DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 and SetupId = @rSetupId
			and StoreLocationId = @rStoreLocationId

			if len(@cnt)=12
			begin
			select @cnt = Right(isnull(@cnt,00000),4)
			end
			else if(len(@cnt)=13)
			begin
			select @cnt = Right(isnull(@cnt,00000),5)
			end
			else
			begin
			select @cnt = Right(isnull(@cnt,00000),4)
			end
			
			if(@cnt=9999)
			begin
				select @cnt = @cnt + 1 +(select count(*) from [sWellness].[tWellnessConsultation] 
				where isnull(ConsultationNumber,'') <> '' and 
				DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 
				and SetupId = @rSetupId	and StoreLocationId = @rStoreLocationId)
			end
			else
			begin
			select @cnt = @cnt + 1
			end

			select @prefix = case when sCommon.fGetIntIdForOrg(17,@rOrgId) = @rSetupId then
			'WC-' + sCommon.fGetFormattedDate()  + RIGHT(100000 + (@cnt) ,5) else '' end

			update [sWellness].[tWellnessConsultation] set ConsultationNumber = @prefix where Id = @lNextNumber
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE [sWellness].[tWellnessConsultation] SET OrgId = @rOrgId,ParticipantSourceTypeId  = @rParticipantSourceTypeId,
			ParticipantSourceId  = @rParticipantSourceId, ConsultationDate = @rConsultationDate,
			DoctorEmployeeId = case when isnull(@rDoctorFlag,0) = 1 then DoctorEmployeeId else @rDoctorEmployeeId end,
			CauseId = @rCauseId,ConsultationNotes=@rConsultationNotes,ConsultationRemarks=@rConsultationRemarks,
			ConsultationTime=@rConsultationTime,ConsultationOutTime=@rConsultationOutTime,
			UpdatedUserId =  case when @rUpdatedUserId>0 then @rUpdatedUserId else @rCreatedUserId end,
			UpdatedDateTime = sCommon.fGetDate()
			WHERE Id = @rId
		END
		SELECT @lNextNumber AS Result		
		
      commit tran;
	END TRY
	BEGIN CATCH
	declare @error int, @message varchar(4000), @xstate int,@username nvarchar(200);
		select @error = ERROR_NUMBER(),
               @message = ERROR_MESSAGE(), 
               @xstate = XACT_STATE();
		set @username =(select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(CreatedUserId,0))
		--if @xstate = -1
  --          rollback;
  --      if @xstate = 1 and @trancount = 0
  --          rollback
  --      if @xstate = 1 and @trancount > 0
            rollback transaction;

		set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
		<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>
		<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
		<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>
		<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>
		<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>
		</Table>'

		insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)
		Select @rOrgId,'Consultation_Main_DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rCreatedUserId	
		SELECT -1 AS RESULT
		return
	END CATCH	
	
END
GO
PRINT N'Creating Procedure [sWellness].[pConsultationLoadAllDropDownLists]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pConsultationLoadAllDropDownLists]
    @rStoreLocationId INT,
    @rOrgId INT,
    @rLocationId INT
AS
BEGIN
    SET NOCOUNT ON;

    -- Query 1: Employee/Doctor data
    SELECT 
        d.EmployeeId as Id,
        ISNULL(e.EmployeePrefix + ' ', '') + e.FirstName + ' ' + e.LastName AS Title 
    FROM sCwb.tDoctorMaster d 
    INNER JOIN sHrm.tEmployeeMaster e ON d.EmployeeId = e.Id 
    INNER JOIN sCwb.tDoctorStoreLocation S ON d.EmployeeId = S.EmployeeId 
    WHERE S.SubLocationId = @rStoreLocationId 
        AND e.StatusId = 7 AND ISNULL(d.IsWellness,0) = 1;

    -- Query 2: Clinic Master
    SELECT Id, Title, isnull(DoctorName,'') as DoctorName
    FROM sCommon.tClinicMaster 
    WHERE IsObsolete = 0 
        AND OrgId = @rOrgId 
        AND LocationId = @rLocationId;

    -- Query 3: Wellness Visit Purpose
    SELECT WVP.Id, WVP.Title
    FROM sWellness.tWellnessVisitPurposeMaster WVP
    WHERE WVP.IsObsolete = 0 AND WVP.OrgId = @rOrgId;

    -- Query 4: Further Action Master
    SELECT 
        Id,
        Code,
        Title,
        IsHospitalDoctor 
    FROM sSafety.tFurtherActionMaster 
    WHERE IsObsolete = 0 
        AND OrgId = @rOrgId 
    ORDER BY Id, Title DESC;

    -- Query 5: Gender Master
    SELECT 
        Id,
        Title 
    FROM sCommon.tGenderMaster 
    WHERE IsObsolete = 0;

	-- Query 6: Wellness Activity Category
    SELECT Id, Title 
    FROM [sWellness].[tWellnessActivityCategoryMaster]
    WHERE IsObsolete = 0;

	-- Query 7: Wellness Activity
    SELECT ActivityId as Id, ActivityName as Title, WellnessActivityCategoryId, DefaultUnitId
    FROM [sWellness].[tWellnessActivityMaster]
    WHERE IsObsolete = 0;

	-- Query 8: Wellness Activity Task
    SELECT Id,[Name] as Title,ActivityId, TargetValue, 
		   FrequencyTypeId, FrequencyCount, DurationDays
    FROM [sWellness].[tWellnessActivityTaskMaster]
END;
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramMaster]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		BEGIN TRANSACTION;

		DECLARE @DeletedRows INT;
				DELETE FROM [sWellness].[tProgramMaster] WHERE OrgId = @rOrgId  AND Id = @rId;
				SET @DeletedRows = @@ROWCOUNT;

				IF @DeletedRows > 0
				BEGIN
					DELETE FROM [sWellness].[tProgramLocation] WHERE ProgramId = @rId;
					DELETE FROM [sWellness].[tProgramCoach] WHERE ProgramId = @rId;
					DELETE FROM [sWellness].[tProgramParameter] WHERE ProgramId = @rId;
					DELETE FROM [sWellness].[tProgramDocument] WHERE ProgramId = @rId;

					COMMIT TRANSACTION;
					SELECT 1 AS Result;
				END
				ELSE
				BEGIN
					ROLLBACK TRANSACTION;
					SELECT 0 AS Result;
				END
		END TRY
		BEGIN CATCH
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION;
			SELECT -101 AS Result;
		END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramParameter]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramParameter]
(
    @rId INT
)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @Result INT;
	IF EXISTS 
	(
        SELECT 1 FROM [sWellness].[tProgramParameterTrack] WHERE ProgramParameterId = @rId
    )
    BEGIN
         SET @Result = -101;
		  SELECT @Result AS Result;
        RETURN;
    END
    
    DELETE FROM [sWellness].[tProgramParameter]
    WHERE AutoId = @rId;
	 SET @Result=@rId;
	 SELECT @Result AS Result;
     RETURN;
END
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramSessionAttendance]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramSessionAttendance]
(
    @rId INT,
	@rProgramId INT
)
AS
BEGIN
    DELETE FROM 
		[sWellness].[tProgramSessionAttendance]
	WHERE
		ProgramId = @rProgramId  
	AND 
		AutoId = @rId ;

	SELECT CASE WHEN @@ROWCOUNT = 1 THEN 1 ELSE 0 END AS Result;
	RETURN;
END
GO
PRINT N'Creating Procedure [sWellness].[pEmpDailyTaskDetailsGet]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pEmpDailyTaskDetailsGet]
(@rEmpId BIGINT)
AS
BEGIN
SELECT 
    AA.AssignedActivityId,
    ISNULL(AA.WellnessActivityTaskId,0) AS WellnessActivityTaskId,
    AA.ConsultationId,
    CASE 
        WHEN AA.IsCustomActivityTask = 1 
            THEN AA.WellnessActivityCustom
        ELSE WATM.Name
    END AS TaskName,
    CAST(GETDATE() AS DATE) AS TaskDate,
    ISNULL(ETT.Status, 0) AS TaskStatus   -- Pending 0 and Completed 1
FROM 
    [sWellness].[tAssignedActivity] AA
LEFT JOIN 
    [sWellness].[tWellnessActivityTaskMaster] WATM 
ON 
    WATM.Id = AA.WellnessActivityTaskId
    AND ISNULL(AA.IsCustomActivityTask,0) <> 1
LEFT JOIN 
    [sWellness].[tEmployeeTaskTrack] ETT 
ON  
    ETT.EmployeeId = AA.EmployeeId 
    AND ETT.WellnessActivityTaskId = AA.WellnessActivityTaskId
    AND CAST(ETT.TaskDate AS DATE) = CAST(GETDATE() AS DATE)   -- Only today's entry
WHERE 
    AA.EmployeeId = @rEmpId
    AND CAST(GETDATE() AS DATE) 
        BETWEEN CAST(AA.WeekStart AS DATE) AND CAST(AA.WeekEnd AS DATE)
END
GO
PRINT N'Creating Procedure [sWellness].[PempDashboardDetailGet_MHI]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[PempDashboardDetailGet_MHI]
(
	@rEmpId bigint,
	@rOrgId int = 0
)
AS
BEGIN

	DECLARE @lLatestVitalDisplayConfigVal varchar(5) = 'False';
      
	IF (@rOrgId > 0)
	BEGIN
		select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);
	END

	Declare @lHealthIndexScore decimal(10,2),@lOpdCount int,@lHeight int,@lWeight decimal(8,2),@lBMI decimal(8,2),@lBloodPressureSystolic int
	,@lBloodPressureDiastolic int,@lFBS nvarchar(10),@lHB nvarchar(10),@lchol nvarchar(10),@lTreatment nvarchar(500),@lPreviousOPDVisit nvarchar(max)
	,@lInjuryDate nvarchar(20),@lInjuryTime nvarchar(20),@lInjuryTreatment nvarchar(500),@lInjuryDiagnisis nvarchar(500),@lsurgery nvarchar(500)
	,@lLastExaminationId bigint,@lLastDiagnosis nvarchar(500),@lLastRecomendation nvarchar(500),@lLastExaminationdate nvarchar(20),
	@labnoramltest nvarchar(MAX),@lHealthAnalysis nvarchar(1000),@lRBS nvarchar(10),@lHBA1C nvarchar(10), @lHealthScoreDate nvarchar(20),
	@lBMIDate nvarchar(20), @lBPDate nvarchar(20), @lBloodSugarDate nvarchar(20), @lCholesterolDate nvarchar(20), @lHBDate nvarchar(20),
	@lMetabolicSyndrome bit, @lCVDMajorRisk bit, @lCVDMinorRisk bit, @lNCDsRisk bit,@lLDL decimal(8,2),
	@MHIBiometricsCategory NVARCHAR(20) = 'Pending', @MHIStressCategory NVARCHAR(20) = 'Pending', @MHILifestyleCategory NVARCHAR(20) = 'Pending', @MHISurveyCategory NVARCHAR(20) = 'Pending', @MHICategory NVARCHAR(20),
	@MHIHBA1C NUMERIC(10,2)=0, @MHILDL NUMERIC(10,2)=0, @MHIBMI NUMERIC(10,2)=0,  @MHIBP NVARCHAR(20) = ''


	Select @lHealthIndexScore = (select top 1 Convert(decimal(10,2),Round(Isnull(D.HealthIndex,0),2)) 
	from sExamination.tExamination E 
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
	Order by E.ExaminationDate desc)

	Select @lHealthScoreDate = (select top 1 convert(varchar(20),ExaminationDate,103)
	from sExamination.tExamination E
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
	Order by E.ExaminationDate desc)

	Select @lOpdCount = Count(E.id)
	from sExamination.tExamination E 
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
	and STM.MainTypeId=8

	Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103) -- mantis 27146, dt - 10/10/2023, Nidhi Pandey (remove Round() from weight)
	from sExamination.tExamination E 
	inner join sExamination.tVital V on V.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order by E.ExaminationDate desc

	Select Top 1 @lBloodPressureSystolic=BloodPressureSystolic,@lBloodPressureDiastolic=BloodPressureDiastolic,
	@lBPDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tExamination E 
	inner join sExamination.tVital V on V.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and Isnull(V.BloodPressureSystolic,0)>0 and Isnull(V.BloodPressureDiastolic,0)>0 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order by E.ExaminationDate desc

	Select Top 1 @lFBS=TRD.ServiceValue, @lBloodSugarDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
			inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
			inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 19 and  Isnull(TRD.ServiceValue,'')<>'' 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order By E.ExaminationDate desc

	Select Top 1 @lRBS=TRD.ServiceValue
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 21 and  Isnull(TRD.ServiceValue,'')<>''
	Order By E.ExaminationDate desc

	Select Top 1 @lHBA1C=TRD.ServiceValue
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 25 and  Isnull(TRD.ServiceValue,'')<>''
	Order By E.ExaminationDate desc

	---LDL-----
	Select Top 1 @lLDL=TRD.ServiceValue
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 34 and  Isnull(TRD.ServiceValue,'')<>''
	Order By E.ExaminationDate desc


	Select Top 1 @lHB=TRD.ServiceValue, @lHBDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
			inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
			inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 2 and  Isnull(TRD.ServiceValue,'')<>'' 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order By E.ExaminationDate desc

	Select Top 1 @lchol=TRD.ServiceValue, @lCholesterolDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
			inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
			inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 31 and  Isnull(TRD.ServiceValue,'')<>'' 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order By E.ExaminationDate desc

	Select  @lTreatment = COALESCE(@lTreatment,'') + Isnull(SIM.Title,'') + ','
	From sExamination.tExamination E
	LEFt join sExamination.tPrescription P on P.SourceId=E.id
	LEFt join sExamination.tPrescriptionDetail PD on PD.PrescriptionId=p.id
	Left join sIp.tStockItemMaster SIM on SIM.id=PD.StockItemId
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=8
	and E.id in(Select Top 1 E.ID from sExamination.tExamination E inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95 and STM.MainTypeId=8
	AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
	Order By E.ExaminationDate desc)
	Order By E.ExaminationDate desc

	print @lTreatment
	SET @lTreatment = Replace(LEFT(@lTreatment, LEN(@lTreatment) - 1),',','</br>')
	print @lTreatment

	select Top 1 @lPreviousOPDVisit = '<p class="color_black" style=""><span class="inner_content_left" style="">Date & Time :</span><span class="inner_content_right" style="">
	'+convert(varchar(20),E.ExaminationDate,103)+' '+replace(replace(Right(convert(varchar(20),E.CreatedDateTime,100),7),'AM',' AM'),'PM',' PM')+'</span></p>
	<p class="color_black" style=""><span class="inner_content_left" style="">Visit Purpose :</span><span class="inner_content_right" style="">'+ CM.Title +'</span></p>
	<p class="color_black" style=""><span class="inner_content_left" style="">Diagnosis :</span><span class="inner_content_right" style="color: #7b6f10; font-weight: bold;">'+([sExamination].[fExistingDiseaseGet](E.ID))+'
	</span></p><p class="color_black" style=""><span class="inner_content_left" style="">Treatment :</span><span class="inner_content_right" style="">'+ @lTreatment +'</span></p>'
	from sExamination.tExamination E 
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	inner join sExamination.tCauseMaster CM on CM.Id=E.CauseId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=8
	AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
	Order By E.ExaminationDate desc

	select Top 1 @lInjuryDate=Convert(varchar(20),IA.IncidentDate,104),@lInjuryTime=IncidentTime,@lInjuryDiagnisis=Isnull(IncidentRemark,''),@lInjuryTreatment=Isnull(TreatmentRemark,'')
	From sIncident.tAccident IA
	Inner JOIN sExamination.tExamination EE ON IA.ExaminationId=EE.Id 
	Where EE.ParticipantSourceId=@rEmpId and EE.ParticipantSourceTypeId=95
	Order by EE.ExaminationDate Desc

	select @lsurgery= case when Isnull(IsSurgeryDone,0)= 1 then 'Yes' else 'No' end + '-' + Isnull(H.SurgeryRemark,'')
	from sExamination.tHistory H
	where H.ParticipantSourceId =@rEmpId and H.Isobsolete=0

	select Top 1 @lLastExaminationId=E.Id,@lLastExaminationdate=convert(varchar(20),ExaminationDate,104),@lLastDiagnosis=Isnull(DiagnosisRemark,'')
	,@lLastRecomendation=Isnull(RecommendationEnglish,'')
	from sExamination.tExamination E 
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1
	Order by E.ExaminationDate desc

	select @labnoramltest = COALESCE(@labnoramltest,'') + TPM.Title + '- ' + TRD.ServiceValue + ' ,'
	FROM sExamination.tTestRequest TR	
		INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id AND isnull(TR.IsObsolete,0) = 0
		INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id and TR.TestId = TD.TestId
		INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
	where TR.SourceId=@lLastExaminationId and Isnull(TRD.IsAbnormal,0)<>0

	SET @labnoramltest = Replace(LEFT(@labnoramltest, LEN(@labnoramltest) - 1),',','</br>')
	print @lLastExaminationId

	DECLARE @HabitName VARCHAR(1000)
	(SELECT @HabitName = COALESCE(@HabitName,'') + ISNULL(H.Title,'')
	+ '-' + Convert(varchar(10),ISNULL(HHD.Duration,'')) + ' ' + ISNULL(DUM.Title,'') + ', ' 
	FROM sExamination.tHabitHygineDetail HHD 
	INNER JOIN sExamination.tHabitHygine HH ON HH.Id = HHD.HabitHygineId 
	INNER JOIN sExamination.tHabitTypeMaster H ON HHD.HabitId = H.Id
	LEft Join sCommon.tDurationUnitMaster DUM on DUM.id=HHD.DurationUnitId
	WHERE HH.SourceId = @lLastExaminationId AND HH.Isobsolete=0
	)
	  SET @HabitName = Replace(Replace(LEFT(@HabitName, LEN(@HabitName) - 1),',','</br>'),'0','')

	declare @lConfValue int
			select @lConfValue = ISNULL(CS.ItemValue,CM.ItemValue)
			from sConfig.tConfigurationMaster as CM
			LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
			where CM.ItemKey = 'FirstAid.SetTrainingRenewal'

	SELECT @lHealthAnalysis = COALESCE(@lHealthAnalysis,'') + HIM.Title + ' - '		
			+ Convert(varchar(100),CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints))))) + ' - '
			+ (SELECT (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints)))) AND CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI

	.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints))))>RangeFrom)
			+ ' ,'
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID=EXM.SetupId
		INNER JOIN sExamination.tSubTypeMaster SSM ON SSM.Id = STM.SubTypeId 
		INNER JOIN sExamination.tHealthIndex AS  HI ON HI.ExaminationId=EXM.Id  
		INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIM ON HIM.ID=HI.HealthIndexParameterId
	WHERE EXM.ParticipantSourceTypeId=95 
		AND  HI.TotalPoints > 0
		AND EXM.Id=@lLastExaminationId
		AND  SSM.MainTypeId=1 
	GROUP BY HI.HealthIndexParameterId,HIM.Title
		ORDER BY HI.HealthIndexParameterId

	SET @lHealthAnalysis = Replace(LEFT(@lHealthAnalysis, LEN(@lHealthAnalysis) - 1),',','</br>')

	DECLARE @HealthHeader varchar(max) = '',@HealthDetail varchar(max) = ''
	SELECT @HealthHeader = '<tbody><tr><th>Date</th><th>HealthScore</th><tr>'

	Select @HealthDetail = @HealthDetail + '<tr><td>'+ convert(varchar(20),E.ExaminationDate,104)+ '</td><td>' + Convert(varchar(10),Convert(decimal(10,2),Round((Isnull(D.HealthIndex,0)),2))) + '</td></tr>'
	from sExamination.tExamination E 
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0

	--select @HealthHeader + @HealthDetail
	print @HealthHeader + @HealthDetail + '</tbody>'

	Select TOP 1 @lMetabolicSyndrome = ISNULL(DTE.MetabolicSyndrome, 0), @lCVDMajorRisk = ISNULL(DTE.CVDMajorRisk, 0), 
				 @lCVDMinorRisk = ISNULL(DTE.CVDMinorRisk, 0), @lNCDsRisk = ISNULL(DTE.NCDsRisk, 0)
	from sExamination.tExamination E
	inner join sExamination.tDiagnosisTrackerEmployee DTE on DTE.ExaminationId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1
	Order by E.ExaminationDate desc


	SELECT TOP 1 @MHIBiometricsCategory = BiometricsCategory, @MHIStressCategory = StressCategory, @MHILifestyleCategory = LifestyleCategory, @MHISurveyCategory = SurveyCategory, @MHICategory = MHICategory , 
				 @MHIHBA1C = HBA1C, @MHILDL = LDL , @MHIBMI = BMI, @MHIBP = BP
		   FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmpId

	   

	Select EM.Id AS EmployeeId,
		'Emp ID : ' + EM.Code as Code,	
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
		convert(varchar(20),(DATEDIFF(yy,EPD.DateOfBirth,GETDATE()))) + ' Years ' + ' ' + Isnull(GM.Title,'') AS Years,
		Isnull(BGM.Title,'') as BloodGroup,
		'Working Since Last ' + Convert(varchar(20),(DATEDIFF(yy,EJD.DateOfJoining,GETDATE()))) + ' Years ' as WorkingSince,
		'Dept: ' + ISNULL(ODM.Title,'') AS DepartmentName,
		'Emp Type : ' + Isnull(ETM.Title,'') as EmployeeType,
		'' as allergies,
		'Reporting Mgr : ' + ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') ReportingMangerName,
		ISNULL(EC.CompanyEmail,'') AS EmailId,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		isnull(EC.PresentStreetOne,'') as Add1,
		isnull(EC.PresentStreetTwo,'') as Add2,
		isnull(EC.PresentStreetThree,'') + ','+isnull(EC.PresentCity,'')+','+isnull(EC.PresentState,'') as Add3,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		--isnull(EI.EmployeePhoto,0) as EmployeePhoto
		(SELECT TOP 1 CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) as EmployeePhoto,
		Isnull(@lHealthIndexScore,0) as HEALTHSCORE,
		Isnull(@lOpdCount,0) as OpdCount,
		'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,
		'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,
		Isnull(@lHeight,0) as Height1,
		Isnull(@lWeight,0) as Weight1,
		Isnull(@lBMI,0) as BMI,
		convert(varchar(10),@lBloodPressureSystolic) + '/' + Convert(varchar(10),@lBloodPressureDiastolic) as BP,
		Isnull(@lFBS,'0') as BloodSugar,
		Isnull(@lHB,'0') + ' g/dl' as Haemoglobin,
		Isnull(@lchol,'0') as Cholesterol,
		@lPreviousOPDVisit as PreviousOPDVisit,
		Replace([sExamination].[fFamilyHistoryWithRelationGet](@rEmpId),'-','- ') as FamilyHistory,
		Replace([sExamination].[fHistoryGet_new](@rEmpId),'-',' ') as History,
		@lInjuryDate as InjuryDate,
		@lInjuryTime as InjuryTime,
		@lInjuryDiagnisis as InjuryDiagnisis,
		@lInjuryTreatment as InjuryTreatment,
		@lsurgery as surgery,
		@lLastExaminationdate as LastExaminationdate,
		@lLastDiagnosis as LastDiagnosis,
		@lLastRecomendation as LastRecomendation,
		[sExamination].[fExistingDiseaseWithDurationUnitGet](@lLastExaminationId) as ExistingDisease,
		@labnoramltest as AbnormalTest,
		@HabitName as Habits,
		Isnull(P.Remark,'') as Allergy,
		convert(varchar(20),isnull(EPD.FirstAidTrainingDate,''),104) as FirstAidTrainingDate,
		convert(varchar(20),DATEADD(d,@lConfValue, EPD.FirstAidTrainingDate),104) as NextTraningDate,
		LM.Title as Location,
		@lHealthAnalysis as HealthAnalysis,
		@HealthHeader + @HealthDetail + '</tbody>' as healthdata,
		Isnull(@lRBS,'0') as RBS,
		Isnull(@lHBA1C,'0') as HBA1C,
		Isnull(@lLDL,'0') as LDL,
		@lHealthScoreDate as HealthScoreDate,
		@lBMIDate as BMIDate,
		@lBPDate as BPDate,
		@lBloodSugarDate as BloodSugarDate,
		@lCholesterolDate as CholesterolDate,
		@lHBDate as HBDate,
		@lMetabolicSyndrome as MetabolicSyndrome, @lCVDMajorRisk as CVDMajorRisk, 
		@lCVDMinorRisk as CVDMinorRisk, @lNCDsRisk as NCDsRisk,
		ISNULL(@MHIBiometricsCategory,'Pending') AS MHIBiometricsCategory,
		ISNULL(@MHIStressCategory,'Pending') AS MHIStressCategory,
		ISNULL(@MHILifestyleCategory,'Pending') AS MHILifestyleCategory,
		ISNULL(@MHISurveyCategory,'Pending') AS MHISurveyCategory,
		ISNULL(@MHICategory,'Pending') AS MHISurveyCategory,
		ISNULL(@MHIHBA1C,0) AS MHIHBA1C,
		ISNULL(@MHILDL,0) AS MHILDL,
		ISNULL(@MHIBMI,0) AS MHIBMI,
		ISNULL(@MHIBP,0) AS MHIBP
	FROM 
		sHrm.tEmployeeMaster EM
	INNER JOIN 
		sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	INNER JOIN 
		sCommon.tLocationMaster LM on LM.ID = EJD.EmployeeLocationId
	LEFT JOIN 
		sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
	LEFT JOIN 
		sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
	LEFT JOIN 
		sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
	LEFT JOIN 
		sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id = EJD.EmployeeJobTitleId
	LEFT JOIN 
		sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
	LEFT JOIN 
		sCommon.tBloodGroupMaster BGM ON BGM.Id = EPD.BloodGroupId
	LEFT JOIN 
		sCommon.tOrganizationDepartmentMaster ODM	ON EJD.OrganizationDepartmentId = ODM.Id
	LEFT JOIN 
		sHrm.tEmployeeTypeMaster ETM on ETM.Id=EJD.EmployeeTypeId
	LEFT JOIN 
		Shrm.temployeemaster EM1 on EM1.Id=EJD.ReportingMangerEmployeeId
	LEFT JOIN 
		sHrm.tEmployeeImages EI on EI.EmployeeId=EM.id
	LEFT JOIN 
		sExamination.tPrompt P on P.ParticipantId	=EM.id and P.ParticipantSourceTypeId=95
	WHERE
		EM.Id=@rEmpId
END
GO
PRINT N'Creating Procedure [sWellness].[pEmployeeMHIScoreList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pEmployeeMHIScoreList]
(
	@rOrgId SMALLINT = 0,
	@rProgramId INT = 0,
	@rDepartmentId INT = 0,
	@rLocationId INT = 0,
	@rUserId BIGINT
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT *
	FROM
	(
		SELECT DISTINCT
			MHI.Id,
			MHI.CreatedDateTime,
			MHI.UpdatedDateTime,
			ISNULL(EEM.Code,'-') AS EmployeeCode,
			ISNULL(EEM.EmployeeName,'-') AS EmployeeName,
			ISNULL(PM.Title,'-') AS ProgramName,
			ISNULL(EEM.DepartmentName,'-') AS DepartmentName,
			ISNULL(MHI.HBA1C,0) AS HBA1C,
			ISNULL(MHI.HBA1CCategory,'Pending') AS HBA1CCategory,
			ISNULL(MHI.LDL,0) AS LDL,
			ISNULL(MHI.LDLCategory,'Pending') AS LDLCategory,
			ISNULL(MHI.BMI,0) AS BMI,
			ISNULL(MHI.BMICategory,'Pending') AS BMICategory,
			ISNULL(MHI.BP,0) AS BP,
			ISNULL(MHI.BPCategory,'Pending') AS BPCategory,
			ISNULL(MHI.Biometrics,0) AS Biometrics,
			ISNULL(MHI.BiometricsCategory,'Pending') AS BiometricsCategory,
			ISNULL(MHI.Stress,0) AS Stress,
			ISNULL(MHI.StressCategory,'Pending') AS StressCategory,
			ISNULL(MHI.Lifestyle,0) AS Lifestyle,
			ISNULL(MHI.LifestyleCategory,'Pending') AS LifestyleCategory,
			ISNULL(MHI.SurveyCategory,'Pending') AS SurveyCategory,
			ISNULL(MHI.MHICategory,'Pending') AS MHICategory,
			MHI.ProgramId,
			MHI.EmployeeId,
			CASE 
				WHEN MHI.UpdatedDateTime IS NOT NULL THEN CONVERT(VARCHAR(10), MHI.UpdatedDateTime, 103)
				WHEN MHI.CreatedDateTime IS NOT NULL THEN CONVERT(VARCHAR(10), MHI.CreatedDateTime, 103)
				ELSE '-' END AS LastUpdated,
			ISNULL(MHI.UpdatedDateTime, MHI.CreatedDateTime) AS SortDate
		FROM 
			[sWellness].[tMHIScore] MHI
		INNER JOIN 
			[sHrm].[vExtEmployeeMaster] EEM
		ON 
			EEM.EmployeeId = MHI.EmployeeId
		INNER JOIN 
			[sIp].[tStoreLocationMaster] SLM
		ON 
			SLM.LocationId = EEM.EmployeeLocationId
		INNER JOIN 
			sSecurity.tUserLocation UL
		ON 
			UL.StoreLocationId = SLM.Id
		INNER JOIN 
			[sWellness].[tProgramMaster] PM
		ON 
			PM.Id = MHI.ProgramId
		WHERE
			((@rProgramId = 0) OR (MHI.ProgramId = @rProgramId))
		AND 
			((@rDepartmentId = 0) OR (EEM.DepartmentId = @rDepartmentId))
		AND 
			((@rLocationId = 0) OR (EEM.EmployeeLocationId = @rLocationId))
		AND 
			MHI.ProgramId > 0
		AND 
			(MHI.BiometricsCategory IS NOT NULL  OR MHI.SurveyCategory IS NOT NULL  OR MHI.MHICategory IS NOT NULL)
		AND 
			MHI.OrgId = @rOrgId
		AND 
			UL.UserId = @rUserId
	) AS A
	ORDER BY A.SortDate DESC;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetActivityCategoryList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetActivityCategoryList]

AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		Id,
        Title
    FROM 
	[sWellness].[tWellnessActivityCategoryMaster] 
	where IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pGetAllConsultationDetails]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetAllConsultationDetails] 
@rConsultationId bigint,    
@rOrgId int,    
@rStoreLocationId int    
as    
SET NOCOUNT ON    
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED    
begin    
 declare @rParticipantId bigint,@rParticipantSourceTypeId int,@lothermedicines nvarchar(1000)    
 select @rParticipantId = ParticipantSourceId,@rParticipantSourceTypeId = ParticipantSourceTypeId    
 from sWellness.tWellnessConsultation where Id = @rConsultationId    

 select EE.Id, EE.Id as ConsultationId,
 isnull(EE.ConsultationNumber,'') as ConsultationNumber,
 EE.ConsultationDate,
 ParticipantName = EM.FirstName + ' ' + EM.LastName,
 ParticipantCode = EM.Code,
 EE.ParticipantSourceTypeId,    
 EE.ParticipantSourceId,  
 EE.SetupId,  
 EE.DoctorEmployeeId,
 isnull(C.Id,0) as CauseId,
 isnull(EM.StatusId,0) as EmployeeStatusId,   
 isnull(convert(varchar,EE.ConsultationDate,103),'') as ExDate,
 isnull(G.Title,'') AS Gender,
 Age = case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end,    
 isnull(SA.Id,'') as WellnessAppointmentId,    
 isnull(convert(varchar,SA.AppointmentDate,103),'') as AppointmentDate,    
 isnull(SA.FollowupRemark,'') as FollowupRemark,
 isnull(EE.ConsultationNotes,'') as ConsultationNotes,
 isnull(EE.ConsultationRemarks,'') as ConsultationRemarks,  
 EM2.FirstName + ' ' + isnull(EM2.LastName,'') as DoctorName, 
 isnull(EE.ConsultationTime,'') as ConsultationTime,    
 isnull(EE.ConsultationOutTime,'') as ConsultationOutTime,
  EJD.EmployeeLocationId as EmployeeLocationId, 
  ISNULL(PM.Title,'') as ProgramName
 from sWellness.tWellnessConsultation EE    
 left join sHrm.tEmployeeMaster EM on EE.ParticipantSourceId = EM.Id and EE.ParticipantSourceTypeId = 95
 LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.Id and MS.EmployeeSourceTypeId = 95
 LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
 left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId = EM.Id
 left join sHrm.tEmployeePersonalDetail EP on EE.ParticipantSourceId = EP.EmployeeId and EE.ParticipantSourceTypeId = 95
 left join sWellness.tWellnessVisitPurposeMaster C on C.Id = EE.CauseId
 left join sHrm.tEmployeePersonalDetail PD on EE.ParticipantSourceId = PD.EmployeeId and EE.ParticipantSourceTypeId = 95
 left join sWellness.tAppointment SA on EE.Id = SA.ReferSourceId     
 left join sHrm.tEmployeeMaster EM2 on EM2.Id = EE.DoctorEmployeeId
 left join sCommon.tGenderMaster G ON EP.GenderId = G.Id
 where EE.Id = @rConsultationId
 OPTION (RECOMPILE)    
  
 select AA.AssignedActivityId as Id, 
 AA.WellnessActivityCategoryId,WAC.Title as WellnessActivityCategoryName,
 AA.WellnessActivityId, WA.ActivityName as WellnessActivityName,
 ISNULL(AA.WellnessActivityTaskId,0) as WellnessActivityTaskId, 
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'') 
 ELSE ISNULL(WAT.[Name],'') END as WellnessActivityTask,
 ISNULL(AA.IsCustomActivityTask,0) as IsCustomActivityTask,
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 2 ELSE 1 END AS TypeId,
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS TypeName,
 ISNULL(AA.WellnessActivityCustom,'') as WellnessActivityCustomTask,
 ISNULL(AA.TargetValue, 0) as TargetValue, AA.UnitId, AA.FrequencyTypeId, AA.FrequencyCount,
 AA.WeekNo as WeekNoId,
 CASE AA.WeekNo WHEN 1 THEN 'Week 1' WHEN 2 THEN 'Week 2' WHEN 3 THEN 'Week 3' WHEN 4 THEN 'Week 4' END AS WeekName,
 CASE AA.UnitId WHEN 1 THEN 'Steps' WHEN 2 THEN 'Min' WHEN 3 THEN 'ML' WHEN 4 THEN 'Times' END AS UnitNo,
 CASE AA.FrequencyTypeId WHEN 1 THEN 'Daily' WHEN 2 THEN 'Weekly' END AS FrequencyType,
 CASE WHEN AA.WeekStart IS NULL THEN 'Assigned' WHEN GETDATE() < AA.WeekStart THEN 'Assigned'
			WHEN GETDATE() BETWEEN AA.WeekStart AND AA.WeekEnd THEN 'Active'
			WHEN GETDATE() > AA.WeekEnd THEN 'Expired' ELSE '-'
		END AS [Status]
 from sWellness.tAssignedActivity AA    
 INNER JOIN sWellness.tWellnessActivityCategoryMaster WAC on WAC.Id = AA.WellnessActivityCategoryId
 INNER JOIN sWellness.tWellnessActivityMaster WA on WA.ActivityId = AA.WellnessActivityId
 LEFT JOIN sWellness.tWellnessActivityTaskMaster WAT on WAT.Id = AA.WellnessActivityTaskId
 where AA.ConsultationId = @rConsultationId
 OPTION (RECOMPILE)

 SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off    
end
GO
PRINT N'Creating Procedure [sWellness].[pGetCompletedHealthIndexEmployeeList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetCompletedHealthIndexEmployeeList]
(
    @rMaINTypeId        INT,
    @rOrgId             INT,
    @rSetupGroupId      INT,
    @rSetupId           INT,
    @rStoreLocationId   INT,
    @rUserId            BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH CTE AS
    (
        SELECT
            E.Id AS EmployeeId,
			E.ParticipantSourceId AS SourceId,
            CASE 
                WHEN E.ParticipantSourceTypeId = 95 THEN ISNULL(EM.Code,'')
                WHEN E.ParticipantSourceTypeId = 1001 THEN ISNULL(EM1.Code,'')
                ELSE ISNULL(CS.Code,'')
            END AS EmployeeCode,

            CASE 
                WHEN E.ParticipantSourceTypeId = 95 
                    THEN ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'')
                WHEN E.ParticipantSourceTypeId = 1001 
                    THEN ISNULL(EFD.Name,'')
                ELSE 
                    ISNULL(CS.FirstName,'') + ' ' + ISNULL(CS.LastName,'')
            END AS EmployeeName,

            CASE 
                WHEN E.ParticipantSourceTypeId = 95 
                    THEN DATEDIFF(YEAR, EP.DateOfBirth, GETDATE())
                WHEN E.ParticipantSourceTypeId = 1001 
                    THEN DATEDIFF(YEAR, EFD.DateOfBirth, GETDATE())
                ELSE 
                    DATEDIFF(YEAR, CS.DateOfBirth, GETDATE())
            END AS Age

        FROM sExamination.tExamination E

        LEFT JOIN sHrm.tEmployeeMaster EM 
            ON E.ParticipantSourceId = EM.Id 
            AND E.ParticipantSourceTypeId = 95

        LEFT JOIN sHrm.tEmployeeFamilyDetails EFD 
            ON E.ParticipantSourceId = EFD.Id 
            AND E.ParticipantSourceTypeId = 1001

        LEFT JOIN sHrm.tCsrBenefiterMaster CS 
            ON E.ParticipantSourceId = CS.Id 
            AND E.ParticipantSourceTypeId = 1009

        LEFT JOIN sHrm.tEmployeeMaster EM1 
            ON EFD.EmployeeId = EM1.Id

        LEFT JOIN sHrm.tEmployeePersonalDetail EP 
            ON E.ParticipantSourceId = EP.EmployeeId

        INNER JOIN sExamination.tSetupMaster STP 
            ON E.SetupId = STP.Id

		INNER JOIN sExamination.tSubTypeMaster STM 
        ON STM.Id = STP.SubTypeId

        INNER JOIN sIp.tStoreLocationMaster SLM 
            ON SLM.Id = E.StoreLocationId

        INNER JOIN sSecurity.tUserLocation USR 
            ON USR.StoreLocationId = SLM.Id

        WHERE 
            STP.OrgId = @rOrgId
            AND E.ParticipantSourceTypeId = 95
            AND STP.IsObsolete = 0
            AND (STM.MainTypeId = @rMaINTypeId OR @rMaINTypeId = 0)
            AND STP.SetupGroupId = @rSetupGroupId
            AND E.StatusId = 4
            AND USR.UserId = @rUserId
            AND E.StoreLocationId = @rStoreLocationId
            AND STP.Id = @rSetupId

            -- IMPORTANT: Use EXISTS instead of JOIN
            AND EXISTS
            (
                SELECT 1 
                FROM sExamination.tHealthIndex HI
                WHERE HI.ExaminationId = E.Id
            )
    )

    SELECT 
        ROW_NUMBER() OVER (ORDER BY EmployeeId) AS SrNo,
		SourceId,
		EmployeeId,
        EmployeeCode,
        EmployeeName,
        Age
    FROM CTE
END
GO
PRINT N'Creating Procedure [sWellness].[pGetConsultationDetailsById]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetConsultationDetailsById]
@rConsultationId bigint
as
begin
	declare @lMainTypeId int,@lSetupId int,@lStoreLocationId int,@lRoundResult varchar(max)='',@lOrgId int,@lParticipantSourceId bigint
	
	select @lSetupId = SetupId,@lStoreLocationId = StoreLocationId,@lOrgId = OrgId,@lParticipantSourceId = ParticipantSourceId from sWellness.tWellnessConsultation where Id = @rConsultationId
	select @lMainTypeId = SubTypeId from sExamination.tSetupMaster where Id = @lSetupId

	select @lRoundResult = @lRoundResult + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
		from sExamination.tSetupMaster where IsObsolete = 0 and IsClosed = 0
		and (SubTypeId = @lMainTypeId) and OrgId = @lOrgId
		and (StoreLocationId = @lStoreLocationId or @lStoreLocationId = 0)
			
	select M.Id as MainTypeId,
	E.SetupId,
	ParticipantCode = case E.ParticipantSourceTypeId when 95 then EM.Code when 1001 then EM2.Code else BM.Code end,
	E.DoctorEmployeeId,
	E.Id, E.Id as ConsultationId,
	GenderId = case E.ParticipantSourceTypeId when 95 then isnull(EP.GenderId,0) when 1001 then isnull(EFD.GenderId,0) else isnull(BM.GenderId,0) end,
	dateofbirth = case E.ParticipantSourceTypeId when 95 then convert(varchar,isnull(EP.DateOfBirth,''),103)
	when 1001 then convert(varchar,isnull(EFD.DateOfBirth,''),103) else convert(varchar,isnull(BM.DateOfBirth,''),103) end,
	Age = case E.ParticipantSourceTypeId when 95 then isnull(datediff(yy,EP.DateOfBirth,E.ConsultationDate),0)
	when 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0) else isnull(datediff(yy,BM.DateOfBirth,E.ConsultationDate),0) end,
	case when isnumeric(EC.MobileNumber) = 1 then isnull(EC.MobileNumber,'') else '' end as MobileNumber,
	case when isnull(CompanyEmail,'')<>'' then isnull(CompanyEmail,'') else isnull(personalEmail,'') end as CompanyEmail,
	convert(varchar,E.ConsultationDate,103) as ConsultationDate,
	ParticipantSourceId,
	ParticipantSourceTypeId,
	E.StatusId,
	M.Title as MainType,
	Name = case E.ParticipantSourceTypeId when 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'') when 1001 then EFD.Name
	else isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'') end,
	SM.Title as StatusName,
	@lRoundResult as RoundRes,
	EmployeeId = case E.ParticipantSourceTypeId when 95 then EM.Id when 1001 then EM2.Id else BM.Id end,
	EM5.FirstName + ' ' + isnull(EM5.LastName,'') as DoctorName,
	S.Title as SetupName,
	Isnull(EM.StatusId,0) as EmployeeStatusId
	from sWellness.tWellnessConsultation E	
	inner join sExamination.vExtSetupMaster S on S.Id = E.SetupId
	inner join sExamination.tMainTypeMaster M on S.MainTypeId = M.Id
	left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
	left join sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	left join sHrm.tEmployeeJobDetail JD on EM.Id = JD.EmployeeId
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId	
	left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
	left join sExamination.tStatusMaster SM	on E.StatusId = SM.Id
	left join sHrm.tEmployeeMaster EM5 on E.DoctorEmployeeId = EM5.Id
	where E.Id = @rConsultationId
			
end
GO
PRINT N'Creating Procedure [sWellness].[pGetEmployeeHealthIndex]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetEmployeeHealthIndex]
(
	@rEmployeeID BIGINT,
	@rBMI NUMERIC(10,2),
	@lBMIDate nvarchar(20), 		
    @rSystolicBP NUMERIC(10,0),
    @rDiastolicBP NUMERIC(10,0),
	@lBPDate nvarchar(20), 		
    @rHBA1C NUMERIC(10,2),
	@lHBA1CDate nvarchar(20), 	
    @rLDL NUMERIC(10,2),
	@lLDLDate nvarchar(20)
)
AS
BEGIN
		SET NOCOUNT ON;

		CREATE TABLE #TempParameterRange
		(
			StaticHIPId INT, ParameterName VARCHAR(100), MinimumRange NUMERIC(10,5), MaximumRange NUMERIC(10,5), Score SMALLINT, Category NVARCHAR(100), GenderId SMALLINT
		)

		INSERT INTO #TempParameterRange 
		SELECT 
			HIPM.StaticHealthIndexParameterId, HIPM.Title, HIPD.FromValue, HIPD.ToValue, HIPD.Points, HIPD.DiagnosisRemark,HIPD.GenderId
		FROM 
			[sExamination].[tHealthIndexParameterMaster] HIPM
		INNER JOIN
			[sExamination].[tHealthIndexParameterDetail] HIPD
		ON
			HIPD.HealthIndexParameterId = HIPM.Id
		WHERE 
			StaticHealthIndexParameterId IN (1,2,5,17,23)

		DECLARE @TotalRecord INT = 0;
		SET @TotalRecord = (SELECT COUNT(StaticHIPId) FROM #TempParameterRange)
		IF(@TotalRecord > 0)
		BEGIN
			UPDATE #TempParameterRange SET Score = CASE WHEN Score = 10 THEN 1 WHEN Score = 6 THEN 2 WHEN Score = 3 THEN 3 ELSE Score END WHERE Score IS NOT NULL  AND Score > 0;
		END


		DECLARE @DepartmentId INT, @GenderId SMALLINT,
				@BMICategory NVARCHAR(30) = NULL, @BMIScore SMALLINT,
				@HBA1CCategory NVARCHAR(30) = NULL, @HBA1CScore SMALLINT,
				@LDLCategory NVARCHAR(30) = NULL, @LDLScore SMALLINT,
				@SystolicCategory NVARCHAR(30) = NULL, @SystolicScore SMALLINT,
				@DiastolicCategory NVARCHAR(30) = NULL, @DiastolicScore SMALLINT,
				@BPCategory NVARCHAR(30) = NULL, @BPScore SMALLINT = NULL,
				@BiometricsCategory NVARCHAR(40)='',
				@BiometricsScore NUMERIC(10,5)=0,
				@StressCategory NVARCHAR(40)='',
				@StressScore SMALLINT=0,
				@LifestyleCategory NVARCHAR(40)='',
				@LifestyleScore SMALLINT=0,
				@SurveyCategory NVARCHAR(40)='',
				@MHICategory NVARCHAR(40)='',
				@SurveyDate VARCHAR(20)='';

		SET @GenderId = (SELECT TOP 1 GenderId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);

		IF(@rBMI IS NOT NULL AND @rBMI > 0 )
		BEGIN
			SELECT TOP 1 @BMICategory = Category, @BMIScore = Score FROM #TempParameterRange WHERE StaticHIPId = 1 AND @rBMI >= MinimumRange AND @rBMI <= MaximumRange AND GenderId = 1
		END

		-- HBA1C
		IF(@rHBA1C IS NOT NULL AND @rHBA1C > 0 )
		BEGIN
			SELECT TOP 1 @HBA1CCategory = Category, @HBA1CScore = Score FROM #TempParameterRange WHERE StaticHIPId = 2 AND @rHBA1C >= MinimumRange AND @rHBA1C <= MaximumRange AND GenderId = @GenderId
		END
		-- LDL
		IF(@rLDL IS NOT NULL AND @rLDL > 0 )
		BEGIN
			SELECT TOP 1 @LDLCategory = Category, @LDLScore = Score FROM #TempParameterRange WHERE StaticHIPId = 5 AND @rLDL >= MinimumRange AND @rLDL <= MaximumRange AND GenderId = @GenderId
		END

		-- Systolic
		IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 )
		BEGIN
			SELECT TOP 1 @SystolicCategory = Category, @SystolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 23 AND @rSystolicBP >= MinimumRange AND @rSystolicBP <= MaximumRange AND GenderId = @GenderId
		END

		-- Diastolic
		IF(@rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
		BEGIN
			SELECT TOP 1 @DiastolicCategory = Category, @DiastolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 17 AND @rDiastolicBP >= MinimumRange AND @rDiastolicBP <= MaximumRange AND GenderId = @GenderId
		END

		IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 AND @rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
		BEGIN
			SET @BPScore = CASE WHEN @SystolicScore > @DiastolicScore THEN @SystolicScore ELSE @DiastolicScore END
			SET @BPCategory = CASE @BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END
		END


		IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeID)
		BEGIN
			SELECT 
				@BiometricsCategory = BiometricsCategory, @BiometricsScore = Biometrics,
				@StressCategory = StressCategory , @StressScore = Stress,
				@LifestyleCategory = LifestyleCategory, @LifestyleScore = Lifestyle,
				@SurveyCategory = SurveyCategory,
				@MHICategory = MHICategory, 
				@SurveyDate = CONVERT(VARCHAR(20),UpdatedDatetime,103)
			FROM 
				[sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeID
		END

		DROP TABLE #TempParameterRange;


		CREATE TABLE #TempMHIScore
		(
			Id INT, ParameterName VARCHAR(100), Score VARCHAR(100), MHICategory NVARCHAR(20), ParameterType VARCHAR(5), SurveyDate VARCHAR(20)
		)

		INSERT INTO #TempMHIScore VALUES(1,'BMI',@rBMI, @BMICategory,'1', @lBMIDate);
		INSERT INTO #TempMHIScore VALUES(2,'HBA1C',@rHBA1C, @HBA1CCategory,'1', @lHBA1CDate);
		INSERT INTO #TempMHIScore VALUES(3,'LDL',@rLDL, @LDLCategory,'1', @lLDLDate);
		INSERT INTO #TempMHIScore VALUES(4,'BP',CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)), @BPCategory,'1', @lBPDate);
		INSERT INTO #TempMHIScore VALUES(5,'Biometrics',@BiometricsScore, @BiometricsCategory,'2', @SurveyDate);
		INSERT INTO #TempMHIScore VALUES(6,'Stress',@StressScore, @StressCategory,'2', @SurveyDate);
		INSERT INTO #TempMHIScore VALUES(7,'Lifestyle',@LifestyleScore, @LifestyleCategory,'2', @SurveyDate);
		INSERT INTO #TempMHIScore VALUES(8,'Survey','-', @SurveyCategory,'3', @SurveyDate);
		INSERT INTO #TempMHIScore VALUES(9,'MHI','-', @MHICategory,'3', @SurveyDate);


		SELECT * FROM #TempMHIScore

		DROP TABLE #TempMHIScore
END
GO
PRINT N'Creating Procedure [sWellness].[pGetEmployeeListCoach]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetEmployeeListCoach]
(@rOrgId INT,
@rLocationId INT)
AS

 SET NOCOUNT ON 

BEGIN

SELECT 
    SC.Id ,
    EM.EmployeeId ,
    EM.EmployeeName ,
	PM.Id AS ProgramId ,
    PM.Title AS ProgramName ,
	SC.MHICategory , 
	EM.Code AS EmployeeCode ,
	EM.DepartmentName , 
	LM.Title AS LocationName  
FROM 
    sWellness.tMHIScore SC
LEFT JOIN 
    sWellness.tProgramMaster PM ON PM.Id = SC.ProgramId
LEFT JOIN 
    [sHrm].[vExtEmployeeMaster] EM ON EM.EmployeeId= SC.EmployeeId
LEFT JOIN 
    sCommon.tLocationMaster LM ON LM.Id = EM.EmployeeLocationId
WHERE 
    SC.OrgId = @rOrgId
AND
    EM.EmployeeLocationId = @rLocationId ;

END
GO
PRINT N'Creating Procedure [sWellness].[PGetEmployeeMHIDetailDashboard]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[PGetEmployeeMHIDetailDashboard]
(
	@rEmpId bigint,
	@rOrgId int = 0
)
AS
BEGIN

	declare @lLatestVitalDisplayConfigVal varchar(5) = 'False';
      
	IF (@rOrgId > 0)
	BEGIN
		select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);
	END

	Declare @lHealthIndexScore decimal(10,2),@lOpdCount int,@lHeight int,@lWeight decimal(8,2),@lBMI decimal(8,2),@lBloodPressureSystolic int
	,@lBloodPressureDiastolic int,@lFBS nvarchar(10),@lHB nvarchar(10),@lchol nvarchar(10),@lTreatment nvarchar(500),@lPreviousOPDVisit nvarchar(max)
	,@lInjuryDate nvarchar(20),@lInjuryTime nvarchar(20),@lInjuryTreatment nvarchar(500),@lInjuryDiagnisis nvarchar(500),@lsurgery nvarchar(500)
	,@lLastExaminationId bigint,@lLastDiagnosis nvarchar(500),@lLastRecomendation nvarchar(500),@lLastExaminationdate nvarchar(20),
	@labnoramltest nvarchar(MAX),@lHealthAnalysis nvarchar(1000),@lRBS nvarchar(10),@lHBA1C nvarchar(10), @lHealthScoreDate nvarchar(20),
	@lBMIDate nvarchar(20), @lBPDate nvarchar(20), @lBloodSugarDate nvarchar(20), @lCholesterolDate nvarchar(20), @lHBDate nvarchar(20),
	@lMetabolicSyndrome bit, @lCVDMajorRisk bit, @lCVDMinorRisk bit, @lNCDsRisk bit,@lLDL nvarchar(10);

	Select @lHealthIndexScore = (select top 1 Convert(decimal(10,2),Round(Isnull(D.HealthIndex,0),2)) 
	from sExamination.tExamination E 
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
	Order by E.ExaminationDate desc)

	Select @lHealthScoreDate = (select top 1 convert(varchar(20),ExaminationDate,103)
	from sExamination.tExamination E
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
	Order by E.ExaminationDate desc)

	Select @lOpdCount = Count(E.id)
	from sExamination.tExamination E 
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
	and STM.MainTypeId=8

	Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103) -- mantis 27146, dt - 10/10/2023, Nidhi Pandey (remove Round() from weight)
	from sExamination.tExamination E 
	inner join sExamination.tVital V on V.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order by E.ExaminationDate desc

	Select Top 1 @lBloodPressureSystolic=BloodPressureSystolic,@lBloodPressureDiastolic=BloodPressureDiastolic,
	@lBPDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tExamination E 
	inner join sExamination.tVital V on V.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and Isnull(V.BloodPressureSystolic,0)>0 and Isnull(V.BloodPressureDiastolic,0)>0 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order by E.ExaminationDate desc

	Select Top 1 @lFBS=TRD.ServiceValue, @lBloodSugarDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
			inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
			inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 19 and  Isnull(TRD.ServiceValue,'')<>'' 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order By E.ExaminationDate desc

	Select Top 1 @lRBS=TRD.ServiceValue
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 21 and  Isnull(TRD.ServiceValue,'')<>''
	Order By E.ExaminationDate desc

	Select Top 1 @lHBA1C=TRD.ServiceValue
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 25 and  Isnull(TRD.ServiceValue,'')<>''
	Order By E.ExaminationDate desc

	---LDL-----
	Select Top 1 @lLDL=TRD.ServiceValue
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 34 and  Isnull(TRD.ServiceValue,'')<>''
	Order By E.ExaminationDate desc


	Select Top 1 @lHB=TRD.ServiceValue, @lHBDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
			inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
			inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 2 and  Isnull(TRD.ServiceValue,'')<>'' 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order By E.ExaminationDate desc

	Select Top 1 @lchol=TRD.ServiceValue, @lCholesterolDate=convert(varchar(20),ExaminationDate,103)
	from sExamination.tTestRequestDetail TRD
			inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id				
			inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id
			inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id
			inner join sExamination.tExamination E on TR.SourceId = E.Id
			inner join sExamination.tSetupMaster SM on SM.id=E.SetupId  -- mantis 27307, dt - 21/09/2023, Nidhi Pandey
			inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and TP.StaticTestParameterId = 31 and  Isnull(TRD.ServiceValue,'')<>'' 
	and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))
	Order By E.ExaminationDate desc

	Select  @lTreatment = COALESCE(@lTreatment,'') + Isnull(SIM.Title,'') + ','
	From sExamination.tExamination E
	LEFt join sExamination.tPrescription P on P.SourceId=E.id
	LEFt join sExamination.tPrescriptionDetail PD on PD.PrescriptionId=p.id
	Left join sIp.tStockItemMaster SIM on SIM.id=PD.StockItemId
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=8
	and E.id in(Select Top 1 E.ID from sExamination.tExamination E inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95 and STM.MainTypeId=8
	AND IsNULL(E.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
	Order By E.ExaminationDate desc)
	Order By E.ExaminationDate desc

	print @lTreatment
	SET @lTreatment = Replace(LEFT(@lTreatment, LEN(@lTreatment) - 1),',','</br>')
	print @lTreatment

	select Top 1 @lPreviousOPDVisit = '<p class="color_black" style=""><span class="inner_content_left" style="">Date & Time :</span><span class="inner_content_right" style="">
	'+convert(varchar(20),C.ConsultationDate,103)+' '+replace(replace(Right(convert(varchar(20),C.CreatedDateTime,100),7),'AM',' AM'),'PM',' PM')+'</span></p>
	<p class="color_black" style=""><span class="inner_content_left" style="">Visit Purpose :</span><span class="inner_content_right" style="">'+ WVPM.Title +'</span></p>
	'+ '' +'</span></p>'
	from sWellness.tWellnessConsultation C 
	inner join sExamination.tSetupMaster SM on SM.id=C.SetupId
	inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	inner join sWellness.tWellnessVisitPurposeMaster WVPM on WVPM.Id=C.CauseId
	Where C.ParticipantSourceId=@rEmpId and C.ParticipantSourceTypeId=95
	and STM.MainTypeId=17
	AND IsNULL(C.IsCancel,0) = 0 
	Order By C.Id desc

	select Top 1 @lInjuryDate=Convert(varchar(20),IA.IncidentDate,104),@lInjuryTime=IncidentTime,@lInjuryDiagnisis=Isnull(IncidentRemark,''),@lInjuryTreatment=Isnull(TreatmentRemark,'')
	From sIncident.tAccident IA
	Inner JOIN sExamination.tExamination EE ON IA.ExaminationId=EE.Id 
	Where EE.ParticipantSourceId=@rEmpId and EE.ParticipantSourceTypeId=95
	Order by EE.ExaminationDate Desc

	select @lsurgery= case when Isnull(IsSurgeryDone,0)= 1 then 'Yes' else 'No' end + '-' + Isnull(H.SurgeryRemark,'')
	from sExamination.tHistory H
	where H.ParticipantSourceId =@rEmpId and H.Isobsolete=0

	select Top 1 @lLastExaminationId=E.Id,@lLastExaminationdate=convert(varchar(20),ExaminationDate,104),@lLastDiagnosis=Isnull(DiagnosisRemark,'')
	,@lLastRecomendation=Isnull(RecommendationEnglish,'')
	from sExamination.tExamination E 
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1
	Order by E.ExaminationDate desc

	select @labnoramltest = COALESCE(@labnoramltest,'') + TPM.Title + '- ' + TRD.ServiceValue + ' ,'
	FROM sExamination.tTestRequest TR	
		INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id AND isnull(TR.IsObsolete,0) = 0
		INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id and TR.TestId = TD.TestId
		INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
	where TR.SourceId=@lLastExaminationId and Isnull(TRD.IsAbnormal,0)<>0

	SET @labnoramltest = Replace(LEFT(@labnoramltest, LEN(@labnoramltest) - 1),',','</br>')
	print @lLastExaminationId

	DECLARE @HabitName VARCHAR(1000)
	(SELECT @HabitName = COALESCE(@HabitName,'') + ISNULL(H.Title,'')
	+ '-' + Convert(varchar(10),ISNULL(HHD.Duration,'')) + ' ' + ISNULL(DUM.Title,'') + ', ' 
	FROM sExamination.tHabitHygineDetail HHD 
	INNER JOIN sExamination.tHabitHygine HH ON HH.Id = HHD.HabitHygineId 
	INNER JOIN sExamination.tHabitTypeMaster H ON HHD.HabitId = H.Id
	LEft Join sCommon.tDurationUnitMaster DUM on DUM.id=HHD.DurationUnitId
	WHERE HH.SourceId = @lLastExaminationId AND HH.Isobsolete=0
	)
	  SET @HabitName = Replace(Replace(LEFT(@HabitName, LEN(@HabitName) - 1),',','</br>'),'0','')

	declare @lConfValue int
			select @lConfValue = ISNULL(CS.ItemValue,CM.ItemValue)
			from sConfig.tConfigurationMaster as CM
			LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
			where CM.ItemKey = 'FirstAid.SetTrainingRenewal'

	SELECT @lHealthAnalysis = COALESCE(@lHealthAnalysis,'') + HIM.Title + ' - '		
			+ Convert(varchar(100),CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints))))) + ' - '
			+ (SELECT (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints)))) AND CONVERT(DECIMAL(18,2),((SUM(CONVERT(DECIMAL(18,2),HI

	.EarnedPoints))* 100) /SUM(CONVERT(DECIMAL(18,2),HI.TotalPoints))))>RangeFrom)
			+ ' ,'
		FROM sExamination.tExamination AS EXM
		INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID=EXM.SetupId
		INNER JOIN sExamination.tSubTypeMaster SSM ON SSM.Id = STM.SubTypeId 
		INNER JOIN sExamination.tHealthIndex AS  HI ON HI.ExaminationId=EXM.Id  
		INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIM ON HIM.ID=HI.HealthIndexParameterId
	WHERE EXM.ParticipantSourceTypeId=95 
		AND  HI.TotalPoints > 0
		AND EXM.Id=@lLastExaminationId
		AND  SSM.MainTypeId=1 
	GROUP BY HI.HealthIndexParameterId,HIM.Title
		ORDER BY HI.HealthIndexParameterId

	SET @lHealthAnalysis = Replace(LEFT(@lHealthAnalysis, LEN(@lHealthAnalysis) - 1),',','</br>')

	DECLARE @HealthHeader varchar(max) = '',@HealthDetail varchar(max) = ''
	SELECT @HealthHeader = '<tbody><tr><th>Date</th><th>HealthScore</th><tr>'

	Select @HealthDetail = @HealthDetail + '<tr><td>'+ convert(varchar(20),E.ExaminationDate,104)+ '</td><td>' + Convert(varchar(10),Convert(decimal(10,2),Round((Isnull(D.HealthIndex,0)),2))) + '</td></tr>'
	from sExamination.tExamination E 
	inner join sExamination.tDiagnosis D on D.SourceId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0

	--select @HealthHeader + @HealthDetail
	print @HealthHeader + @HealthDetail + '</tbody>'

	Select TOP 1 @lMetabolicSyndrome = ISNULL(DTE.MetabolicSyndrome, 0), @lCVDMajorRisk = ISNULL(DTE.CVDMajorRisk, 0), 
				 @lCVDMinorRisk = ISNULL(DTE.CVDMinorRisk, 0), @lNCDsRisk = ISNULL(DTE.NCDsRisk, 0)
	from sExamination.tExamination E
	inner join sExamination.tDiagnosisTrackerEmployee DTE on DTE.ExaminationId=E.Id
	inner join sExamination.tSetupMaster SM on SM.id=E.SetupId
	inner join SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1
	Order by E.ExaminationDate desc

	Select EM.Id AS EmployeeId,
		'Emp ID : ' + EM.Code as Code,	
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
		convert(varchar(20),(DATEDIFF(yy,EPD.DateOfBirth,GETDATE()))) + ' Years ' + ' ' + Isnull(GM.Title,'') AS Years,
		Isnull(BGM.Title,'') as BloodGroup,
		'Working Since Last ' + Convert(varchar(20),(DATEDIFF(yy,EJD.DateOfJoining,GETDATE()))) + ' Years ' as WorkingSince,
		'Dept: ' + ISNULL(ODM.Title,'') AS DepartmentName,
		'Emp Type : ' + Isnull(ETM.Title,'') as EmployeeType,
		'' as allergies,
		'Reporting Mgr : ' + ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') ReportingMangerName,
		ISNULL(EC.CompanyEmail,'') AS EmailId,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		isnull(EC.PresentStreetOne,'') as Add1,
		isnull(EC.PresentStreetTwo,'') as Add2,
		isnull(EC.PresentStreetThree,'') + ','+isnull(EC.PresentCity,'')+','+isnull(EC.PresentState,'') as Add3,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		--isnull(EI.EmployeePhoto,0) as EmployeePhoto
		(SELECT TOP 1 CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) as EmployeePhoto,
		Isnull(@lHealthIndexScore,0) as HEALTHSCORE,
		Isnull(@lOpdCount,0) as OpdCount,
		'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,
		'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,
		Isnull(@lHeight,0) as Height1,
		Isnull(@lWeight,0) as Weight1,
		Isnull(@lBMI,0) as BMI,
		convert(varchar(10),@lBloodPressureSystolic) + '/' + Convert(varchar(10),@lBloodPressureDiastolic) as BP,
		Isnull(@lFBS,'0') as BloodSugar,
		Isnull(@lHB,'0') + ' g/dl' as Haemoglobin,
		Isnull(@lchol,'0') as Cholesterol,
		@lPreviousOPDVisit as PreviousOPDVisit,
		Replace([sExamination].[fFamilyHistoryWithRelationGet](@rEmpId),'-','- ') as FamilyHistory,
		Replace([sExamination].[fHistoryGet_new](@rEmpId),'-',' ') as History,
		@lInjuryDate as InjuryDate,
		@lInjuryTime as InjuryTime,
		@lInjuryDiagnisis as InjuryDiagnisis,
		@lInjuryTreatment as InjuryTreatment,
		@lsurgery as surgery,
		@lLastExaminationdate as LastExaminationdate,
		@lLastDiagnosis as LastDiagnosis,
		@lLastRecomendation as LastRecomendation,
		[sExamination].[fExistingDiseaseWithDurationUnitGet](@lLastExaminationId) as ExistingDisease,
		@labnoramltest as AbnormalTest,
		@HabitName as Habits,
		Isnull(P.Remark,'') as Allergy,
		convert(varchar(20),isnull(EPD.FirstAidTrainingDate,''),104) as FirstAidTrainingDate,
		convert(varchar(20),DATEADD(d,@lConfValue, EPD.FirstAidTrainingDate),104) as NextTraningDate,
		LM.Title as Location,
		@lHealthAnalysis as HealthAnalysis,
		@HealthHeader + @HealthDetail + '</tbody>' as healthdata,
		Isnull(@lRBS,'0') as RBS,
		Isnull(@lHBA1C,'0') as HBA1C,
		Isnull(@lLDL,'0') as LDL,
		@lHealthScoreDate as HealthScoreDate,
		@lBMIDate as BMIDate,
		@lBPDate as BPDate,
		@lBloodSugarDate as BloodSugarDate,
		@lCholesterolDate as CholesterolDate,
		@lHBDate as HBDate,
		@lMetabolicSyndrome as MetabolicSyndrome, @lCVDMajorRisk as CVDMajorRisk, 
		@lCVDMinorRisk as CVDMinorRisk, @lNCDsRisk as NCDsRisk
	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
		INNER JOIN sCommon.tLocationMaster LM on LM.ID = EJD.EmployeeLocationId
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
		LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id = EJD.EmployeeJobTitleId
		Left JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		Left JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EPD.BloodGroupId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM	ON EJD.OrganizationDepartmentId = ODM.Id
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id=EJD.EmployeeTypeId
		LEFT JOIN Shrm.temployeemaster EM1 on EM1.Id=EJD.ReportingMangerEmployeeId
		left join sHrm.tEmployeeImages EI on EI.EmployeeId=EM.id
		left join sExamination.tPrompt P on P.ParticipantId	=EM.id and P.ParticipantSourceTypeId=95
	Where EM.Id=@rEmpId
END
GO
PRINT N'Creating Procedure [sWellness].[pGetMHIScoreUpdation]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetMHIScoreUpdation]
	@rId Int
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		
	if exists (select 1 from [sWellness].[tMHIScoreUpdation]  where Id = @rId)
	begin	

			Select 
			mhi.Id,
			mhi.ParticipantSourceTypeId,
			mhi.ParticipantSourceId,
			BMI,
			HBA1C,
			LDL,
			BPSystolic,
			BPDiastolic,
			Stress,
			LifeStyle,
			ED.Code as EmployeeCode,
			ED.EmployeeName
			FROM [sWellness].[tMHIScoreUpdation] mhi
			INNER JOIN 
			[sHrm].[vEmployeeDetail] ED on mhi.ParticipantSourceId = ED.EmployeeId
			Where mhi.Id=@rId	
			ORDER BY mhi.Id DESC 
	end
	else
	begin
		select -101 as Result
	end
END
GO
PRINT N'Creating Procedure [sWellness].[pGetMHIScoreUpdationList]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetMHIScoreUpdationList]
AS

BEGIN		
			Select 
			mhi.Id,
			mhi.ParticipantSourceTypeId,
			mhi.ParticipantSourceId,
			BMI,
			HBA1C,
			LDL,
			BPSystolic,
			BPDiastolic,
			Stress,
			LifeStyle,
			ED.Code as EmployeeCode,
			ED.EmployeeName
			FROM [sWellness].[tMHIScoreUpdation] mhi
			INNER JOIN 
			[sHrm].[vEmployeeDetail] ED on mhi.ParticipantSourceId = ED.EmployeeId
			ORDER BY mhi.Id DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pGetMySurveylist]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetMySurveylist]--9999,999900147,9999000151595,999900255
	@rOrgId SMALLINT,
	@rLocationId BIGINT,
	@rEmployeeId BIGINT,
	@rAssignSurveyId INT = 0
AS
SET NOCOUNT ON
BEGIN
 
BEGIN TRY
	
	DECLARE @Age int=0

	SELECT @Age=CONVERT(int,ROUND(DATEDIFF(hour,ECS.DateOfBirth,sCommon.fGetDate())/8766.0,0)) from sHrm.vEmployeeCustomSearch ECS where ECS.EmployeeId=@rEmployeeId

	SELECT DISTINCT
		ASM.Id as AssignSurveyId,
		ASM.Title as Title,
		CASE WHEN HSRM.StatusId=554 THEN 'Completed' ELSE 'Pending' END AS Status,
		DATEDIFF(day, sCommon.fGetDate(), ASM.ToDate) AS RemainingDays,
		CONVERT(VARCHAR,COUNT(DISTINCT HSRD.Id))+'/'+CONVERT(VARCHAR,COUNT(DISTINCT HSPD.HealthSurveyParameterId)) AS Questions,
		CASE WHEN ASM.ToDate<sCommon.fGetDate() THEN 0 ELSE 1 END AS IsOpen,
		CASE WHEN HSRM.StatusId=554 THEN 0 ELSE ISNULL(HSRM.Id,0) END AS SurveyResponseId
	FROM sSupport.tAssignSurveyMaster ASM
	INNER JOIN sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId
	INNER JOIN sSupport.tHealthSurveyMaster HSM on HSM.Id=ASM.HealthSurveyId
	INNER JOIN sSupport.tHealthSurveyParameterMaster HSPM on HSM.Id=HSPM.HealthSurveyId
	LEFT JOIN sSupport.tHealthSurveyParameterDetail HSPD on HSPD.HealthSurveyParameterId=HSPM.Id and (HSPD.FromAge<=@Age and @Age<=HSPD.ToAge)
	LEFT JOIN sHrm.vEmployeeCustomSearch ECS on ASD.SourceId=ECS.EmployeeId and (ECS.GenderId=HSPD.GenderId or isnull(HSPD.GenderId,0)=0) 
	LEFT JOIN sSupport.tHealthSurveyResponseMaster HSRM on ASM.Id=HSRM.AssignSurveyId and ASD.SourceId=HSRM.SourceId
	LEFT JOIN sSupport.tHealthSurveyResponseDetail HSRD on  HSRD.SurveyResponseId=HSRM.Id and HSRD.QuestionId=HSPM.Id
	WHERE 
		ASM.OrgId=@rOrgId 
--	AND 
	--	(ASM.Id = @rAssignSurveyId OR @rAssignSurveyId = 0)
	AND 
		ASD.SourceId = @rEmployeeId
	--AND 
		-- ASM.Id IN (Select DISTINCT AssignSurveyId From sWellness.tProgramMaster PM
		--						JOIN sWellness.tProgramLocation PL ON PM.Id = PL.ProgramId
		--						Where PL.LocationId = @rLocationId AND PM.IsSurveyRequired = 1)
	 AND 
		HSPM.HealthSurveyAnsTypeId != 5
	 GROUP BY ASM.Id,
			  ASM.Title,
			  HSRM.StatusId,
			  DATEDIFF(day, sCommon.fGetDate(), ASM.ToDate),
			  ASM.ToDate,
			  HSRM.Id

END TRY
BEGIN CATCH 
  --select '' as Result
END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pGetNonAdherenceEmpList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetNonAdherenceEmpList]
(
	@rOrgId INT,
	@rLocationId INT
)
AS
SET NOCOUNT ON 
BEGIN

	SELECT 
		SC.Id ,
		EM.EmployeeId ,
		EM.Code as EmployeeCode,
		EM.EmployeeName ,
		PM.Id AS ProgramId ,
		ISNULL(PM.Title, 'Not Assigned') AS ProgramName,
		SC.MHICategory , 
		LM.Title AS LocationName,
		EM.DepartmentName,
		CASE WHEN (SC.Biometrics IS NULL OR SC.Biometrics <= 0) AND SC.SurveyCategory IS NOT NULL THEN 'Biometrics Pending'
		WHEN SC.SurveyCategory IS NULL AND SC.Biometrics IS NOT NULL THEN 'Survey Pending'
		WHEN SC.SurveyCategory IS NULL AND SC.Biometrics IS  NULL THEN 'Both Pending'
		WHEN SC.SurveyCategory IS NOT NULL AND SC.Biometrics IS NOT NULL  AND SC.MHICategory IS NULL THEN 'MHI Pending'
		ELSE ''
		END AS Status
	FROM 
		sWellness.tMHIScore SC
	LEFT JOIN 
		sWellness.tProgramMaster PM ON PM.Id = SC.ProgramId
	INNER JOIN 
		[sHrm].[vExtEmployeeMaster] EM ON EM.EmployeeId= SC.EmployeeId
	LEFT JOIN 
		sCommon.tLocationMaster LM ON LM.Id = EM.EmployeeLocationId
	WHERE 
		SC.OrgId = @rOrgId
	AND
	    EM.EmployeeLocationId = @rLocationId
	AND
		(SC.BiometricsCategory IS NULL OR SC.SurveyCategory IS NULL OR SC.MHICategory IS NULL )
END
GO
PRINT N'Creating Procedure [sWellness].[pGetNonAdherenceTaskList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetNonAdherenceTaskList]
(
	@rLocationId INT
)
AS
SET NOCOUNT ON 
BEGIN
DECLARE @Today DATE = CAST(sCommon.fGetDate() AS DATE);
	SELECT 
		EM.EmployeeId,
		EM.EmployeeName,
		LM.Title AS LocationName,
		EM.DepartmentName,
		EM.Code as EmployeeCode,
		AA.CreatedDateTime as AssignedDate,
		ISNULL(PM.Title, 'Not Assigned') AS ProgramName,
		CASE 
    WHEN AA.WeekNo IS NULL THEN '-' 
    ELSE 'Week ' + CAST(AA.WeekNo AS VARCHAR(10)) 
END AS WeekNo,
WATM.Name as TaskName,
	    CAST(DAY(AA.EndDate) AS VARCHAR) +
    CASE 
        WHEN DAY(AA.EndDate) IN (1,21,31) THEN 'st'
        WHEN DAY(AA.EndDate) IN (2,22) THEN 'nd'
        WHEN DAY(AA.EndDate) IN (3,23) THEN 'rd'
        ELSE 'th'
    END
    + ' ' + FORMAT(AA.EndDate, 'MMM') AS EndDate
	FROM 
		sWellness.tAssignedActivity AA
	INNER JOIN 
		[sHrm].[vExtEmployeeMaster] EM ON EM.EmployeeId= AA.EmployeeId
	LEFT JOIN 
		sCommon.tLocationMaster LM ON LM.Id = EM.EmployeeLocationId
LEFT JOIN [sWellness].[tMHIScore] MH
    ON AA.EmployeeId = MH.EmployeeId
LEFT JOIN [sWellness].[tProgramMaster] PM
    ON MH.ProgramId = PM.Id
LEFT JOIN [sWellness].[tWellnessActivityTaskMaster] WATM
   ON WATM.Id = AA.WellnessActivityTaskId
	   
	WHERE 
	    EM.EmployeeLocationId = @rLocationId
	AND
		AA.EndDate <= DATEADD(DAY,1,@Today)
	AND 
	    Status = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramAdherenceData]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramAdherenceData] 
(
    @rEmployeeId BIGINT,
    @rWeekStart  DATE
)
AS
BEGIN

SET NOCOUNT ON;

--;WITH DateSeries AS
--(
--    SELECT DATEADD(DAY, v.n, @rWeekStart) AS TaskDate
--    FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) v(n)
--),
--TaskList AS
--(
--    SELECT 
--        aa.AssignedActivityId,
--        t.Name AS TaskName
--    FROM sWellness.tAssignedActivity aa
--    INNER JOIN sWellness.tWellnessActivityTaskMaster t
--        ON aa.WellnessActivityTaskId = t.Id
--    WHERE aa.EmployeeId = @rEmployeeId
--      AND aa.WeekStart = @rWeekStart
--)

--SELECT
--    tl.TaskName,
--    ds.TaskDate,
--    CASE
--        WHEN at.Status IS NOT NULL THEN at.Status
--        WHEN ds.TaskDate < CAST(GETDATE() AS DATE) THEN 2
--        ELSE 0
--    END AS Status
--FROM TaskList tl

--CROSS JOIN DateSeries ds

--LEFT JOIN sWellness.tEmployeeTaskTrack at
--    ON at.AssignedActivityId = tl.AssignedActivityId
--    AND at.TaskDate = ds.TaskDate

--ORDER BY tl.TaskName, ds.TaskDate
DECLARE @cols NVARCHAR(MAX)
DECLARE @sql  NVARCHAR(MAX)


;WITH N AS
(
    SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 
    UNION ALL SELECT 3 UNION ALL SELECT 4 
    UNION ALL SELECT 5 UNION ALL SELECT 6
)
SELECT @cols = STRING_AGG(
        QUOTENAME(
            CONVERT(VARCHAR(10), DATEADD(DAY,n,@rWeekStart), 23)
        )
    , ',')
FROM N


SET @sql = '
;WITH DateSeries AS
(
    SELECT 
        DATEADD(DAY, v.n, ''' + CONVERT(VARCHAR(10),@rWeekStart,120) + ''') AS TaskDate,
        CONVERT(VARCHAR(10), DATEADD(DAY, v.n, ''' + CONVERT(VARCHAR(10),@rWeekStart,120) + '''), 23) AS ColumnName
    FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) v(n)
),
BaseData AS
(
    SELECT 
        CASE WHEN aa.IsCustomActivityTask = 1 THEN aa.WellnessActivityCustom
		WHEN aa.IsCustomActivityTask = 0 THEN t.Name
		ELSE t.Name END as TaskName,
        ds.ColumnName,
        CASE 
            WHEN at.Status IS NOT NULL THEN at.Status
            WHEN ds.TaskDate < CAST(GETDATE() AS DATE) THEN 2
            ELSE 0
        END AS FinalStatus
    FROM sWellness.tAssignedActivity aa
    LEFT JOIN sWellness.tWellnessActivityTaskMaster t
        ON aa.WellnessActivityTaskId = t.Id
    CROSS JOIN DateSeries ds
    LEFT JOIN sWellness.tEmployeeTaskTrack at
        ON at.AssignedActivityId = aa.AssignedActivityId
        AND at.TaskDate = ds.TaskDate
    WHERE aa.EmployeeId = ' + CAST(@rEmployeeId AS VARCHAR) + '
      AND aa.WeekStart = ''' + CONVERT(VARCHAR(10),@rWeekStart,120) + '''
)
SELECT *
FROM BaseData
PIVOT
(
    MAX(FinalStatus)
    FOR ColumnName IN (' + @cols + ')
) p
ORDER BY TaskName;
'


EXEC(@sql)

END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramDashboardDetails]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramDashboardDetails]
(
    @rProgramId INT,
	@rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

SELECT 
    LM.Title AS LocationName,

    COUNT(DISTINCT EJD.EmployeeId) AS TotalEmployee,

    COUNT(DISTINCT PP.Id) AS RegisteredEmployee,

    COUNT(DISTINCT CASE 
        WHEN PA.ProgramParticipantId IS NOT NULL THEN PP.Id 
    END) AS AttendedEmployee

FROM 
    sWellness.tProgramParticipant PP

LEFT JOIN 
    sWellness.tProgramAttendance PA 
        ON PA.ProgramParticipantId = PP.Id 
        AND PA.ProgramId = PP.ProgramId

LEFT JOIN 
    sCommon.tLocationMaster LM 
        ON LM.Id = PP.ParticipantLocationId

INNER JOIN 
    sHrm.tEmployeeJobDetail EJD
	ON PP.ParticipantLocationId = EJD.EmployeeLocationId
     

WHERE 
    PP.ProgramId = @rProgramId

GROUP BY 
    LM.Title

ORDER BY 
    LM.Title


SELECT 
    pp.AutoID, 
    pp.OrgId,
    pp.ProgramId, 
    pp.ParameterTypeId,
    'General' AS ParameterType,
    pp.ParameterSourceTypeId,
    pp.ParameterSourceId, 
    GTP.Title AS ParameterName,
    ISNULL(GTP.StaticGeneralTemplateParameterId, 0) AS StaticParameterSourceId, 
    pp.OrderIndex,

    AVG(CASE 
            WHEN PPT.InputId = 1 
            THEN TRY_CAST(PPT.ProgramParameterValue AS DECIMAL(18,2))
        END) AS FirstValue,

    AVG(CASE 
            WHEN PPT.InputId = 3 
            THEN TRY_CAST(PPT.ProgramParameterValue AS DECIMAL(18,2))
        END) AS LastValue

FROM [sWellness].[tProgramParameter] pp

LEFT JOIN [sWellness].[tProgramParameterTrack] PPT 
       ON pp.AutoID = PPT.ProgramParameterId

INNER JOIN [sExamination].[tGeneralTemplateParameter] GTP 
       ON pp.ParameterSourceId = GTP.Id

WHERE pp.ParameterTypeId = 2 
  AND pp.ProgramId = @rProgramId 
  AND pp.OrgId = @rOrgId

GROUP BY
    pp.AutoID, 
    pp.OrgId, 
    pp.ProgramId, 
    pp.ParameterTypeId,
    pp.ParameterSourceTypeId,
    pp.ParameterSourceId,
    GTP.Title,
    GTP.StaticGeneralTemplateParameterId,
    pp.OrderIndex

UNION ALL

SELECT 
    pp.AutoID, 
    pp.OrgId, 
    pp.ProgramId, 
    pp.ParameterTypeId,
    'Test' AS ParameterType,
    pp.ParameterSourceTypeId,
    pp.ParameterSourceId,
    TPM.Title AS ParameterName,
    ISNULL(TPM.StaticTestParameterId, 0) AS StaticParameterSourceId, 
    pp.OrderIndex,

    AVG(CASE 
            WHEN PPT.InputId = 1 
            THEN TRY_CAST(PPT.ProgramParameterValue AS DECIMAL(18,2))
        END) AS FirstValue,

    AVG(CASE 
            WHEN PPT.InputId = 3 
            THEN TRY_CAST(PPT.ProgramParameterValue AS DECIMAL(18,2))
        END) AS LastValue

FROM [sWellness].[tProgramParameter] pp

LEFT JOIN [sWellness].[tProgramParameterTrack] PPT 
       ON pp.AutoID = PPT.ProgramParameterId

INNER JOIN sOrderEntry.tTestParameterMaster TPM 
       ON pp.ParameterSourceId = TPM.Id

WHERE pp.ParameterTypeId = 3 
  AND pp.ProgramId = @rProgramId 
  AND pp.OrgId = @rOrgId

GROUP BY
    pp.AutoID, 
    pp.OrgId, 
    pp.ProgramId, 
    pp.ParameterTypeId,
    pp.ParameterSourceTypeId,
    pp.ParameterSourceId,
    TPM.Title,
    TPM.StaticTestParameterId,
    pp.OrderIndex;

END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramDocument]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramDocument]
(
	@rDocId INT,
	@rConfigId INT
)
AS
BEGIN
	SELECT 
		PD.FileName,
		PD.ProgramId,
		PD.CreatedUserId AS UserId
	FROM 
		[sWellness].[tProgramDocument] PD
	where 
		Id = @rDocId
	AND 
		PD.ConfigurationTypeId = @rConfigId
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramEffectiveness]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramEffectiveness] 
(
    @rProgramId INT,
	@rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

WITH ParticipantValues AS
(
  SELECT 
    PPT.ProgramParameterId,
	PPT.ProgramParticipantId,
    GTP.Title AS ParameterName,

        MAX(CASE 
                WHEN InputId = 1 
                THEN TRY_CAST(ProgramParameterValue AS DECIMAL(18,2)) 
            END) AS FirstValue,

        MAX(CASE 
                WHEN InputId = 3 
                THEN TRY_CAST(ProgramParameterValue AS DECIMAL(18,2)) 
            END) AS LastValue

FROM [sWellness].[tProgramParameter] pp

LEFT JOIN [sWellness].[tProgramParameterTrack] PPT 
       ON pp.AutoID = PPT.ProgramParameterId

INNER JOIN [sExamination].[tGeneralTemplateParameter] GTP 
       ON pp.ParameterSourceId = GTP.Id

WHERE pp.ParameterTypeId = 2 
  AND pp.ProgramId = @rProgramId 
  AND pp.OrgId = @rOrgId

GROUP BY
PPT.ProgramParameterId,
PPT.ProgramParticipantId,
GTP.Title

UNION ALL

SELECT 
    PPT.ProgramParameterId,
	PPT.ProgramParticipantId,
    TPM.Title AS ParameterName,

    AVG(CASE 
            WHEN PPT.InputId = 1 
            THEN TRY_CAST(PPT.ProgramParameterValue AS DECIMAL(18,2))
        END) AS FirstValue,

    AVG(CASE 
            WHEN PPT.InputId = 3 
            THEN TRY_CAST(PPT.ProgramParameterValue AS DECIMAL(18,2))
        END) AS LastValue

FROM [sWellness].[tProgramParameter] pp

LEFT JOIN [sWellness].[tProgramParameterTrack] PPT 
       ON pp.AutoID = PPT.ProgramParameterId

INNER JOIN sOrderEntry.tTestParameterMaster TPM 
       ON pp.ParameterSourceId = TPM.Id

WHERE pp.ParameterTypeId = 3 
  AND pp.ProgramId = @rProgramId 
  AND pp.OrgId = @rOrgId

GROUP BY
PPT.ProgramParameterId,
PPT.ProgramParticipantId,
TPM.Title


),

ParameterEfficiency AS
(
    SELECT
        ProgramParameterId,
		ParameterName,
        COUNT(*) AS TotalParticipants,

        SUM(CASE 
                WHEN LastValue < FirstValue   -- Decrease = Improvement
                THEN 1 
                ELSE 0 
            END) AS ImprovedParticipants,

        CAST(
            (SUM(CASE 
                    WHEN LastValue < FirstValue THEN 1 ELSE 0 
                 END) * 100.0)
            / NULLIF(COUNT(*), 0)
            AS DECIMAL(5,2)
        ) AS EfficiencyPercentage

    FROM ParticipantValues
    WHERE FirstValue IS NOT NULL
      AND LastValue IS NOT NULL
    GROUP BY ProgramParameterId,ParameterName
)

-- 🔹 Final Output
SELECT 
    ProgramParameterId,
	ParameterName,
    TotalParticipants as RegisteredParticipants,
    ImprovedParticipants,
    EfficiencyPercentage,
	(SELECT Title from [sWellness].[tProgramMaster] where Id = @rProgramId) as ProgramName,
    -- Overall Program Effectiveness (same value repeated per row)
    CAST(
        AVG(EfficiencyPercentage) OVER ()
        AS DECIMAL(5,2)
    ) AS OverallProgramEffectiveness

FROM ParameterEfficiency;


END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramParticipantList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramParticipantList]
(
    @rProgramId INT
)
AS
SET NOCOUNT ON
BEGIN
SELECT 
	     PP.Id AS ProgramParticipantId,
         PP.ParticipantCode,
         PP.ParticipantName,
         DM.Title AS DepartmentName
     FROM 
         [sWellness].[tProgramParticipant] PP
     LEFT JOIN 
         sCommon.tOrganizationDepartmentMaster DM ON DM.Id = PP.ParticipantDepartmentId
	WHERE 
         PP.ProgramId = @rProgramId
	ORDER BY 
         PP.ParticipantName;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetWellnessActivityDropdownList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessActivityDropdownList]
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		ActivityId AS Id,
        ActivityName AS Title
    FROM 
		[sWellness].[tWellnessActivityMaster] 
	WHERE 
		IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pGetWellnessActivityTaskMasterById]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessActivityTaskMasterById]
	@rId INT = 0
AS
BEGIN		
		SELECT [Id]
			  ,WATM.[ActivityId] AS ActivityId
			  ,WAM.ActivityName AS ActivityName
			  ,WATM.Name as TaskName
			  ,[TargetValue]
			  ,WAM.DefaultUnitId AS UnitId
			  ,CASE WHEN WAM.DefaultUnitId = 1 THEN 'Steps' 
					WHEN WAM.DefaultUnitId = 2 THEN 'Min' 
					WHEN WAM.DefaultUnitId = 3 THEN 'ML'
					WHEN WAM.DefaultUnitId = 4 THEN 'Times' 
				END AS UnitName
			  ,[FrequencyTypeId]
			  ,CASE WHEN [FrequencyTypeId] = 1 THEN 'Daily'
					WHEN [FrequencyTypeId] = 2 THEN 'Weekly'
				END AS FrequencyType
			  ,[FrequencyCount]
			  ,[DurationDays]
		 FROM 
			[sWellness].[tWellnessActivityTaskMaster] WATM
		 LEFT JOIN 
			[sWellness].[tWellnessActivityMaster] WAM
		 ON 
			WAM.ActivityId = WATM.ActivityId
		 WHERE 
			WATM.Id = @rId
END
GO
PRINT N'Creating Procedure [sWellness].[pGetWellnessActivityTaskMasterList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessActivityTaskMasterList]
	@rActivityId INT = 0,
	@rFrequencyTypeId INT = 0
AS
BEGIN		
		SELECT [Id]
			  ,WATM.[ActivityId] AS ActivityId
			  ,WAM.ActivityName AS ActivityName
			  ,WATM.Name as TaskName
			  ,[TargetValue]
			  ,WAM.DefaultUnitId
			  ,CASE WHEN WAM.DefaultUnitId = 1 THEN 'Steps' 
					WHEN WAM.DefaultUnitId = 2 THEN 'Min' 
					WHEN WAM.DefaultUnitId = 3 THEN 'ML'
					WHEN WAM.DefaultUnitId = 4 THEN 'Times' 
				END AS UnitName
			  ,[FrequencyTypeId]
			  ,CASE WHEN [FrequencyTypeId] = 1 THEN 'Daily'
					WHEN [FrequencyTypeId] = 2 THEN 'Weekly'
				END AS FrequencyType
			  ,[FrequencyCount]
			  ,[DurationDays]
		 FROM 
			[sWellness].[tWellnessActivityTaskMaster] WATM
		 LEFT JOIN 
			[sWellness].[tWellnessActivityMaster] WAM
		 ON 
			WAM.ActivityId = WATM.ActivityId
		 WHERE 
			(WAM.[ActivityId] = @rActivityId OR ISNULL(@rActivityId,0) = 0)
		 AND
			([FrequencyTypeId] = @rFrequencyTypeId OR ISNULL(@rFrequencyTypeId,0) = 0)
END
GO
PRINT N'Creating Procedure [sWellness].[pGetWellnessAppointmentSchedulingList]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessAppointmentSchedulingList]      
    @rOrgId INT,     
    @rId BIGINT = 0,
    @rEmployeeCode NVARCHAR(20) = '',      
    @rPatientName NVARCHAR(500) = '',      
    @rStoreLocationId INT = 0,      
    @rLocationId INT = 0,      
    @rSetupId INT = 0,      
    @rDoctorEmployeeId BIGINT = 0,      
    @rEmployeeStoreLocationId INT = 0,
	@rDescription nvarchar(4000)=''
AS      
BEGIN    
    SET @rEmployeeCode = CASE     
        WHEN CHARINDEX('*', @rEmployeeCode) > 0    
            THEN REPLACE(@rEmployeeCode, '*', '%')    
        ELSE '%' + @rEmployeeCode + '%'    
    END;    
    
    SELECT     
        A.Id,    
        A.AppointmentNumber,    
        A.PatientSourceTypeId,    
        A.PatientSourceId,    
        A.PatientName,    
        A.AppointmentDate,    
        ISNULL(A.FromTime, CONVERT(DATETIME, A.AppointmentDate)) AS FromTime,    
        ISNULL(A.ToTime, CONVERT(DATETIME, A.AppointmentDate)) AS ToTime,    
        ISNULL(A.DoctorEmployeeId, 0) AS DoctorEmployeeId,    
        A.EmployeeCode,    
        A.EmployeeId,    
        REPLACE(A.Relation, 'Ohter', 'Other') AS Relation,    
        A.Gender,    
        A.DoctorName,    
        A.OrgId,    
        A.IsRegister,    
        A.IsObsolete,    
        A.StatusName,    
        A.DepartmentName,    
        ISNULL(A.DepartmentId, 0) AS DepartmentId,    
        A.DependentId,    
        A.StoreLocationId,    
        A.SetupId,    
        A.ExaminationTypeId,    
        A.MainType,    
        A.Setup,    
        A.ReferSourceId,    
        A.LocationId,    
        ISNULL(A.CauseId, -1) AS CauseId,    
        A.StoreLocation,    
        ISNULL(A.OtherName, '') AS OtherName,    
        ISNULL(A.FollowupRemark, '') AS FollowupRemark,    
        A.Age,    
        A.Months,    
        A.GenderId,    
        A.ExaminationId,    
        A.Timeslot,
		ISNULL(A.CompliantRemark, '') AS CompliantRemark
    FROM
		[sWellness].[vExtPatientWellnessAppointmentDetail] A
    LEFT JOIN     
        sWellness.tWellnessConsultation E ON A.ExaminationId = E.Id    
        OR A.ReferSourceId = E.Id
    WHERE     
        A.ApprovalStatusId = 548   
		AND A.AppointmentDate = CONVERT(DATE, sCommon.fGetDate())    
        AND (A.Id = @rId OR @rId = 0)    
        AND A.OrgId = @rOrgId    
        AND (A.PatientName LIKE @rPatientName + '%' OR A.OtherName LIKE @rPatientName + '%' OR ISNULL(@rPatientName, '') = '')    
		AND ((ISNULL(Relation, '')  Like @rDescription + '%') OR(@rDescription = ''))
        AND (A.EmployeeCode LIKE @rEmployeeCode OR ISNULL(@rEmployeeCode, '') = '')    
        AND (A.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)    
        AND (A.LocationId = @rLocationId OR @rLocationId = 0)    
        AND (A.SetupId = @rSetupId OR @rSetupId = 0)    
        AND (A.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0)    
        AND ISNULL(A.ExaminationId, 0) = 0    
        AND ISNULL(E.IsCancel, 0) = 0
	ORDER BY A.Id DESC;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetWellnessEmployeeProgramDetailsById]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessEmployeeProgramDetailsById](
	@rId INT,
	@rOrgId INT
)
AS		
BEGIN		--  [sWellness].[pGetWellnessEmployeeProgramDetailsById]1,9999
SET NOCOUNT ON;	

		SELECT MS.[Id] AS Id
			  ,MS.[ProgramId] AS ProgramId
			  ,PM.Title AS ProgramName
			  ,MS.[EmployeeId] AS EmployeeId
			  ,ED.Code As EmployeeCode
			  ,ED.EmployeeName AS EmployeeName
			  ,ED.EmployeeLocationId AS LocationId
			  ,ISNULL(ED.CompanyEmail,'') AS EmployeeEmail
			  ,LM.Title AS LocationName
			  ,[ED].[DepartmentId] AS DepartmentId
			  ,[ED].[DepartmentName] AS DepartmentName
			  ,[SurveyCategory] AS SurveyCategory
			  ,[MHICategory] AS MHICategory
		  FROM 
			  [sWellness].[tMHIScore] MS
		  INNER JOIN
		      [sWellness].[tProgramMaster] PM 
		  ON 
			  MS.ProgramId = PM.Id
		  INNER JOIN 
			  [sHrm].[vExtEmployeeMaster] ED
		  ON 
			  MS.EmployeeId = ED.EmployeeId
		  LEFT JOIN
			  [sCommon].[tLocationMaster] LM
		  ON 
			 LM.Id = ED.EmployeeLocationId
		  WHERE
			 MS.OrgId = @rOrgId AND MS.Id = @rId;
END
GO
PRINT N'Creating Procedure [sWellness].[pInsertMHIScoreHistoryIfChanged]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pInsertMHIScoreHistoryIfChanged]
(
    @rEmployeeId BIGINT,
    @rUserId BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO sWellness.tMHIScore_History
    (
        Id,
        OrgId, ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,

        BMI, BMIScore, BMICategory,
        HBA1C, HBA1CScore, HBA1CCategory,
        LDL, LDLScore, LDLCategory,
        BP, BPScore, BPCategory,
        Stress, StressScore, StressCategory,
        Lifestyle, LifestyleScore, LifestyleCategory,
        Biometrics, BiometricsCategory,
        SurveyCategory, MHICategory,MHICategoryId,ActionType,CreatedUserId,
        ActionDateTime
    )
    SELECT
        m.Id,
        m.OrgId, m.ProgramId, m.EmployeeId, m.EmployeeSourceTypeId, m.LastUpdateType,

        m.BMI, m.BMIScore, m.BMICategory,
        m.HBA1C, m.HBA1CScore, m.HBA1CCategory,
        m.LDL, m.LDLScore, m.LDLCategory,
        m.BP, m.BPScore, m.BPCategory,
        m.Stress, m.StressScore, m.StressCategory,
        m.Lifestyle, m.LifestyleScore, m.LifestyleCategory,
        m.Biometrics, m.BiometricsCategory,
        m.SurveyCategory, m.MHICategory,m.MHICategoryId,'Update',m.CreatedUserId,
        sCommon.fGetDate()
    FROM sWellness.tMHIScore m
    WHERE m.EmployeeId = @rEmployeeId
      AND NOT EXISTS
      (
          SELECT 1
          FROM sWellness.tMHIScore_History h
          WHERE h.EmployeeId = m.EmployeeId
            AND h.ActionDateTime =
            (
                SELECT MAX(h2.ActionDateTime)
                FROM sWellness.tMHIScore_History h2
                WHERE h2.EmployeeId = m.EmployeeId
            )
            AND ISNULL(h.BMI,0)                  = ISNULL(m.BMI,0)
            AND ISNULL(h.BMIScore,0)             = ISNULL(m.BMIScore,0)
            AND ISNULL(h.BMICategory,'')         = ISNULL(m.BMICategory,'')

            AND ISNULL(h.HBA1C,0)                = ISNULL(m.HBA1C,0)
            AND ISNULL(h.HBA1CScore,0)           = ISNULL(m.HBA1CScore,0)
            AND ISNULL(h.HBA1CCategory,'')       = ISNULL(m.HBA1CCategory,'')

            AND ISNULL(h.LDL,0)                  = ISNULL(m.LDL,0)
            AND ISNULL(h.LDLScore,0)             = ISNULL(m.LDLScore,0)
            AND ISNULL(h.LDLCategory,'')         = ISNULL(m.LDLCategory,'')

            AND ISNULL(h.BP,'')                  = ISNULL(m.BP,'')
            AND ISNULL(h.BPScore,0)              = ISNULL(m.BPScore,0)
            AND ISNULL(h.BPCategory,'')          = ISNULL(m.BPCategory,'')

            AND ISNULL(h.Stress,0)               = ISNULL(m.Stress,0)
            AND ISNULL(h.StressScore,0)          = ISNULL(m.StressScore,0)
            AND ISNULL(h.StressCategory,'')      = ISNULL(m.StressCategory,'')

            AND ISNULL(h.Lifestyle,0)            = ISNULL(m.Lifestyle,0)
            AND ISNULL(h.LifestyleScore,0)       = ISNULL(m.LifestyleScore,0)
            AND ISNULL(h.LifestyleCategory,'')   = ISNULL(m.LifestyleCategory,'')

            AND ISNULL(h.Biometrics,0)           = ISNULL(m.Biometrics,0)
            AND ISNULL(h.BiometricsCategory,'')  = ISNULL(m.BiometricsCategory,'')

            AND ISNULL(h.SurveyCategory,'')      = ISNULL(m.SurveyCategory,'')
            AND ISNULL(h.MHICategory,'')         = ISNULL(m.MHICategory,'')
			AND ISNULL(h.MHICategoryId,0)        = ISNULL(m.MHICategoryId,0)
      );

    RETURN @@ROWCOUNT; -- 1 = inserted, 0 = skipped
END;
GO
PRINT N'Creating Procedure [sWellness].[pIsProgramMasterUsed]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pIsProgramMasterUsed]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;
    BEGIN TRY    

		DECLARE @MHICount BIT = 0, @MHIHistoryCount BIT
		SELECT @MHICount = CASE WHEN EXISTS (SELECT 1  FROM [sWellness].[tMHIScore] WHERE OrgId = @rOrgId AND ProgramId = @rId ) THEN 1 ELSE 0 END;
		SELECT @MHIHistoryCount = CASE WHEN EXISTS ( SELECT 1  FROM [sWellness].[tMHIScore_History] WHERE OrgId = @rOrgId AND ProgramId = @rId) THEN 1 ELSE 0 END;

		SELECT CASE WHEN @MHICount = 1 OR @MHIHistoryCount = 1 THEN 1 ELSE 0 END AS Result
		
    END TRY
    BEGIN CATCH 
        SELECT -101 AS Result;  
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pListAssignedEmployeeTask]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListAssignedEmployeeTask]
(
	@rEmployeeId BIGINT
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT
		ISNULL(WACM.Title,'-') AS CategoryName,
		ISNULL(WAM.ActivityName,'-') AS ActivityName,

		CASE 
			WHEN Assigned.IsCustomActivityTask = 1 
				THEN ISNULL(Assigned.WellnessActivityCustom,'-')
			ELSE ISNULL(WATM.Name,'-')
		END AS TaskName,

		EM.FirstName +' '+ EM.LastName AS ConsultedBy,
		Assigned.WeekNo,

		CASE 
			WHEN Assigned.WeekStart IS NULL THEN '-' 
			ELSE CONVERT(VARCHAR,Assigned.WeekStart,103) 
		END AS WeekStart,

		CASE 
			WHEN Assigned.WeekEnd IS NULL THEN '-' 
			ELSE CONVERT(VARCHAR,Assigned.WeekEnd,103) 
		END AS WeekEnd,

		Assigned.TargetValue,

		CASE 
			WHEN WAM.DefaultUnitId = 1 THEN 'Steps'
			WHEN WAM.DefaultUnitId = 2 THEN 'Min'
			WHEN WAM.DefaultUnitId = 3 THEN 'ML'
			WHEN WAM.DefaultUnitId = 4 THEN 'Times'
			ELSE '-'
		END AS UnitName,

		CASE 
			WHEN Assigned.WeekStart IS NULL THEN 'Assigned'
			WHEN GETDATE() < Assigned.WeekStart THEN 'Assigned'
			WHEN GETDATE() BETWEEN Assigned.WeekStart AND Assigned.WeekEnd THEN 'Active'
			WHEN GETDATE() > Assigned.WeekEnd THEN 'Expired'
			ELSE '-'
		END AS Status

	FROM
		[sWellness].[tAssignedActivity] Assigned

	INNER JOIN
		[sWellness].[tWellnessActivityMaster] WAM
	ON
		WAM.ActivityId = Assigned.WellnessActivityId

	INNER JOIN
		[sWellness].[tWellnessActivityCategoryMaster] WACM
	ON
		WACM.Id = WAM.WellnessActivityCategoryId

	LEFT JOIN
		[sWellness].[tWellnessActivityTaskMaster] WATM
	ON
		WATM.Id = Assigned.WellnessActivityTaskId
		AND ISNULL(Assigned.IsCustomActivityTask,0) <> 1

	INNER JOIN
		[sWellness].[tWellnessConsultation] Consult
	ON
		Assigned.ConsultationId = Consult.Id

	INNER JOIN
		[sHrm].[tEmployeeMaster] EM
	ON
		EM.Id = Consult.DoctorEmployeeId

	WHERE
		Assigned.EmployeeId = @rEmployeeId;

END
GO
PRINT N'Creating Procedure [sWellness].[pListEmployeeConsultionHistory]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListEmployeeConsultionHistory]    
(    
	@rEmployeeId BIGINT
)    
AS    
SET NOCOUNT ON    
BEGIN    
	SELECT 
		WC.ConsultationNumber,
		CASE WHEN WC.ConsultationDate IS NULL THEN '-' ELSE CONVERT(VARCHAR(15),WC.ConsultationDate,103) END AS ConsultationDate,
		EEM.DepartmentName AS DepartmentName,
		EEM2.EmployeeName AS ConsultedBy
	FROM 
		[sWellness].[tWellnessConsultation] WC
	LEFT JOIN
		[sHrm].[vExtEmployeeMaster] EEM
	ON
		EEM.EmployeeId = WC.ParticipantSourceId
	LEFT JOIN
		[sHrm].[vExtEmployeeMaster] EEM2
	ON
		EEM2.EmployeeId = WC.DoctorEmployeeId
	WHERE
		ParticipantSourceId = @rEmployeeId
END
GO
PRINT N'Creating Procedure [sWellness].[pListEmployeeEncounterNotes]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListEmployeeEncounterNotes]
(
	@rEmployeeId BIGINT
)
AS
SET NOCOUNT ON 
BEGIN
	SET NOCOUNT ON; 

	SELECT 
		CT.Id,
		EM.EmployeeName as ConsultedBy,
		CT.ConsultationNumber as ConsultationNumber,
		ISNULL(ConsultationNotes,'-') AS ConsultationNotes,
		CASE 
    WHEN CT.CreatedDateTime IS NULL THEN '-' 
    ELSE 
        CAST(DATEPART(DAY, CT.CreatedDateTime) AS VARCHAR(2)) + ' ' +
        DATENAME(MONTH, CT.CreatedDateTime) + ' ' +
        CAST(DATEPART(YEAR, CT.CreatedDateTime) AS VARCHAR(4)) +
        ' at ' +
        LOWER(
            FORMAT(CT.CreatedDateTime, 'hh:mm tt')
        )
END AS CreatedDateTime,
		CONVERT(VARCHAR,CT.CreatedDateTime,103) AS ConsultationDate,
		FORMAT(CT.CreatedDateTime, 'hh:mm tt') AS ConsultationTime,
 		'' as Speciality
	FROM 
		[sWellness].[tWellnessConsultation] CT 
	INNER JOIN 
		[sHrm].[vExtEmployeeMaster] EM 
	ON 
		EM.EmployeeId= CT.DoctorEmployeeId
	WHERE 
		CT.ParticipantSourceId = @rEmployeeId
	Order by Id Desc
END
GO
PRINT N'Creating Procedure [sWellness].[pListPastProgramForEmployee]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListPastProgramForEmployee]
(
    @rEmployeeId BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH CTE AS
    (
        SELECT 
            Id,
            MHICategory,
			EmployeeId,
			ProgramId,
            ActionDateTime,
			CASE WHEN ActionDateTime IS NULL THEN '-' ELSE CONVERT(VARCHAR,ActionDateTime,103) END AS UpdatedDate,
            LAG(MHICategory) OVER (ORDER BY ActionDateTime DESC) AS PrevCategory
        FROM 
			[sWellness].[tMHIScore_History]		
		WHERE 
			EmployeeId = @rEmployeeId AND MHICategory IS NOT NULL
    )

    SELECT 
        CTE.Id,
        CTE.MHICategory,
		CTE.EmployeeId,
		CTE.ProgramId,
		PM.Title,
        CTE.ActionDateTime,
        CTE.UpdatedDate
    FROM 
		CTE
	INNER JOIN
			[sWellness].[tProgramMaster] PM
	ON
		PM.Id = CTE.ProgramId
    WHERE 
		PrevCategory IS NULL  OR MHICategory <> PrevCategory
    ORDER BY 
		ActionDateTime 
	DESC;
END
GO
PRINT N'Creating Procedure [sWellness].[pListProgramByCategory]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListProgramByCategory]
(
	@rCategoryId SMALLINT,
	@rLocationId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
		SET NOCOUNT ON;

		SELECT 
			PM.Id AS Value,
			PM.Title AS Text
		FROM	
			[sWellness].[tProgramMaster] PM
		INNER JOIN
			[sWellness].[tProgramLocation] PL
		ON
			PL.ProgramId = PM.Id
		WHERE
			PM.IsObsolete = 0
		AND
			PM.CategoryId = @rCategoryId
		AND
			PL.LocationId = @rLocationId
		AND
			PM.IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pListProgramSessionAttendance]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListProgramSessionAttendance]
(
	@rProgramId INT
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT 
		PSA.AutoId,
		PSA.StoreLocationId,
		ISNULL(SLM.Title,'-') AS StoreLocationName,
		PSA.ProgramId,
		PSA.AttendedEmployee,
		PSA.AttendedDate,
		ISNULL(CONVERT(VARCHAR(10), PSA.AttendedDate, 103), '-') AS AttendateDateString,
		PSA.Remark,
		EM.FirstName +' ' + EM.LastName AS EmployeeName
	FROM
		[sWellness].[tProgramSessionAttendance] PSA
	INNER JOIN
		[sIp].[tStoreLocationMaster] SLM
	ON
		SLM.Id = PSA.StoreLocationId
	INNER JOIN
		[sSecurity].[tUser]  Users
	ON
		Users.Id = PSA.CreatedUserId
	LEFT JOIN
		[shrm].[tEmployeeMaster] EM
	ON
		EM.Id = Users.SourceId AND Users.SourceTypeId = 95
 	WHERE
		ProgramId = @rProgramId
END
GO
PRINT N'Creating Procedure [sWellness].[pListProgramSubLocationForUser]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pListProgramSubLocationForUser]
(
	@rProgramId INT,
    @rUserId BIGINT,
    @rOrgId SMALLINT
)
AS
BEGIN
   SELECT 
		StoreLocationId AS Value,
		StoreName AS Text 
   FROM 
		[sSecurity].[vExtUserLocation]  UL
   INNER JOIN
		[sWellness].[tProgramLocation] PL
   ON
		PL.LocationId = UL.LocationId
   WHERE
		UL.IsObsolete = 0 
	AND 
		UL.OrgId = @rOrgId  
	AND 
		UL.UserId = @rUserId 
	AND
		PL.ProgramId = @rProgramId
	ORDER BY 
		StoreName
END
GO
PRINT N'Creating Procedure [sWellness].[pMHIScoreUpdationAddUpdate]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pMHIScoreUpdationAddUpdate]
	@rId bigint=0,
	@rParticipantSourceTypeId smallint,
	@rParticipantSourceId bigint,
	@rBMI decimal(10,2),
	@rHBA1C decimal(10,2),
	@rLDL decimal(10,2),
	@rBPSystolic decimal(10,2),
	@rBPDiastolic decimal(10,2),
	@rStress decimal(10,2),
	@rLifeStyle decimal(10,2),
	@rUserId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN TRY

		IF  EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE  ParticipantSourceId = @rParticipantSourceId  and Id<>@rId)
		BEGIN	 
			SELECT -102 AS RESULT
			return
		END
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF(@rId=0)
					BEGIN
					INSERT INTO [sWellness].[tMHIScoreUpdation]
							(
							ParticipantSourceTypeId,
							ParticipantSourceId,
							BMI,
							HBA1C,
							LDL,
							BPSystolic,
							BPDiastolic,
							Stress,
							LifeStyle,
							CreatedUserId,
							CreatedDateTime
							)
							values
							(
							@rParticipantSourceTypeId,
							@rParticipantSourceId,
							@rBMI,
							@rHBA1C,
							@rLDL,
							@rBPSystolic,
							@rBPDiastolic,
							@rStress,
							@rLifeStyle,
							@rUserId,
							sCommon.fGetDate()
							)
	                SET @lNextNumber = SCOPE_IDENTITY();
					END
			ELse
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE Id=@rId)
						BEGIN	 
							SELECT -101 AS RESULT
							return
						END
						Update [sWellness].[tMHIScoreUpdation]
							Set 
								BMI=@rBMI,
								HBA1C =@rHBA1C,
								LDL=@rLDL,
								BPSystolic=@rBPSystolic,
								BPDiastolic =@rBPDiastolic,
								Stress = @rStress,
								LifeStyle = @rLifeStyle,
								UpdatedUserId = @rUserId,
								UpdatedDateTime = sCommon.fGetDate()
							Where Id=@rId

							SET @lNextNumber=@rId
				END
		COMMIT TRAN
		Select @lNextNumber as Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END
GO
PRINT N'Creating Procedure [sWellness].[pNextPreviousConsultationGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pNextPreviousConsultationGet]
@rOrgId bigint,
@rId bigint,
@rType nvarchar(20) = '',
@rSetupId int,
@rStoreLocationId int
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lNumber bigint = 0,@lNextNumber bigint = 0,@lPreviousNumber bigint = 0--,@Archivedate int = 0

	IF ( @rType = 'Next') 
	BEGIN
		SELECT @lNumber = ISNULL(MIN(ID),0) FROM sWellness.tWellnessConsultation
		WHERE ID > @rId	AND SetupId = @rSetupId AND OrgId = @rOrgId
		AND StoreLocationId = @rStoreLocationId and isnull(IsCancel,0) = 0

		IF ( @lNumber > 0)
			SELECT @lNextNumber =  ISNULL(MIN(ID),0) FROM sWellness.tWellnessConsultation
			WHERE ID > @lNumber AND SetupId = @rSetupId AND OrgId = @rOrgId
			AND StoreLocationId = @rStoreLocationId and isnull(IsCancel,0) = 0

	END
	ELSE if (@rType = 'Previous' AND @rId = 0)
	BEGIN      
		SELECT @lNumber =  ISNULL(MAX(ID),0) FROM sWellness.tWellnessConsultation
		WHERE SetupId = @rSetupId  AND OrgId = @rOrgId AND StoreLocationId = @rStoreLocationId
		and isnull(IsCancel,0) = 0
		
		IF ( @lNumber > 0)
		SELECT @lPreviousNumber =  ISNULL(MIN(ID),0) FROM sWellness.tWellnessConsultation
		WHERE ID < @lNumber AND SetupId = @rSetupId AND OrgId = @rOrgId  AND StoreLocationId = @rStoreLocationId
		and isnull(IsCancel,0) = 0
	END
	ELSE If (@rType = 'Previous')
	BEGIN
		SELECT @lNumber =  ISNULL(MAX(ID),0) FROM sWellness.tWellnessConsultation
		WHERE ID < @rId AND SetupId = @rSetupId	AND OrgId = @rOrgId AND StoreLocationId = @rStoreLocationId
		and isnull(IsCancel,0) = 0

		IF ( @lNumber > 0)
		BEGIN
			SELECT  @lPreviousNumber = ISNULL(MIN(ID),0) FROM sWellness.tWellnessConsultation
			WHERE ID < @lNumber	AND SetupId = @rSetupId AND  OrgId = @rOrgId AND StoreLocationId = @rStoreLocationId
			and isnull(IsCancel,0) = 0
		END
	END
	ELSE If ( @rType = 'Current' AND @rId = 0)
	BEGIN
		SET @lNextNumber = 0
		SELECT @lPreviousNumber = ISNULL(MAX(ID),0) FROM sWellness.tWellnessConsultation
		WHERE SetupId = @rSetupId AND  OrgId = @rOrgId AND StoreLocationId = @rStoreLocationId
		and isnull(IsCancel,0) = 0

	END
	ELSE If ( @rType = 'Current')
	BEGIN
		SELECT @lNumber =  @rId
		SELECT @lNextNumber =  ISNULL(MIN(ID),0) FROM sWellness.tWellnessConsultation
		WHERE ID > @lNumber AND SetupId = @rSetupId AND  OrgId = @rOrgId  AND StoreLocationId = @rStoreLocationId
		and isnull(IsCancel,0) = 0

		SELECT @lPreviousNumber =  ISNULL(MIN(ID),0) FROM sWellness.tWellnessConsultation
		WHERE ID < @lNumber	AND SetupId = @rSetupId AND  OrgId = @rOrgId   AND StoreLocationId = @rStoreLocationId
		and isnull(IsCancel,0) = 0

	END

	IF (@lNumber > 0)
	BEGIN
		SELECT E.Id,E.[OrgId],
		E.[ParticipantSourceTypeId],
		E.[ParticipantSourceId],
		ParticipantName = case when E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + EM.LastName
		when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + CS.LastName end,
		SS.Title as StatusName,
		E.[SetupId],
		SM.[RoundNumber],
		E.[StatusId],
		E.[ConsultationDate],
		ISNULL(E.[DoctorEmployeeId],0) AS DoctorEmployeeId,
		@lNextNumber AS NextId,
		@lPreviousNumber AS PreviousId,
		STM.MainTypeId As MainTypeId,
		MT.Title AS MainTypeName,
		E.StoreLocationId,
		SL.Title AS StoreLocationName,
		SL.LocationId as LocationId,
		LM.Title As LocationName,
		SM.Title AS SetUp,
		ParticiantCode = case when E.ParticipantSourceTypeId = 95 then EM.Code
		when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end

		FROM sWellness.tWellnessConsultation E
		inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		inner join sExamination.tMainTypeMaster MT on STM.MainTypeId = MT.Id
		inner join sIp.tStoreLocationMaster SL on E.StoreLocationId = SL.Id
		inner join sCommon.tLocationMaster LM on SL.LocationId = LM.Id
		left join sExamination.tStatusMaster SS on E.StatusId = SS.Id
		left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001
		left join sHrm.tCsrBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		where E.Id = @lNumber
	END
	ELSE
	BEGIN
		SELECT 0 AS Id,0 AS OrgId,0 AS ParticipantSourceTypeId,0 AS ParticipantSourceId,'' AS ParticipantName,
		'' AS StatusName,0 AS OrganizationDepartmentId,0 AS SetupId,0 AS RoundNumber,0 AS StatusId,'2012-1-01' AS ExaminationDate,
		0 AS DoctorEmployeeId,@lNextNumber AS NextId,@lPreviousNumber AS PreviousId,0 As MainTypeId,0 AS MainTypeName,
		0 As StoreLocationId,'' As StoreLocationName,0 As StoreLocationId,'' AS StoreLocationName,0 AS LocationId,
		'' As LocationName,'' AS SetUp,'' AS ParticiantCode
	END
END
GO
PRINT N'Creating Procedure [sWellness].[pSaveAllConsultationDatas]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pSaveAllConsultationDatas]   
@rId BIGINT,
@rSourceTypeId int = 10173,
@rParticipantSourceTypeId int = 95,
@rParticipantSourceId bigint,
@rOrgId smallint,
@rVitals nvarchar(max),                
@rTests nvarchar(max),              
@rWellnessAppointments nvarchar(max),                
@rTasks nvarchar(max),                
@rAdditionalFields nvarchar(max),
@rUserId bigint
as                
begin                 
SET NOCOUNT ON                
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED                
--SET XACT_ABORT ON                
                
 --SELECT -1 AS RESULT                
 --return                
 declare @trancount int;                
                    
 declare @error int, @message varchar(4000), @xstate int,@errorCount int, @errorLine int;                
                
 declare @lNextNumber bigint,@lFromNextNumber bigint,@lCount int,@rStoreLocationId int               
 declare @lAppointmentid bigint,@rReferSourceId bigint,@i int,@lAppointmentType tinyint                
 declare @loNextNumber varchar(20),@lAppointmentDate varchar(50),@rConsultationDate varchar(50)               
                 
 declare @lxmlVital xml,@lxmlTests xml,@lxmlWellnessAppointment xml,@lxmlTasks xml,@lxmlAdditionalFields xml;
                 
 declare @exceptiondetail nvarchar(max),@username nvarchar(200);
 declare @cnt int;
 BEGIN TRY                       
 set @lxmlVital = CAST(@rVitals AS xml)           
 set @lxmlTests = CAST(@rTests AS xml) 
 set @lxmlWellnessAppointment = CAST(@rWellnessAppointments AS xml)                
 set @lxmlTasks = CAST(@rTasks AS xml)                
 set @lxmlAdditionalFields = CAST(@rAdditionalFields AS xml)
 
 set @username = (select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(@rUserId,0));
 set @rConsultationDate = (select ConsultationDate from sWellness.tWellnessConsultation where Id = @rId);

BEGIN TRY
 declare @tblGeneralTemplates table(tid int identity(1,1),TestId int,ParamId int,
	GeneralTemplateConsultationId bigint,GeneralTemplateConsultationDetailId bigint,ServiceResult varchar(250),Remark varchar(250), GtgId smallint)
	insert into @tblGeneralTemplates
	select T.c.value('@GtId','Int') as TestId,
	T.c.value('@GtpId','Int') as ParamId,
	T.c.value('@GtExId','bigint') as GtExId,
	T.c.value('@GeneralTemplateConsultationDetailId','bigint') as GeneralTemplateConsultationDetailId,
	T.c.value('@ServiceResult','varchar(250)') as ServiceResult,
	T.c.value('@Remark','varchar(250)') as Remark,
	T.c.value('@GtgId','smallint') as GtgId
	from @lxmlVital.nodes('/GeneralTemplates/GeneralTemplate')T(c)

	select @cnt = count(*),@i = 1 from @tblGeneralTemplates

	delete w from sWellness.tGeneralTemplateConsultationDetail w
	inner join sWellness.tGeneralTemplateConsultation e
	on e.Id = w.GeneralTemplateConsultationId
	where e.GeneralTemplateId not in
	(
		select TestId from @tblGeneralTemplates
	)
	and w.GeneralTemplateParameterId not in
	(
		select ParamId from @tblGeneralTemplates
	) and e.SourceId = @rId and e.OrgId = @rOrgId
	and ((select distinct GtgId from @tblGeneralTemplates) = (select GeneralTemplateGroupId from sExamination.tGeneralTemplateMaster where Id = e.GeneralTemplateId))
		
	delete from sWellness.tGeneralTemplateConsultation where GeneralTemplateId not in
	(
		select TestId from @tblGeneralTemplates
	) and SourceId = @rId and OrgId = @rOrgId
	and ((select distinct GtgId from @tblGeneralTemplates) = (select GeneralTemplateGroupId from sExamination.tGeneralTemplateMaster where Id = GeneralTemplateId))

	while @i <= @cnt
	begin
		declare @TestId int,@ParamId int,@rServiceResult varchar(250)
		select @TestId = TestId,@ParamId = ParamId,@rServiceResult = ServiceResult from @tblGeneralTemplates where tid = @i
		select @TestId = isnull(@TestId,0),@ParamId = isnull(@ParamId,0),@rServiceResult = isnull(@rServiceResult,'')
		
		declare @detailid bigint
		select @detailid = GeneralTemplateConsultationDetailId from @tblGeneralTemplates where tid = @i
		
		declare @lParameterValueTypeId int,@lListValueTypeId int;
		select @lParameterValueTypeId = ParameterValueTypeId from sExamination.tGeneralTemplateParameter where Id = @ParamId
		
		if @TestId > 0
		begin
			if not exists(select * from sWellness.tGeneralTemplateConsultation where SourceId = @rId and SourceTypeId = @rSourceTypeId
			and GeneralTemplateId = @TestId and OrgId = @rOrgId)
			begin
				exec sCommon.pTableRowIdGet @rOrgId,'sWellness.tGeneralTemplateConsultation', 0, 1, 1,@outNextNumber = @lNextNumber output
				insert into sWellness.tGeneralTemplateConsultation
				(
					[Id],[SourceId],[GeneralTemplateId],[SourceTypeId],OrgId
				)
				values
				(
					@lNextNumber,@rId,@TestId,@rSourceTypeId,@rOrgId
				)
			end
			else
			begin
				select @lNextNumber = Id from sWellness.tGeneralTemplateConsultation where SourceId = @rId and SourceTypeId = @rSourceTypeId
				and GeneralTemplateId = @TestId and OrgId = @rOrgId
			end
			
			if @detailid > 0
			begin
				update sWellness.tGeneralTemplateConsultationDetail set ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult)
				where Id = @detailid
			end
			else if not exists(select * from sWellness.tGeneralTemplateConsultationDetail where GeneralTemplateConsultationId = @lNextNumber
			and GeneralTemplateParameterId = @ParamId)
			begin
				declare @GeneralTempExamiantionId bigint
				select @GeneralTempExamiantionId = @lNextNumber
				insert into sWellness.tGeneralTemplateConsultationDetail
				(
					[GeneralTemplateConsultationId],[GeneralTemplateParameterId],[ParameterValue],Remark,IsAbnormal
				)
				values
				(
					@GeneralTempExamiantionId,@ParamId,[sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult),'',0
				)
			end
			else
			begin
				update sWellness.tGeneralTemplateConsultationDetail set ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult)
				where [GeneralTemplateConsultationId] = @GeneralTempExamiantionId and [GeneralTemplateParameterId] = @ParamId
			end
		end
		select @i = @i + 1
	end  
 END TRY          
 BEGIN CATCH                 
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();

 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @rOrgId,'Consultation_Vital_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 1              
 END CATCH             
  
 declare @tblTests table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ConsultationId bigint,                
 t_OrgId int,t_ParameterId int,t_ServiceValue nvarchar(500),t_Remark varchar(max),t_IsReferred bit,t_ClinicalId bigint,t_IsDone bit,                
 t_ParticipantAreaId bigint,t_TestRequestId bigint,t_TestDetailId int,t_TestRequestDetailId bigint,t_IsPackageValue varchar(10))                
 insert into @tblTests                
select T.c.value('@AreaId','int') as AreaId,                
 T.c.value('@AreaTypeId','int') as AreaTypeId,                
 T.c.value('@ConsultationId','bigint') as ConsultationId,                 
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ParameterId','int') as ParameterId,            
 T.c.value('@ServiceValue','nvarchar(500)') as ServiceValue,      
 T.c.value('@Remark','varchar(max)') as Remark,                
 T.c.value('@IsReferred','bit') as IsReferred,                
 T.c.value('@ClinicalId','bigint') as ClinicalId,                
 T.c.value('@IsDone','bit') as IsDone,                 
 null,null,null,null,                
 T.c.value('@IsPackageValue','varchar(10)') as IsPackageValue                
 from @lxmlTests.nodes('/ExaminTest/Tests')T(c)                
                  
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ConsultationId = p.SourceId                
                 
 update t set t.t_TestDetailId = p.Id from @tblTests t inner join sOrderEntry.tTestDetail p                
 on t.t_AreaId = p.TestId and t.t_ParameterId = p.TestParameterId                
                 
 declare @tblTestsNew table(tid int identity(1,1),tt_TestId int,tt_ConsultationId bigint,tt_OrgId int,                
 tt_ParticipantAreaId bigint,tt_TestRequestId bigint,tt_IsPackageValue varchar(10))                
 insert into @tblTestsNew                
 select distinct t_AreaId,t_ConsultationId,t_OrgId,t_ParticipantAreaId,t_TestRequestId,t_IsPackageValue from @tblTests                
 BEGIN TRY          
         
 begin                
 exec sCommon.pTableRowIdGet @rOrgId, 'sWellness.tConsultationTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                 
 MERGE sWellness.tConsultationTestRequest AS Target USING                 
 (                
  SELECT Id,tt_TestRequestId,tt_TestId,tt_OrgId,tt_ConsultationId,tid,tt_IsPackageValue                
  FROM @tblTestsNew TT LEFT JOIN sWellness.tConsultationTestRequest T with(NOLOCK) ON TT.tt_TestRequestId = T.Id                
 ) AS Source ON Target.Id = Source.tt_TestRequestId                 
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,TestId,SourceTypeId,OrgId,IsObsolete,IsPackage                
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,tt_ConsultationId,tt_TestId,@rSourceTypeId,tt_OrgId,0,case when upper(tt_IsPackageValue)='Y' then 1 else 0 end                
  );                
 begin                
 select @lCount = COUNT(1) FROM @tblTestsNew                 
 SET @lNextNumber  = @lCount + @lFromNextNumber                 
 exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sWellness.tConsultationTestRequest', @rCurrentNumber = @lNextNumber                
 end             
                 
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ConsultationId = p.SourceId                
                 
 update t set t.t_TestRequestDetailId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequestDetail p                
 on t.t_TestDetailId = p.TestDetailId and t.t_TestRequestId = p.TestRequestId
                 
 declare @tblTestsM table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ConsultationId bigint,                
 t_OrgId int,t_ParameterId int,t_ServiceValue nvarchar(500),t_Remark varchar(400),t_IsReferred bit,t_ClinicalId bigint,t_IsDone bit,                
 t_ParticipantAreaId bigint,t_TestRequestId bigint,t_TestDetailId int,t_TestRequestDetailId bigint)                
 insert into @tblTestsM      
 select t_AreaId,t_AreaTypeId,t_ConsultationId,t_OrgId,t_ParameterId,t_ServiceValue,t_Remark,t_IsReferred,t_ClinicalId,t_IsDone,                
 t_ParticipantAreaId,t_TestRequestId,t_TestDetailId,t_TestRequestDetailId from @tblTests where t_TestDetailId is not null        
                
MERGE sWellness.tConsultationTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ConsultationId,t_TestRequestDetailId,tid,t_ServiceValue,t_Remark      
  FROM @tblTestsM TT LEFT JOIN sWellness.tConsultationTestRequestDetail T with(NOLOCK) ON TT.t_TestRequestDetailId = T.Id                
 ) AS Source ON Target.Id = Source.t_TestRequestDetailId                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   TestRequestId,TestDetailId,OrgId,ServiceValue,Remark           
  )                
  VALUES                
  (                
   t_TestRequestId,t_TestDetailId,t_OrgId,t_ServiceValue,t_Remark      
  )      
  WHEN MATCHED THEN UPDATE SET ServiceValue=t_ServiceValue, Remark=t_Remark;    
             
 END TRY                
 BEGIN CATCH                
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
                    
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @rOrgId,'Consultation_TestRequestDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 2              
 END CATCH

 declare @tblWellnessAppointments table(tid int identity(1,1),a_AppointmentId bigint,a_ExamId bigint,a_doctorId bigint,a_EmpId bigint,                
 a_obsolete bit,a_PatientSourceTypeId bigint,a_OrgId int,a_AppointmentDate varchar(50),a_StoreLocationId int,                
 a_FollowupRemark varchar(max),a_SetupId int,a_CauseId int,a_CreatedUserId bigint,a_SubTypeId int,                
 a_AppointNumber varchar(200),a_OtherName varchar(200),a_age int,a_VaccineId int,a_AppointmentType tinyint,a_genderId int)            
 insert into @tblWellnessAppointments                
 select T.c.value('@AppointmentId','bigint') as AppointmentId,                
 T.c.value('@ConsultationId','bigint') as ConsultationId,
 T.c.value('@DoctorEmployeeId','bigint') as DoctorEmployeeId,                
 T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,                
 T.c.value('@IsObsolete','bit') as IsObsolete,                
 T.c.value('@PatientSourceTypeId','int') as PatientSourceTypeId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@AppointmentDate','varchar(50)') as AppointmentDate,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,   
 T.c.value('@FollowupRemark','varchar(max)') as FollowupRemark,                
 T.c.value('@SetupId','int') as SetupId,                
 T.c.value('@CauseId','int') as CauseId,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,null,'',                
 T.c.value('@OtherName','varchar(200)') as OtherName,null as age,                
 T.c.value('@VaccineId','int') as VaccineId,                
 T.c.value('@AppointmentType','tinyint') as AppointmentType, null as genderId           
 from @lxmlWellnessAppointment.nodes('/Appointments/Appointment')T(c)         
            
 update w set w.a_SubTypeId = s.SubTypeId from @tblWellnessAppointments w inner join sExamination.tSetupMaster s on s.Id = w.a_SetupId                
                  
 update @tblWellnessAppointments set a_AppointmentId = IsNull(Id,0) from sWellness.tAppointment where a_ExamId = ReferSourceId               
                 
 update a set a_age = case when a.a_PatientSourceTypeId = 1009 then                
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end                
 when a.a_PatientSourceTypeId = 1001 then                
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else                
 case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end end                
 From @tblWellnessAppointments as a                
 left join sHrm.tEmployeeMaster EM on a.a_EmpId = EM.Id and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeePersonalDetail EP on a.a_EmpId = EP.EmployeeId and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = a.a_EmpId and a.a_PatientSourceTypeId = 1001                
 left join sHrm.tCsrBenefiterMaster CS on a.a_EmpId = CS.Id and a.a_PatientSourceTypeId = 1009                
            
  update a set a_genderId = case when a.a_PatientSourceTypeId = 1009 then CS.GenderId                
 when a.a_PatientSourceTypeId = 1001 then EFD.GenderId else EP.GenderId end            
 From @tblWellnessAppointments as a                
 left join sHrm.tEmployeeMaster EM on a.a_EmpId = EM.Id and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeePersonalDetail EP on a.a_EmpId = EP.EmployeeId and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = a.a_EmpId and a.a_PatientSourceTypeId = 1001                
 left join sHrm.tCsrBenefiterMaster CS on a.a_EmpId = CS.Id and a.a_PatientSourceTypeId = 1009                
                
  Declare @lExamid bigint = 0, @lFollowUpRemark varchar(max), @lEmpId bigint;            
  select @lAppointmentid = ISNULL(a_AppointmentId,0),@lAppointmentType = ISNULL(a_AppointmentType,0), @lExamid = ISNULL(a_ExamId,0),            
  @lFollowUpRemark = ISNULL(a_FollowupRemark,''), @lEmpId = ISNULL(a_EmpId,0) from @tblWellnessAppointments                    
            
  if(ISNULL(@lAppointmentid,0) > 0)            
  BEGIN
		update sWellness.tAppointment set ExaminationId = @lExamid where Id = ISNULL(@lAppointmentid,0)            
  END
                
  if(ISNULL(@lAppointmentid,0)>0)              
  begin               
  if exists (select 1 from  sWellness.tAppointment where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1 and ISNULL(@lExamid,0) <> ReferSourceId)                 
  begin   
  update sWellness.tAppointment set ApprovalStatusId = 550 where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1              
  end                
 end               
 set @lAppointmentid = 0                
 select @rStoreLocationId = a_StoreLocationId,@lAppointmentid = a_AppointmentId,                
 @lAppointmentDate = a_AppointmentDate,@rReferSourceId = a_ExamId from @tblWellnessAppointments 
       
 if @lAppointmentDate <> ''                
 begin                
   IF NOT EXISTS (SELECT 1 FROM sWellness.tAppointment WHERE ReferSourceId = @lExamid)
   BEGIN    
  exec sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId,@rPrefixFunctionalityId = 1022,@rStoreLocationId = 0,                
  @rNextNumber = @loNextNumber output         
                  
  update @tblWellnessAppointments set a_AppointNumber = @loNextNumber                
  begin try                
  --begin tran                
  begin                
                
  exec sCommon.pTableRowIdGet @rOrgId, 'sWellness.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
    DECLARE @AppointmentFlag VARCHAR(50);
    SET @AppointmentFlag = 'Wellness Followup Appointment';

    INSERT INTO sWellness.tAppointment               
   (                
    Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,                
    AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,                
    IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,                
    StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,age,ApprovalStatusId, GenderId,AppointmentFlag               
   )                
  SELECT                             
    @lFromNextNumber + tid,a_EmpId,a_PatientSourceTypeId,                
    case when len(a_AppointmentDate) = 10 then convert(Datetime, a_AppointmentDate, 104) else CONVERT(VARCHAR(11), a_AppointmentDate) end,                
    a_AppointNumber,case when a_doctorId > 0 then a_doctorId else null end,                
    null,null,0,a_obsolete,a_OrgId,1,a_ExamId,0,a_StoreLocationId,a_SetupId,a_CauseId,                
    case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,200),case when Isnull(a_age,0)=0 then null else a_age end,548, a_genderId,@AppointmentFlag            
   FROM @tblWellnessAppointments TT;     
  begin                
  select @lCount = COUNT(1) FROM @tblWellnessAppointments                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sWellness.tAppointment', @rCurrentNumber = @lNextNumber                
  end                
  --commit tran;                
  end try                
  BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
      @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran ;                
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)             
  Select @rOrgId,'OPD_tAppointment_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 3          
 END CATCH     
 END
 end   
 
 DECLARE @tblTasks TABLE
(
    tid INT IDENTITY(1,1),
    r_ConsultationId BIGINT,
    r_Id BIGINT,
    r_WeekNoId INT,
    r_IsCustomActivityTask BIT,
    r_WellnessActivityCategoryId INT,
    r_WellnessActivityId INT,
    r_WellnessActivityTaskId INT,
    r_WellnessActivityCustomTask NVARCHAR(500),
    r_TargetValue NVARCHAR(100),
    r_UnitId INT,
    r_FrequencyTypeId INT,
    r_FrequencyCount INT,
    r_IsDelete BIT
)

INSERT INTO @tblTasks
SELECT
    T.c.value('@ConsultationId','bigint') AS ConsultationId,
    T.c.value('@Id','bigint') AS Id,
    T.c.value('@WeekNoId','int') AS WeekNoId,
    T.c.value('@IsCustomActivityTask','bit') AS IsCustomActivityTask,
    T.c.value('@WellnessActivityCategoryId','int') AS WellnessActivityCategoryId,
    T.c.value('@WellnessActivityId','int') AS WellnessActivityId,
    T.c.value('@WellnessActivityTaskId','int') AS WellnessActivityTaskId,
    T.c.value('@WellnessActivityCustomTask','nvarchar(500)') AS WellnessActivityCustomTask,
    T.c.value('@TargetValue','nvarchar(100)') AS TargetValue,
    T.c.value('@UnitId','int') AS UnitId,
    T.c.value('@FrequencyTypeId','int') AS FrequencyTypeId,
    T.c.value('@FrequencyCount','int') AS FrequencyCount,
    T.c.value('@IsDelete','bit') AS IsDelete
FROM @lxmlTasks.nodes('/WellnessTasks/Task') T(c)
         
 begin try
	DELETE A
	FROM sWellness.tAssignedActivity A
	INNER JOIN @tblTasks T 
		ON A.AssignedActivityId = T.r_Id
	WHERE T.r_IsDelete = 1

 DELETE FROM @tblTasks WHERE r_IsDelete = 1            
                 
 MERGE sWellness.tAssignedActivity AS Target
USING
(
 SELECT *
 FROM @tblTasks TT
 LEFT JOIN sWellness.tAssignedActivity T WITH(NOLOCK)
  ON TT.r_Id = T.AssignedActivityId
) AS Source
ON Target.AssignedActivityId = Source.r_Id
WHEN MATCHED THEN
 UPDATE SET
  WellnessActivityCategoryId = r_WellnessActivityCategoryId,
  WellnessActivityId = r_WellnessActivityId,
  WellnessActivityTaskId = r_WellnessActivityTaskId,
  IsCustomActivityTask = r_IsCustomActivityTask,
  WellnessActivityCustom = r_WellnessActivityCustomTask,
  TargetValue = r_TargetValue,
  UnitId = r_UnitId,
  FrequencyTypeId = r_FrequencyTypeId,
  FrequencyCount = r_FrequencyCount,
  WeekNo = r_WeekNoId,
  WeekStart = DATEADD(DAY, ((r_WeekNoId - 1) * 7) + 1, @rConsultationDate),
  WeekEnd = DATEADD(DAY, (r_WeekNoId * 7), @rConsultationDate),
  UpdatedUserId = @rUserId,
  UpdatedDateTime = sCommon.fGetDate()

WHEN NOT MATCHED THEN
 INSERT
 (
  ConsultationId,
  EmployeeId,
  WellnessActivityCategoryId,
  WellnessActivityId,
  WellnessActivityTaskId,
  IsCustomActivityTask,
  WellnessActivityCustom,
  TargetValue,
  UnitId,
  FrequencyTypeId,
  FrequencyCount,
  WeekNo,
  WeekStart,
  WeekEnd,
  CreatedUserId,
  CreatedDateTime
 )
 VALUES
 (
  @rId,
  @rParticipantSourceId,
  r_WellnessActivityCategoryId,
  r_WellnessActivityId,
  r_WellnessActivityTaskId,
  r_IsCustomActivityTask,
  r_WellnessActivityCustomTask,
  r_TargetValue,
  r_UnitId,
  r_FrequencyTypeId,
  r_FrequencyCount,
  r_WeekNoId,
  DATEADD(DAY, ((r_WeekNoId - 1) * 7) + 1, @rConsultationDate),
  DATEADD(DAY, (r_WeekNoId * 7), @rConsultationDate),
  @rUserId,
  sCommon.fGetDate()
 );  
                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
  @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();
			   
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)         
  Select @rOrgId,'Consultation_Tasks_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 4              
END CATCH 

BEGIN TRY
	IF NOT EXISTS (select * from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rId)
	begin    
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sWellness.tConsultationAdditionalFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output 
		
	INSERT INTO sWellness.tConsultationAdditionalFieldMaster
	(
		Id,ConsultationId,
		OrgId, IsObsolete, CreatedUserId, CreatedDateTime,
		UpdatedUserId, UpdatedDateTime
	)
	VALUES
	(
		@lNextNumber,@rId,
		@rOrgId, 0, @rUserId, sCommon.fGetDate(), 
		@rUserId, sCommon.fGetDate()
	)
	end
	else
	begin
		UPDATE sWellness.tConsultationAdditionalFieldMaster SET
		UpdatedUserId = @rUserId, UpdatedDateTime = sCommon.fGetDate()
		WHERE ConsultationId = @rId

		select @lNextNumber = Id from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rId
	end

	DECLARE @loDoc INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAdditionalFields

	DELETE FROM sWellness.tConsultationAdditionalFieldDetails WHERE AdditionalFieldId=@lNextNumber
	
		INSERT INTO sWellness.tConsultationAdditionalFieldDetails
		(
			AdditionalFieldId,
			AdditionalFieldSetupId,
			AdditionalFieldResponse
		)
		SELECT
			@lNextNumber,AdditionalFieldSetupId,[sSetup].[fPortalXMLTagsReplaceReverse](AdditionalFieldResponse)
		FROM
			OPENXML (@loDoc, '/AdditionalFields/AdditionalField', 1)WITH
			(
				AdditionalFieldSetupId int,
				AdditionalFieldResponse nvarchar(1000)
			)
END TRY
BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
                     
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)                
  Select @rOrgId,'Consultation_QA_Error',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 5              
 END CATCH
                
              
 END TRY                
  BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
                     
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)                
  Select @rOrgId,'Consultation_DBError',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 6             
 END CATCH
 --COMMIT TRANSACTION                
 if (@errorCount=-1)                
 begin                
 SELECT -1 AS RESULT,  @message as Error, @errorLine as [LineNo]              
 end                
 else                
 begin                
 SELECT 1 AS RESULT  ,  @message as Error, @errorLine as [LineNo]              
 end                
 --SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off            
end
GO
PRINT N'Creating Procedure [sWellness].[pSaveEmployeeTaskTrack]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pSaveEmployeeTaskTrack]
(
    @rTaskDate DATETIME,
    @rEmployeeId BIGINT,
    @rUserId BIGINT,
    @TaskList sWellness.EmployeeTaskTrackTableType READONLY,
    @Result BIT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY

        MERGE sWellness.tEmployeeTaskTrack AS TARGET
        USING
        (
            SELECT
                ConsultationId,
                @rEmployeeId AS EmployeeId,
                ISNULL(WellnessActivityTaskId,0) AS WellnessActivityTaskId,
                @rTaskDate AS TaskDate,
                AssignedActivityId,
                Status
            FROM @TaskList
        ) AS SOURCE
        ON  TARGET.EmployeeId = SOURCE.EmployeeId
		AND TARGET.AssignedActivityId = SOURCE.AssignedActivityId        
        AND TARGET.ConsultationId = SOURCE.ConsultationId
		AND ISNULL(TARGET.WellnessActivityTaskId,0) = SOURCE.WellnessActivityTaskId
        AND CAST(TARGET.TaskDate AS DATE) = CAST(SOURCE.TaskDate AS DATE)

        WHEN MATCHED THEN
            UPDATE SET
                TARGET.Status = SOURCE.Status,
                TARGET.UpdatedUserId = @rUserId,
                TARGET.UpdatedDateTime = GETDATE()

        WHEN NOT MATCHED THEN
            INSERT
            (
                ConsultationId,
                EmployeeId,
                WellnessActivityTaskId,
                TaskDate,
                AssignedActivityId,
                Status,
                CreatedUserId,
                CreatedDateTime
            )
            VALUES
            (
                SOURCE.ConsultationId,
                SOURCE.EmployeeId,
                SOURCE.WellnessActivityTaskId,
                SOURCE.TaskDate,
                SOURCE.AssignedActivityId,
                SOURCE.Status,
                @rUserId,
                GETDATE()
            );

        SET @Result = 1;

    END TRY
    BEGIN CATCH
        SET @Result = 0;
        THROW;
    END CATCH

END
GO
PRINT N'Creating Procedure [sWellness].[pSearchProgramParticipant]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pSearchProgramParticipant]
(
    @rProgramId INT,
    @rSearchText NVARCHAR(100) = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT TOP 20
         PP.Id AS ProgramParticipantId,
         PP.ParticipantCode,
         PP.ParticipantName,
		 PP.ParticipantDepartmentId,
		 PP.ParticipantSourceId,
		 PP.ParticipantSourceTypeId
    FROM 
         [sWellness].[tProgramParticipant] PP
    WHERE 
         PP.ProgramId = @rProgramId
         AND (
                @rSearchText IS NULL
                OR PP.ParticipantName LIKE '%' + @rSearchText + '%'
                OR PP.ParticipantCode LIKE '%' + @rSearchText + '%'
             )
    ORDER BY 
         PP.ParticipantName;

END
GO
PRINT N'Creating Procedure [sWellness].[pUpdateMHIScoreRoundLocationWise]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pUpdateMHIScoreRoundLocationWise]
(
    @rMaINTypeId        INT,
    @rOrgId             INT,
    @rSetupGroupId      INT,
    @rSetupId           INT,
    @rStoreLocationId   INT,
    @rUserId            BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @lLatestVitalDisplayConfigVal VARCHAR(5) = 'False';

    ---------------------------------------------------------
    -- Get Config Value
    ---------------------------------------------------------
    IF (@rOrgId > 0)
    BEGIN
        SELECT @lLatestVitalDisplayConfigVal =
        sConfig.fConfigurationValueGet(
            'Examination.LatestVitalDisplayOnDashboard',
            @rOrgId,0,0,0
        );
    END

    ---------------------------------------------------------
    -- STEP 1: Get Eligible Employees
    ---------------------------------------------------------
    ;WITH EmployeeCTE AS
    (
        SELECT DISTINCT
            E.ParticipantSourceId         AS EmpId,
			E.ParticipantSourceTypeId     AS EmpTypeId,
            EM.Code                       AS EmployeeCode,
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') 
                                            AS EmployeeName
        FROM sExamination.tExamination E
        INNER JOIN sExamination.tSetupMaster STP 
            ON E.SetupId = STP.Id
        INNER JOIN sExamination.tSubTypeMaster STM 
            ON STM.Id = STP.SubTypeId
        INNER JOIN sSecurity.tUserLocation USR 
            ON USR.StoreLocationId = E.StoreLocationId
        INNER JOIN sHrm.tEmployeeMaster EM
            ON EM.Id = E.ParticipantSourceId
        WHERE 
            STP.OrgId = @rOrgId
            AND E.ParticipantSourceTypeId = 95
            AND STP.IsObsolete = 0
            AND (STM.MainTypeId = @rMaINTypeId OR @rMaINTypeId = 0)
            AND STP.SetupGroupId = @rSetupGroupId
            AND STP.Id = @rSetupId
            AND E.StatusId IN (1,4)
            AND USR.UserId = @rUserId
            AND E.StoreLocationId = @rStoreLocationId
            AND EXISTS
            (
                SELECT 1
                FROM sExamination.tHealthIndex HI
                WHERE HI.ExaminationId = E.Id
            )
    )

    ---------------------------------------------------------
    -- STEP 2: Fetch Latest Values (NULL if not found)
    ---------------------------------------------------------
    SELECT DISTINCT
        EC.EmpId,
		EC.EmpTypeId,
        EC.EmployeeCode,
        EC.EmployeeName,

        BP.BloodPressureSystolic,
        BP.BloodPressureDiastolic,
        BMI.BMI,
        HBA1C.HBA1C,
        LDL.LDL,

		--SUR.AssignSurveyId,
		--SUR.TotalPoints,
		--SUR.EarnedPoints,
		--SUR.Percentage,
		--SUR.IndicatorName,

		MH.Stress,
		MH.LifeStyle
    FROM EmployeeCTE EC

    ---------------------------------------------------------
    -- Latest BMI
    ---------------------------------------------------------
    OUTER APPLY
    (
        SELECT TOP 1 V.BMI
        FROM sExamination.tExamination E
        INNER JOIN sExamination.tVital V 
            ON V.SourceId = E.Id
        INNER JOIN sExamination.tSetupMaster SM 
            ON SM.Id = E.SetupId
        INNER JOIN sExamination.tSubTypeMaster STM 
            ON STM.Id = SM.SubTypeId
        WHERE E.ParticipantSourceId = EC.EmpId
            AND E.ParticipantSourceTypeId = EC.EmpTypeId
			AND E.StatusId = 4
            AND ISNULL(V.BMI,0) > 0
            AND (
                    @lLatestVitalDisplayConfigVal = 'True'
                    OR (@lLatestVitalDisplayConfigVal = 'False'
                        AND STM.MainTypeId <> 8)
                )
        ORDER BY E.ExaminationDate DESC
    ) BMI

    ---------------------------------------------------------
    -- Latest Blood Pressure
    ---------------------------------------------------------
    OUTER APPLY
    (
        SELECT TOP 1 
            V.BloodPressureSystolic,
            V.BloodPressureDiastolic
        FROM sExamination.tExamination E
        INNER JOIN sExamination.tVital V 
            ON V.SourceId = E.Id
        INNER JOIN sExamination.tSetupMaster SM 
            ON SM.Id = E.SetupId
        INNER JOIN sExamination.tSubTypeMaster STM 
            ON STM.Id = SM.SubTypeId
        WHERE E.ParticipantSourceId = EC.EmpId
            AND E.ParticipantSourceTypeId = EC.EmpTypeId
			AND E.StatusId = 4
            AND ISNULL(V.BloodPressureSystolic,0) > 0
            AND ISNULL(V.BloodPressureDiastolic,0) > 0
            AND (
                    @lLatestVitalDisplayConfigVal = 'True'
                    OR (@lLatestVitalDisplayConfigVal = 'False'
                        AND STM.MainTypeId <> 8)
                )
        ORDER BY E.ExaminationDate DESC
    ) BP

    ---------------------------------------------------------
    -- Latest HBA1C
    ---------------------------------------------------------
    OUTER APPLY
    (
        SELECT TOP 1 
            TRD.ServiceValue AS HBA1C
        FROM sExamination.tTestRequestDetail TRD
        INNER JOIN sExamination.tTestRequest TR 
            ON TRD.TestRequestId = TR.Id
        INNER JOIN sOrderEntry.tTestDetail TD 
            ON TRD.TestDetailId = TD.Id
        INNER JOIN sOrderEntry.tTestParameterMaster TP 
            ON TD.TestParameterId = TP.Id
        INNER JOIN sExamination.tExamination E 
            ON TR.SourceId = E.Id
        WHERE E.ParticipantSourceId = EC.EmpId
            AND E.ParticipantSourceTypeId = EC.EmpTypeId
			AND E.StatusId = 4
            AND TP.StaticTestParameterId = 25
            AND ISNULL(TRD.ServiceValue,'') <> ''
        ORDER BY E.ExaminationDate DESC
    ) HBA1C

    ---------------------------------------------------------
    -- Latest LDL
    ---------------------------------------------------------
    OUTER APPLY
    (
        SELECT TOP 1 
            CONVERT(DECIMAL(8,2), TRD.ServiceValue) AS LDL
        FROM sExamination.tTestRequestDetail TRD
        INNER JOIN sExamination.tTestRequest TR 
            ON TRD.TestRequestId = TR.Id
        INNER JOIN sOrderEntry.tTestDetail TD 
            ON TRD.TestDetailId = TD.Id
        INNER JOIN sOrderEntry.tTestParameterMaster TP 
            ON TD.TestParameterId = TP.Id
        INNER JOIN sExamination.tExamination E 
            ON TR.SourceId = E.Id
        WHERE E.ParticipantSourceId = EC.EmpId
            AND E.ParticipantSourceTypeId = EC.EmpTypeId
			AND E.StatusId = 4
            AND TP.StaticTestParameterId = 34
            AND ISNULL(TRD.ServiceValue,'') <> ''
        ORDER BY E.ExaminationDate DESC
    ) LDL

	---------------------------------------------------------
	-- Survey Details
	---------------------------------------------------------
	OUTER APPLY
	(
		SELECT TOP 1
			ASD.AssignSurveyId,
			ASD.SourceTypeId,
			ASD.SourceId,
			ASD.TotalPoints,
			ASD.EarnedPoints,
			ASD.Percentage,
			ASD.IndicatorName
		FROM sSupport.tAssignSurveyDetail ASD
		INNER JOIN sSupport.tAssignSurveyMaster ASM ON ASD.AssignSurveyId = ASM.Id
		WHERE 
			ASD.SourceId = EC.EmpId
			AND ASD.SourceTypeId = EC.EmpTypeId
			AND ASM.SetupId = @rSetupId
			AND ASM.SurveyTypeId = 1 -- 1 Means for Examinations
		ORDER BY ASD.AssignSurveyId DESC
	) SUR

	---------------------------------------------------------
	-- Mental & General Health Percentage
	---------------------------------------------------------
	OUTER APPLY
	(
		SELECT
			MAX(CASE WHEN X.Code = 'Mental Health' 
					 THEN X.Percentage END) AS Stress,

			MAX(CASE WHEN X.Code = 'General Health' 
					 THEN X.Percentage END) AS LifeStyle
		FROM
		(
			SELECT 
				HSPGM.Code,
				CAST(
						(SUM(HSRD.EarnedPoints) * 100.0) 
						/ NULLIF(SUM(HSRD.TotalPoints),0)
					AS DECIMAL(10,2)) AS Percentage
			FROM sSupport.tHealthSurveyResponseMaster HSRM

			INNER JOIN sSupport.tHealthSurveyResponseDetail HSRD 
				ON HSRM.Id = HSRD.SurveyResponseId

			INNER JOIN sSupport.tHealthSurveyParameterMaster HSPM 
				ON HSPM.Id = HSRD.QuestionId

			INNER JOIN sSupport.tHealthSurveyParameterGroupMaster HSPGM 
				ON HSPGM.Id = HSPM.GroupId

			INNER JOIN sSupport.tAssignSurveyMaster ASM 
				ON ASM.Id = HSRM.AssignSurveyId

			INNER JOIN sSupport.tAssignSurveyDetail ASD 
				ON ASD.AssignSurveyId = ASM.Id

			WHERE 
				ASM.IsShowMarksDetails = 1
				AND HSRM.SourceId = EC.EmpId
				AND HSRM.OrgId = @rOrgId
				AND HSRD.TotalPoints <> 0
				AND ASD.SourceId = EC.EmpId
				AND ASD.SourceTypeId = EC.EmpTypeId
				AND ASD.AssignSurveyId = SUR.AssignSurveyId

			GROUP BY HSPGM.Code
		) X
	) MH
	
    ORDER BY EC.EmployeeCode

END
GO
PRINT N'Creating Procedure [sWellness].[pUpsertProgramParameterTrack]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pUpsertProgramParameterTrack]
(
    @ProgramParameterTrackList [sWellness].[ProgramParameterTrackTableType] READONLY,
	@Result BIT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    MERGE [sWellness].[tProgramParameterTrack] AS TARGET
    USING @ProgramParameterTrackList AS SOURCE
    ON TARGET.ProgramParticipantId = SOURCE.ProgramParticipantId
       AND TARGET.ProgramParameterId = SOURCE.ProgramParameterId
       AND TARGET.InputId = SOURCE.InputId
       AND TARGET.InputDate = SOURCE.InputDate

    WHEN MATCHED THEN
        UPDATE SET
            TARGET.ProgramParameterValue = SOURCE.ProgramParameterValue,
            TARGET.UpdatedUserId         = SOURCE.CreatedUserId,
            TARGET.UpdatedDatetime       = GETUTCDATE()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ProgramParticipantId,
            ProgramParameterId,
            InputId,
            InputDate,
            ProgramParameterValue,
            CreatedUserId,
            CreatedDatetime
        )
        VALUES
        (
            SOURCE.ProgramParticipantId,
            SOURCE.ProgramParameterId,
            SOURCE.InputId,
            SOURCE.InputDate,
            SOURCE.ProgramParameterValue,
            SOURCE.CreatedUserId,
            GETUTCDATE()
        );
		SET @Result = 1;
END
GO
PRINT N'Creating Procedure [sWellness].[pVisitPurposeMasterAddUpdate]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pVisitPurposeMasterAddUpdate]
	@rId bigint=0,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rIsObsolete bit,	
	@rOrgId smallint,
	@rCreatedUserId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN TRY

		IF  EXISTS (SELECT 1 FROM [sWellness].[tWellnessVisitPurposeMaster] WHERE  UPPER(Code) = UPPER(@rCode)  and Id<>@rId)
		BEGIN	 
			SELECT -102 AS RESULT
			return
		END
		IF  EXISTS (SELECT 1 FROM [sWellness].[tWellnessVisitPurposeMaster] WHERE UPPER(Title) = UPPER(@rTitle)  and Id<>@rId)
		BEGIN	 
			SELECT -103 AS RESULT
			return
		END
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF(@rId=0)
					BEGIN
					EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sWellness.tWellnessVisitPurposeMaster', 0, 101, 1,@outNextNumber = @lNextNumber output

					INSERT INTO [sWellness].[tWellnessVisitPurposeMaster]
							(
							Id,
							Code,
							Title,
							IsObsolete,
							CreatedUserId,
							CreatedDateTime
							)
							values
							(
							@lNextNumber,
							@rCode,
							@rTitle,
							@rIsObsolete,
							@rCreatedUserId,
							sCommon.fGetDate()
							)

					--SELECT @lNextNumber AS RESULT
	 
					END
			ELse
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sWellness].[tWellnessVisitPurposeMaster] WHERE Id=@rId)
						BEGIN	 
							SELECT -101 AS RESULT
							return
						END
						Update [sWellness].[tWellnessVisitPurposeMaster]
							Set
								Code=@rCode,
								Title =@rTitle,
								IsObsolete=@rIsObsolete,
								UpdatedUserId=@rCreatedUserId,
								UpdatedDateTime=sCommon.fGetDate()
							Where Id=@rId

							SET @lNextNumber=@rId
				END
		COMMIT TRAN
		Select @lNextNumber as Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END
GO
PRINT N'Creating Procedure [sWellness].[pVisitPurposeMasterDelete]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pVisitPurposeMasterDelete]
	@rId int
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	if exists (select 1 from [sWellness].[tWellnessVisitPurposeMaster] where Id = @rId )
	begin	
		BEGIN TRANSACTION  
			Delete FROM [sWellness].[tWellnessVisitPurposeMaster] Where Id=@rId 			
			COMMIT TRANSACTION
			Select 1 as Result
	end
	else
	begin
		select -101 as Result
	end
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pVisitPurposeMasterGet]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pVisitPurposeMasterGet]
	@rId Int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		
	IF EXISTS (SELECT 1 FROM [sWellness].[tWellnessVisitPurposeMaster]  
	WHERE
		Id = @rId)
		BEGIN	

			SELECT Id,Code,Title,IsObsolete FROM [sWellness].[tWellnessVisitPurposeMaster]   
			Where
				Id = @rId	
		END
	ELSE
	BEGIN
		SELECT -101 AS Result
	END
END
GO
PRINT N'Creating Procedure [sWellness].[pVisitPurposeMasterGetList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pVisitPurposeMasterGetList]
	@rCode nvarchar(50),
	@rTitle nvarchar(200)
AS
BEGIN		
		Select Id,Code,Title,
			CASE WHEN IsObsolete = 0 THEN 'Active' ELSE 'InActive' END AS Status,
			IsObsolete
			FROM
					[sWellness].[tWellnessVisitPurposeMaster]
			Where 
				 (Code like '%'+@rCode+'%' or ISNULL(@rCode,'')='')
			 AND (Title like '%'+@rTitle+'%' or ISNULL(@rTitle,'')='')
			ORDER BY 
				Id
			DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessActivityTaskMasterDelete]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pWellnessActivityTaskMasterDelete]
	@rId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	IF EXISTS (SELECT 1 from [sWellness].[tWellnessActivityTaskMaster] where Id = @rId)
	BEGIN	
		BEGIN TRANSACTION  
			Delete FROM [sWellness].[tWellnessActivityTaskMaster] Where Id = @rId
			COMMIT TRANSACTION
			SELECT 1 as Result
	END
	ELSE
	BEGIN
		SELECT -101 AS Result
	END
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessAppointmenScheduleListGet]...';


GO
 
CREATE OR ALTER PROCEDURE [sWellness].[pWellnessAppointmenScheduleListGet]  
 @rOrgId [int],  
 @rEmployeeId [bigint],  
 @rStoreLocationId [int],  
 @rIsObsolete [bit],  
 @rIsClosed [bit],  
 @rMainTypeId int,  
 @rSetupId int,  
 @rRegistrationDate date,  
 @rDoctorEmployeeId bigint=0
AS  
BEGIN  
declare @LocationId int  

 select  @LocationId=LocationId from shrm.tEmployeeMaster em  
      inner join shrm.temployeejobdetail ejd on ejd.employeeid=em.id  
      inner join sip.tstorelocationmaster SLM on SLM.LocationId=ejd.EmployeelocationId  
      where EM.Id=@rEmployeeId and SLM.Id=@rStoreLocationId;   

  Begin
   exec [sHrm].[pEmployeeFamilyNameRelationGet] @rOrgId=@rOrgId,@rMainTypeId=@rMainTypeId,@rEmployeeId=@rEmployeeId,@rEmployeeCode=N'',@rLocationId=@LocationId     
  
  select d.EmployeeId,   ISNULL(e.EmployeePrefix + ' ', ' ') + 
(e.FirstName + ISNULL(' ' + e.MiddleName, '') + ' ' + e.LastName) AS Name 
   from sCwb.tDoctorMaster d   
   inner join sHrm.tEmployeeMaster e on d.EmployeeId = e.Id   
   inner join sCwb.tDoctorStoreLocation S on d.EmployeeId = S.EmployeeId   
   where S.SubLocationId = @rStoreLocationId and e.StatusId = 7    
     
   select Id,Title from sExamination.vExtSetupMaster   
   where IsObsolete = @rIsObsolete AND IsClosed = @rIsClosed   
   AND MainTypeId = @rMainTypeId AND OrgId = @rOrgId AND ( StoreLocationId = @rStoreLocationId OR  StoreLocationId =  0);  
  
   select (Left(convert(varchar(5),TSM.FromTime,108),8) + '-' + Left(convert(varchar(5),TSM.ToTime,108),8)) as Title,TSM.Id ,A.ApprovalStatusId  
   FROM [sAppointment].[tTimeSlotMaster] TSM   
   inner join [sAppointment].[tTimeSlotSetup] MT on MT.Id=TSM.TimeSlotSetupId    
   left join sWellness.tAppointment A ON TSM.Id = A.TimeSlotId  
   where TSM.TimeSlotDate=@rRegistrationDate and (MT.MainTypeId = @rMainTypeId or MT.MainTypeId=0)   
   and TSM.Id not IN (Select Isnull(TimeSlotId,0) From sAppointment.tAppointment where AppointmentDate=@rRegistrationDate)
   and MT.SourceTypeId=10171 and TSM.StoreLocationId=@rStoreLocationId   
   and TSM.OrgId=@rOrgId AND (MT.SetupId=@rSetupId or MT.SetupId=0 )   
   AND (MT.DoctorEmployeeId=@rDoctorEmployeeId or MT.DoctorEmployeeId=0 )   
   and ((TSM.FromTime>=CONVERT(TIME, sCommon.fGetDate()) AND CONVERT(date, sCommon.fGetDate())=@rRegistrationDate) OR CONVERT(date, sCommon.fGetDate())<@rRegistrationDate)  
   order by TSM.FromTime
  End 
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessConsultationDocumentAdd]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationDocumentAdd]
	@rId int=0,
	@rConsultationId bigint,
	@rFileName nvarchar(100),
	@rConfigId int,
	@rIsObsolete bit=0,
	@rUserId bigint
AS
BEGIN
	SET NOCOUNT ON;
			
			INSERT INTO [sWellness].[tConsultationDocuments]
			(
			ConsultationId,
			ConfigId,
			FileName,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
			)
			VALUES
			(
			@rConsultationId,
			@rConfigId,
			@rFileName,
			@rIsObsolete,
			@rUserId,
			sCommon.fGetDate()
			)
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessConsultationDocumentAllDelete]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationDocumentAllDelete]
	@rConsultationId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	if exists (select 1 from sWellness.tConsultationDocuments where ConsultationId=@rConsultationId)
	begin			
			Delete FROM sWellness.tConsultationDocuments where ConsultationId=@rConsultationId		
			
			Select 1 as Result
	end
	else
	begin
		select -101 as Result
	end
	END TRY
	BEGIN CATCH
		select -105 as Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessConsultationDocumentDelete]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationDocumentDelete]
	@rId int,
	@rConsultationId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	if exists (select 1 from sWellness.tConsultationDocuments where Id = @rId and ConsultationId=@rConsultationId)
	begin			
			Delete FROM sWellness.tConsultationDocuments where Id = @rId and ConsultationId=@rConsultationId		
			
			Select 1 as Result
	end
	else
	begin
		select -101 as Result
	end
	END TRY
	BEGIN CATCH
		select -105 as Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessConsultationDocumentsGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationDocumentsGet]
	@rConsultationId bigint, 
	@rOrgId int, 
	@rConfigId int
AS
BEGIN
	SET NOCOUNT ON;

	
	declare @res varchar(max)='',@delmessage varchar(100)='''Are you sure to delete this item?'''
	select CD.Id,CD.ConsultationId,CD.FileName,CD.ConfigId,'../../../Content/' + convert(varchar,@rOrgId) + '/WellnessConsultationDocuments/'   
			+ convert(varchar,CD.ConsultationId) + '/' + FileName as FilePath  
			from sWellness.tConsultationDocuments CD
			where CD.ConsultationId = @rConsultationId and CD.ConfigId=@rConfigId
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessConsultationList]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationList]
(
	@rOrgId INT,  
	@rSetupId INT, 
	@rConsultationNo VARCHAR(300) = NULL,
	@rDoctor VARCHAR(200),
	@rFromDate DATETIME = null,
	@rToDate DATETIME = null,
	@rCode NVARCHAR (20),  
	@rName NVARCHAR(50),
	@rCaseCauseId INT,
	@rEmployeeTypeId INT,
	@rStatusId int = 0,
	@rStoreLocationId INT,	
	@rEmployeeId BIGINT = 0,
	@SortColumnName NVARCHAR(MAX)= '',
	@IsAscendingOrder BIT= 0,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@GlobalSearch NVARCHAR(MAX)= ''
)
AS
SET NOCOUNT ON
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	
	SET @rFromDate = ISNULL (@rFromDate, '')
	SET @rToDate = ISNULL (@rToDate, '')

	
	;WITH PageNumbers AS(
	select 
	ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 0 THEN t.ConsultationNumber END DESC,
					 CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 1 THEN t.ConsultationNumber END,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN t.ParticipantCode END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN t.ParticipantCode END,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN t.ParticipantName END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN t.ParticipantName END,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 0 THEN t.CreatedUserName END DESC,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 1 THEN t.CreatedUserName END,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 0 THEN t.CauseName END DESC,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 1 THEN t.CauseName END,
					 CASE WHEN @SortColumnName = '' THEN t.Id END DESC
	) PageId,
	COUNT(*) OVER() 'RecordCount',
	* from (
		SELECT 
			Cons.Id as Id,
			Cons.ConsultationNumber,
			Cons.ConsultationDate,
			CONVERT(VARCHAR,Cons.ConsultationDate,103) AS  ConsultationDateStr,
			ISNULL(PM.Title,'Not Applicable') AS ProgramName,
			Cons.CauseId,
			ISNULL(WVPM.Title,'-') AS CauseName,
			SM.RoundNumber,	
			SM.Title AS Setup,
			EM.Code AS ParticipantCode,
		    EM.FirstName + ' ' + EM.LastName AS ParticipantName,
			[Status] = SS.Title,
			ODP.Title AS Department,
			StoreLocation = SLM.Title,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id = Cons.CreatedUserId) as CreatedUserName,
			CASE WHEN ISNULL(Users.DisplayTitle,'') <> '' THEN Users.DisplayTitle ELSE ISNULL(EM1.FirstName,'') + ' ' + ISNULL( EM1.LastName,'') end as DoctorName,
			ISNULL(ETM.Title,'-') AS EmployeeTypeName
		FROM
			sWellness.tWellnessConsultation Cons
		LEFT JOIN 
			sHrm.tEmployeeMaster EM on Cons.ParticipantSourceId = EM.Id and Cons.ParticipantSourceTypeId = 95
		LEFT JOIN 
			sExamination.tStatusMaster SS on Cons.StatusId = SS.Id
		LEFT JOIN 
			sHrm.tEmployeeMaster EM1 ON EM1.Id=Cons.DoctorEmployeeId
		LEFT JOIN 
			sSecurity.tUser Users on Users.Id = Cons.CreatedUserId
		INNER JOIN 
			sWellness.tWellnessVisitPurposeMaster WVPM on WVPM.Id = Cons.CauseId
		INNER JOIN 
			sExamination.tSetupMaster SM on Cons.SetupId = SM.Id
		INNER JOIN 
			sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
		INNER JOIN 
			sIp.tStoreLocationMaster SLM on SLM.Id = Cons.StoreLocationId
		INNER JOIN
			sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN
			sCommon.tOrganizationDepartmentMaster ODP ON ODP.Id = EJD.OrganizationDepartmentId
		LEFT JOIN
			sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId	
		LEFT JOIN	
			sWellness.tMHIScore MHI  ON MHI.EmployeeId = Cons.ParticipantSourceId
		LEFT JOIN
			sWellness.tProgramMaster PM ON PM.Id = MHI.ProgramId
		WHERE 
			Cons.OrgId = @rOrgId	
		AND 
			ISNULL(Cons.IsCancel,0) = 0
		AND 
			(EM.Code LIKE @rCode + '%')    
		AND 
			(EM.FirstName LIKE @rName + '%'OR @rName = '')			
		AND 
			((Cons.SetupId = @rSetupId) OR (@rSetupId = 0))
		AND 
			((EM.StatusId = @rStatusId) OR (@rStatusId = 0) OR (@rStatusId = -1))
		AND 
			(Cons.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND 
			((Cons.ConsultationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND 
			((Cons.ConsultationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		AND
			((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = -1))
		AND 
			(Cons.CauseId = @rCaseCauseId OR @rCaseCauseId = 0 OR @rCaseCauseId = -1)
		AND 
			(Cons.ConsultationNumber LIKE '%' + @rConsultationNo OR ISNULL(@rConsultationNo,'')='')
	) t where (t.DoctorName like @rDoctor + '%' or @rDoctor ='')
	AND (ISNULL(@GlobalSearch,'') = '' OR ISNULL(t.ConsultationDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.CreatedUserName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.CauseName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR PageId  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessConsultationRemove]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationRemove]
	@rSourceId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION	   
		DELETE FROM sWellness.tWellnessConsultation Where Id = @rSourceId	   
		DELETE FROM sWellness.tGeneralTemplateConsultationDetail Where GeneralTemplateConsultationId IN
		(
			select Id from sWellness.tGeneralTemplateConsultation where SourceId = @rSourceId
		)
		DELETE FROM sWellness.tGeneralTemplateConsultation Where SourceId = @rSourceId
		DELETE FROM sWellness.tConsultationTestRequestDetail Where TestRequestId IN
		(
			select Id from sWellness.tConsultationTestRequest where SourceId = @rSourceId
		)
		DELETE FROM sWellness.tConsultationTestRequest Where SourceId = @rSourceId
		DELETE FROM sWellness.tAssignedActivity Where ConsultationId = @rSourceId
		DELETE FROM sWellness.tConsultationAdditionalFieldDetails Where AdditionalFieldId IN
		(
			select Id from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rSourceId
		)
		DELETE FROM sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rSourceId
		
		update sWellness.tAppointment set ExaminationId=0 where ExaminationId=@rSourceId

		SELECT 1 AS Result	   
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessRegistrationAdd]...';


GO

    
CREATE OR ALTER PROCEDURE [sWellness].[pWellnessRegistrationAdd]    
@rId bigint,    
@rOrgId smallint,    
@rParticipantSourceTypeId smallint,    
@rParticipantSourceId bigint,    
@rSetupId int,    
@rStatusId int=0,    
@rRegistrationDate date,    
@rDoctorEmployeeId bigint,    
@rStoreLocationId int,    
@rCauseId int,    
@rPulse smallint,    
@rTemperature decimal(5, 2),    
@rBloodPressureSystolic int,    
@rBloodPressureDiastolic smallint,    
@rRespiration int,    
@rHeight int,    
@rBodyWeight decimal(5, 2),    
@rBMI decimal(5, 2),    
@rInhalation decimal(5, 2) = null,    
@rExhalation decimal(5, 2) = null,    
@rChestExpansion decimal(5, 2) = null,    
@rAbdominalGirth decimal(5, 2),    
@rElbowWidth decimal(5, 2),    
@rWaist decimal(5, 2),    
@rHip decimal(5, 2),    
@rRemark nvarchar(300),    
@rExaminationId bigint=0,    
@rCreatedUserId bigint,    
@rOtherName varchar(200)=null,    
@rAge int = null,    
@rMonth tinyint = null,    
@rGenderId tinyint = null,    
@rTimeslotId int = null,    
@rFromTime nvarchar(100) = '',    
@rToTime nvarchar(100) = ''    ,
@rSPO2 decimal(5,2) = null,
@rAppointmentId BIGINT =0,
@rCompliantRemark NVARCHAR(MAX),
@rLDL decimal(5, 2) = null,
@rHBA1C decimal(5, 2) = null
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON     
BEGIN    
 DECLARE @lNextNumber BIGINT    
 IF (@rId = 0)    
 BEGIN    
  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sWellness.tWellnessRegistration', 0, 1, 1,@outNextNumber = @lNextNumber output    
      
  DECLARE @loNextNumber nVarchar(20)    
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1023,    
  @rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT    
      
  SET @loNextNumber = ISNULL(@loNextNumber, '-300')     
  IF @loNextNumber = '-300'    
  BEGIN     
   SELECT -300 AS Result, '' AS Number, 0 AS Id     
   RETURN    
  END    
  IF @rParticipantSourceTypeId != 1009    
  BEGIN    
   Declare @lAge int;    
   select @lAge = Case When @rParticipantSourceTypeId = 1001 Then (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeeFamilyDetails where Id = @rParticipantSourceId
  
)    
         ELSE (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeePersonalDetail where EmployeeId = @rParticipantSourceId) END    
   IF @lAge != @rAge    
   BEGIN    
    SELECT -3 AS Result, '' AS Number, 0 AS Id    
    RETURN    
   END    
  END    
      
  INSERT INTO [sWellness].[tWellnessRegistration]    
  (    
   Id,OrgId,ParticipantSourceTypeId,ParticipantSourceId,SetupId,StatusId,RegistrationDate,    
   DoctorEmployeeId,StoreLocationId,CauseId,Pulse,Temperature,BloodPressureSystolic,    
   BloodPressureDiastolic,Respiration,Height,BodyWeight,BMI,ChestExpansion,AbdominalGirth,    
   ElbowWidth,Waist,Hip,Remark,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OtherName,    
   RegistrationNumber,Age,Months,GenderId,ChestExpansionExhalation,ChestExpansionInhalation,TimeslotId,FromTime,ToTime,SPo2,
   AppointmentId,CompliantRemark,LDL,HBA1C
  )    
  VALUES    
  (    
   @lNextNumber,@rOrgId,@rParticipantSourceTypeId,@rParticipantSourceId,@rSetupId,@rStatusId,    
   @rRegistrationDate,@rDoctorEmployeeId,@rStoreLocationId,@rCauseId,@rPulse,@rTemperature,    
   @rBloodPressureSystolic,@rBloodPressureDiastolic,@rRespiration,@rHeight,@rBodyWeight,@rBMI,    
   @rChestExpansion,@rAbdominalGirth,@rElbowWidth,@rWaist,@rHip,@rRemark,@rCreatedUserId,    
   sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),@rOtherName,@loNextNumber,@rAge,    
   @rMonth,@rGenderId,@rExhalation,@rInhalation,@rTimeslotId,@rFromTime,@rToTime,@rSPO2,
   @rAppointmentId,@rCompliantRemark,@rLDL,@rHBA1C
  )    
  SELECT @lNextNumber AS RESULT    
 END    
 ELSE    
 BEGIN    
  SET @lNextNumber=@rId    
  UPDATE [sWellness].[tWellnessRegistration] SET @lNextNumber=@rId,OrgId=@rOrgId,    
  ParticipantSourceTypeId=@rParticipantSourceTypeId,ParticipantSourceId=@rParticipantSourceId,    
  SetupId=@rSetupId,RegistrationDate=@rRegistrationDate,DoctorEmployeeId=@rDoctorEmployeeId,    
  StoreLocationId=@rStoreLocationId,CauseId=@rCauseId,Pulse=@rPulse,Temperature=@rTemperature,    
  BloodPressureSystolic=@rBloodPressureSystolic,BloodPressureDiastolic=@rBloodPressureDiastolic,    
  Respiration=@rRespiration,Height=@rHeight,BodyWeight=@rBodyWeight,BMI=@rBMI,    
  ChestExpansion=@rChestExpansion,AbdominalGirth=@rAbdominalGirth,ElbowWidth=@rElbowWidth,    
  Waist=@rWaist,Hip=@rHip,Remark=@rRemark,UpdatedUserId=@rCreatedUserId,    
  UpdatedDateTime=sCommon.fGetDate(),OtherName = @rOtherName,Age = @rAge,    
  Months = @rMonth,GenderId = @rGenderId,ChestExpansionExhalation=@rExhalation,    
  ChestExpansionInhalation=@rInhalation,FromTime=@rFromTime,ToTime=@rToTime ,SPo2=@rSPO2,
  CompliantRemark=@rCompliantRemark,LDL=@rLDL,HBA1C=@rHBA1C
  WHERE ID=@rId    
 END    
 SELECT @lNextNumber AS RESULT      
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessRegistrationGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessRegistrationGet]  
@rId  bigint= 0,     
@rOrgId smallint,   
@rFromDate datetime='',  
@rToDate datetime='',  
@rStoreLocationId int=0,  
@rSetupId int=0,  
@rDoctorEmployeeId bigint,  
@rEmployeeCode nvarchar(20)='',  
@rEmployeeName nvarchar(100)='',  
@rCauseId int=0  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)  
   
 SELECT R.Id,R.OrgId,R.ParticipantSourceTypeId,R.ParticipantSourceId,  
 R.SetupId,ISNULL(R.StatusId,0) AS StatusId,R.RegistrationDate,R.DoctorEmployeeId,  
 R.StoreLocationId,ISNull(R.CauseId,0) AS  CauseId,Isnull(R.Pulse,0) AS Pulse,  
 ISNULL(R.Temperature,0) AS Temperature,  
 ISNULL(R.BloodPressureSystolic,0) AS BloodPressureSystolic,  
 ISNULL(R.BloodPressureDiastolic,0) AS BloodPressureDiastolic,  
 ISNULL(R.Respiration,0) AS Respiration,ISNULL(R.Height,0) AS Height,  
 ISNULL(R.BodyWeight,0) AS BodyWeight,ISNULL(R.BMI,0) AS BMI,  
 ISNULL(R.ChestExpansion,0) AS ChestExpansion,  
 ISNULL(R.AbdominalGirth,0) AS AbdominalGirth ,  
 ISNULL(R.ElbowWidth,0 ) AS ElbowWidth,ISNULL(R.Waist,0) AS Waist,  
 ISNULL(R.Hip,0) AS Hip,R.Remark,VSM.MainTypeId,VSM.MainType,  
 VSM.Title AS Setup,Isnull(ODM.Id,0) AS DepartmentId,  
 EM1.FirstName + ISNULL(' ' + EM1.MiddleName, '') + ' ' + ISNULL(EM1.LastName,'') AS DoctorName,  
 CASE WHEN R.ParticipantSourceTypeId = 95 THEN ISNULL(EM.Id,0) WHEN R.ParticipantSourceTypeId = 1009 THEN ISNULL(CSB.Id,0) ELSE EFD.Id END AS DependentId,  
 CASE WHEN R.ParticipantSourceTypeId = 95 THEN EM.Code WHEN R.ParticipantSourceTypeId = 1009 THEN CSB.Code ELSE EM2.Code END AS PatientCode,  
 CASE WHEN R.ParticipantSourceTypeId = 95 THEN (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + Isnull(EM.LastName,''))   
 when R.OtherName != '' and R.ParticipantSourceTypeId = 1009 then isnull(R.OtherName,'')  
 WHEN R.ParticipantSourceTypeId = 1009 THEN (CSB.FirstName + ISNULL(' ' + CSB.MiddleName, '') + ' ' + CSB.LastName) ELSE EFD.Name END AS PatientName,  
 isnull(R.OtherName,'') as OtherName,isnull(R.RegistrationNumber,'') as RegistrationNumber,  
 isnull(R.Age,0) as Age,isnull(R.Months,0) as Months,isnull(R.GenderId,0) as GenderId,isnull(R.ChestExpansionInhalation,0) as ChestExpansionInhalation,  
 isnull(R.ChestExpansionExhalation,0) as ChestExpansionExhalation,  
 CASE WHEN R.ParticipantSourceTypeId = 1009 THEN ISNULL(CSB.MobileNo,0) ELSE '' END AS MobileNo,  
 CASE WHEN R.ParticipantSourceTypeId = 1009 THEN ISNULL(CSB.UIDNumber,0) ELSE '' END AS UIDNumber,  
 Isnull(R.TimeSlotId,0) as TimeSlotId,  
 (Left(convert(varchar,TSM.FromTime,108),5) + '-' + Left(convert(varchar,TSM.ToTime,108),5)) as TimeSlot,  
 isnull(R.FromTime,'') as FromTime,  
 isnull(R.ToTime,'') as ToTime,
  isnull(R.SPo2,0) as SPO2,isnull(R.LDL,0) as LDL,isnull(R.HBA1C,0) as HBA1C,
  ISNULL(R.AppointmentId,0) as AppointmentId,
  R.CompliantRemark
 FROM sWellness.tWellnessRegistration R LEFT JOIN sHrm.tEmployeeFamilyDetails EFD  
 ON EFD.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster  EM2 ON EM2.Id = EFD.EmployeeId AND R.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster  EM ON EM.Id = R.ParticipantSourceId  AND R.ParticipantSourceTypeId = 95   
 LEFT JOIN sHrm.tCsrBenefiterMaster  CSB ON CSB.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1009  
 LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = R.DoctorEmployeeId  
 LEFT JOIN sHrm.tEmployeeJobDetail  EJD ON EJD.EmployeeId = EM.Id  
 LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId  
 INNER JOIN sExamination.vExtSetupMaster AS VSM ON VSM.Id = R.SetupId  
 LEFT JOIN sAppointment.tTimeSlotMaster TSM On TSM.Id=R.TimeslotId  
 where ((R.Id=@rId) OR (@rId=0)) AND R.OrgId=@rOrgId  
 AND ((R.registrationDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))  
 AND ((registrationDate<=@rTodate) OR(ISNULL(@rTodate,'')=''))  
 AND ((R.SetupId = @rSetupId) OR (@rSetupId = 0))  
 AND ((R.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))  
 AND ((R.DoctorEmployeeId = @rDoctorEmployeeId) OR (@rDoctorEmployeeId = 0))  
 AND ((EM.Code = @rEmployeeCode) OR (CSB.Code=@rEmployeeCode) OR (EM2.Code=@rEmployeeCode) OR (ISNULL(@rEmployeeCode,'') = ''))  
 AND ((EM.FirstName like @rEmployeeName + '%') OR (CSB.FirstName like @rEmployeeName + '%')  
 OR (EFD.Name like @rEmployeeName + '%') or R.OtherName like @rEmployeeName + '%' OR (Isnull(@rEmployeeName,'')= ''))  
 and(R.CauseId=@rCauseId or @rCauseId=0)  
 order by R.Id desc  
END
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsUpdate]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsUpdate]    
   @rEmpCode NVARCHAR(100),    
   @TicketNumber NVARCHAR(50),    
   @AssignedDoctorId BIGINT = NULL,    
   @IntimationAssignedDoctorId INT = NULL,    
   @rOrgId INT = NULL,    
   @rCreatedUserId BIGINT = NULL  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        DECLARE @CurrentDateTime DATETIME = GETUTCDATE();  
        DECLARE @IntimationDetailId BIGINT;  
        DECLARE @PreviousDoctorId BIGINT;  
        DECLARE @FinalDoctorId BIGINT;
        DECLARE @FinalIntimationDoctorId INT;
  
        -- Find the existing Intimation record  
        SELECT @IntimationDetailId = Id,  
               @PreviousDoctorId = AssignedDoctorId  
        FROM [sHospitalization].[tIntimationDetails]  
        WHERE EmpCode = @rEmpCode  
          AND TicketNumber = @TicketNumber  
          AND OrgId = @rOrgId;  
  
        IF @IntimationDetailId IS NULL  
        BEGIN  
            RAISERROR('Intimation record not found for Employee %s and Ticket %s', 16, 1, @rEmpCode, @TicketNumber);  
            RETURN;  
        END  
  
        -- Determine the doctor to assign
        IF @AssignedDoctorId IS NOT NULL AND @AssignedDoctorId > 0
        BEGIN
            -- Use provided doctor
            SET @FinalDoctorId = @AssignedDoctorId;
            SET @FinalIntimationDoctorId = @IntimationAssignedDoctorId;
        END
        ELSE
        BEGIN
            -- Need to determine doctor based on business rules
            -- This is where you'd implement the same logic as your C# code
            -- For now, let's implement a simple round-robin for central doctors
            
            DECLARE @NextDoctorId BIGINT;
            DECLARE @NextDoctorIndexId INT;
            
            -- Call a helper procedure to get the next central doctor
            EXEC sHospitalization.pGetNextCentralDoctor 
                @rOrgId,
                @NextDoctorId OUTPUT,
                @NextDoctorIndexId OUTPUT;
            
            SET @FinalDoctorId = @NextDoctorId;
            SET @FinalIntimationDoctorId = @NextDoctorIndexId;
        END
  
        -- Update main record  
        UPDATE [sHospitalization].[tIntimationDetails]  
        SET  
            AssignedDoctorId = @FinalDoctorId,  
            IntimationAssignedDoctorId = @FinalIntimationDoctorId,  
            UpdatedUserId = @rCreatedUserId,  
            UpdatedDateTime = @CurrentDateTime  
        WHERE Id = @IntimationDetailId;  
  
        -- Always insert log if doctor was assigned  
        IF @FinalDoctorId IS NOT NULL  
        BEGIN  
            DECLARE @lAssignLogId BIGINT;  
  
            EXEC scommon.ptablerowidget   
                @rOrgId = @rOrgId,  
                @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',  
                @rIsCurrentNumber = 0,  
                @rSeed = 1,  
                @rIncrement = 1,  
                @outNextNumber = @lAssignLogId OUTPUT;  
  
            -- Insert log  
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]  
            (  
                Id,   
                OrgId,   
                HospitalizationIntimationDetailId,   
                PreviousDoctorEmployeeId,   
                NewDoctorEmployeeId,  
                AssignedDate,   
                TicketNumber,   
                CreatedUserId,   
                CreatedDateTime,   
                UpdatedUserId,   
                UpdatedDateTime,   
                Status  
            )  
            VALUES  
            (  
                @lAssignLogId,   
                @rOrgId,   
                @IntimationDetailId,   
                @PreviousDoctorId,   
                @FinalDoctorId,  
                @CurrentDateTime,   
                @TicketNumber,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                'Open'  
            );  
        END  
  
        -- Return updated record id  
        SELECT @IntimationDetailId AS updatedrecordid;  
  
    END TRY  
    BEGIN CATCH  
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();  
        RAISERROR(@ErrorMessage, 16, 1);  
    END CATCH  
END;
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramMHIScore]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScore]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rSubmitFrom SMALLINT,
    @rBMI NUMERIC(10,2) = NULL,
    @rSystolicBP NUMERIC(10,0)=NULL,
    @rDiastolicBP NUMERIC(10,0)=NULL,
    @rHBA1C NUMERIC(10,2)=NULL,
    @rLDL NUMERIC(10,2)=NULL,
    @rStress NUMERIC(10,2)=NULL,
    @rLifeStyle NUMERIC(10,2)=NULL,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;
	BEGIN TRY
        BEGIN TRANSACTION
			CREATE TABLE #TempParameterRange
			(
				StaticHIPId INT, ParameterName VARCHAR(100), MinimumRange NUMERIC(10,5), MaximumRange NUMERIC(10,5), Score SMALLINT, Category NVARCHAR(100), GenderId SMALLINT
			)

			INSERT INTO #TempParameterRange 
			SELECT 
				HIPM.StaticHealthIndexParameterId, HIPM.Title, HIPD.FromValue, HIPD.ToValue, HIPD.Points, HIPD.DiagnosisRemark,HIPD.GenderId
			FROM 
				[sExamination].[tHealthIndexParameterMaster] HIPM
			INNER JOIN
				[sExamination].[tHealthIndexParameterDetail] HIPD
			ON
				HIPD.HealthIndexParameterId = HIPM.Id
			WHERE 
				StaticHealthIndexParameterId IN (1,2,5,17,23)


			DECLARE @DepartmentId INT, @GenderId SMALLINT,
					@BMICategory NVARCHAR(30) = NULL, @BMIScore SMALLINT,
					@HBA1CCategory NVARCHAR(30) = NULL, @HBA1CScore SMALLINT,
					@LDLCategory NVARCHAR(30) = NULL, @LDLScore SMALLINT,
					@SystolicCategory NVARCHAR(30) = NULL, @SystolicScore SMALLINT,
					@DiastolicCategory NVARCHAR(30) = NULL, @DiastolicScore SMALLINT,
					@BPCategory NVARCHAR(30) = NULL, @BPScore SMALLINT = NULL,
					@BiometricsCategory VARCHAR(30) = NULL, @BiometricsCategoryIndex SMALLINT = NULL,
					@LifeStyleCategory VARCHAR(30) = NULL, @LifeStyleIndex SMALLINT = NULL,
					@StressCategory VARCHAR(30) = NULL, @StressIndex SMALLINT = NULL,
					@SurveyCategory VARCHAR(30) = NULL, @SurveyIndex SMALLINT = NULL,
					@MHICategory VARCHAR(30) = NULL, @MHIIndex SMALLINT = NULL,
					@TotalBiometrics INT = NULL, @BiometricScore DECIMAL(10,2) = NULL

			SET @DepartmentId = (SELECT TOP 1 DepartmentId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);
			SET @GenderId = (SELECT TOP 1 GenderId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);

			-- Add OR UPDATE Biometric parameter not included biometric category & survey & mhi category
			IF (@rSubmitFrom = 1 OR @rSubmitFrom = 2)
			BEGIN
				-- BMI
				IF(@rBMI IS NOT NULL AND @rBMI > 0 )
				BEGIN
					SELECT TOP 1 @BMICategory = Category, @BMIScore = Score FROM #TempParameterRange WHERE StaticHIPId = 1 AND @rBMI >= MinimumRange AND @rBMI <= MaximumRange AND GenderId = @GenderId
				END

				-- HBA1C
				IF(@rHBA1C IS NOT NULL AND @rHBA1C > 0 )
				BEGIN
					SELECT TOP 1 @HBA1CCategory = Category, @HBA1CScore = Score FROM #TempParameterRange WHERE StaticHIPId = 2 AND @rHBA1C >= MinimumRange AND @rHBA1C <= MaximumRange AND GenderId = @GenderId
				END
				-- LDL
				IF(@rLDL IS NOT NULL AND @rLDL > 0 )
				BEGIN
					SELECT TOP 1 @LDLCategory = Category, @LDLScore = Score FROM #TempParameterRange WHERE StaticHIPId = 5 AND @rLDL >= MinimumRange AND @rLDL <= MaximumRange AND GenderId = @GenderId
				END

				-- Systolic
				IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 )
				BEGIN
					SELECT TOP 1 @SystolicCategory = Category, @SystolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 23 AND @rSystolicBP >= MinimumRange AND @rSystolicBP <= MaximumRange AND GenderId = @GenderId
				END

				-- Diastolic
				IF(@rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
				BEGIN
					SELECT TOP 1 @DiastolicCategory = Category, @DiastolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 17 AND @rDiastolicBP >= MinimumRange AND @rDiastolicBP <= MaximumRange AND GenderId = @GenderId
				END

				IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 AND @rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
				BEGIN
					SET @BPScore = CASE WHEN @SystolicScore > @DiastolicScore THEN @SystolicScore ELSE @DiastolicScore END
					SET @BPCategory = CASE @BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END
				END

				IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
				BEGIN
					
					EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

					INSERT INTO [sWellness].[tMHIScore] 
					(
						Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
						HBA1C,HBA1CScore, HBA1CCategory, LDL, LDLScore, LDLCategory, BMI, BMIScore, BMICategory,
						BP, BPScore, BPCategory,
						CreatedUserId, CreatedDatetime
					) 
					VALUES
					(
						@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
						@rHBA1C, @HBA1CScore, @HBA1CCategory, @rLDL, @LDLScore, @LDLCategory, @rBMI, @BMIScore, @BMICategory,
						CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)), @BPScore, @BPCategory,
						@rUserId, sCommon.fGetDate()
					)
				END
				ELSE
				BEGIN
					UPDATE 
						[sWellness].[tMHIScore]
					SET
						HBA1C = @rHBA1C,
						HBA1CScore = @HBA1CScore,
						HBA1CCategory = @HBA1CCategory,
						LDL = @rLDL,
						LDLScore = @LDLScore,
						LDLCategory = @LDLCategory,
						BMI = @rBMI,
						BMIScore = @BMIScore,
						BMICategory = @BMICategory,
						BP = CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),
						BPScore = @BPScore,
						BPCategory = @BPCategory,
						UpdatedUserId = @rUserId,
						UpdatedDatetime = sCommon.fGetDate()
					WHERE
						EmployeeId = @rEmployeeId;

					 SET @lNextNumber =@@ROWCOUNT;
				END
			END
			-- Add OR UPDATE survey parameter not included bio metric category & biometric parameter & mhi category
			ELSE IF (@rSubmitFrom = 3)
			BEGIN				
				IF(@rStress IS NOT NULL AND @rStress > 0 )
				BEGIN
					SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress <= 13 THEN 1 WHEN @rStress <= 26 THEN 2 ELSE 3 END;
					SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
				END
				IF(@rLifeStyle IS NOT NULL AND @rLifeStyle > 0 )
				BEGIN
					SET @LifestyleIndex = CASE WHEN @rLifeStyle IS NULL THEN NULL WHEN @rLifeStyle <= 49 THEN 3 WHEN @rLifeStyle <= 70 THEN 2 ELSE 1 END;
					SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
				END

				IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
				BEGIN		
				
					EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

					INSERT INTO [sWellness].[tMHIScore] 
					(
						Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
						Stress, StressScore, StressCategory, Lifestyle, LifestyleScore, LifestyleCategory,
						CreatedUserId, CreatedDatetime
					) 
					VALUES
					(
						@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
						@rStress, @StressIndex, @StressCategory, @rLifeStyle, @LifestyleIndex, @LifeStyleCategory,
						@rUserId, sCommon.fGetDate()
					)
				END
				ELSE
				BEGIN
					UPDATE 
						[sWellness].[tMHIScore]
					SET
						Stress = @rStress,
						StressScore = @StressIndex,
						StressCategory = @StressCategory,
						Lifestyle = @rLifeStyle,
						LifestyleScore = @LifestyleIndex,
						LifestyleCategory = @LifeStyleCategory,
						UpdatedUserId = @rUserId,
						UpdatedDatetime = sCommon.fGetDate()
					WHERE
						EmployeeId = @rEmployeeId;

					 SET @lNextNumber = @@ROWCOUNT;

				END
			END

			-- Calculate Biometric Score,  Biometric Category, Survey Category, MHI Category Start
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND BMIScore IS NOT NULL AND HBA1CScore IS NOT NULL AND LDLScore IS NOT NULL AND  BPScore IS NOT NULL)
			BEGIN
				SELECT @TotalBiometrics = ISNULL(BMIScore, 0) + ISNULL(HBA1CScore, 0) + ISNULL(LDLScore, 0) + ISNULL(BPScore, 0) FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId
				SET @BiometricScore = (100.0 * @TotalBiometrics) / NULLIF(4, 0);			
				SET @BiometricsCategoryIndex = CASE WHEN @BiometricScore IS NULL THEN NULL WHEN @BiometricScore <= 100 THEN 1 WHEN @BiometricScore < 150 THEN 2 ELSE 3 END;
				SET @BiometricsCategory = CASE @BiometricsCategoryIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND StressScore IS NOT NULL AND LifestyleScore IS NOT NULL)
			BEGIN
				SELECT TOP 1 @SurveyCategory = CASE WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert' WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Optimal' END FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId;
			END
			IF(@BiometricsCategory IS NOT NULL AND @SurveyCategory IS NOT NULL)
			BEGIN
				SET @MHICategory =  CASE WHEN @BiometricsCategory = 'Alert' OR @SurveyCategory = 'Alert' THEN 'Alert' 
									WHEN @BiometricsCategory = 'SubOptimal' OR @SurveyCategory = 'SubOptimal' THEN 'SubOptimal' 
									ELSE 'Optimal' END;
			END

			UPDATE 
				[sWellness].[tMHIScore]
			SET
				Biometrics = @BiometricScore,
				BiometricsCategory = @BiometricsCategory,
				SurveyCategory = @SurveyCategory,
				MHICategory =  @MHICategory,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()
			WHERE
				EmployeeId = @rEmployeeId;

			SET @lNextNumber = @@ROWCOUNT;

			IF (@lNextNumber > 0)
			BEGIN
				 EXEC sWellness.pInsertMHIScoreHistoryIfChanged
						@rEmployeeId = @rEmployeeId,
						@rUserId     = @rUserId;
			END
 
		COMMIT TRANSACTION
        SELECT CAST(@lNextNumber AS NVARCHAR(20)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramMHIScoreNew]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScoreNew]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rSubmitFrom SMALLINT,
    @rBMI NUMERIC(10,2) = NULL,
    @rSystolicBP NUMERIC(10,0)=NULL,
    @rDiastolicBP NUMERIC(10,0)=NULL,
    @rHBA1C NUMERIC(10,2)=NULL,
    @rLDL NUMERIC(10,2)=NULL,
    @rStress NUMERIC(10,2)=NULL,
    @rLifeStyle NUMERIC(10,2)=NULL,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;
	BEGIN TRY
        BEGIN TRANSACTION
			CREATE TABLE #TempParameterRange
			(
				StaticHIPId INT, ParameterName VARCHAR(100), MinimumRange NUMERIC(10,5), MaximumRange NUMERIC(10,5), Score SMALLINT, Category NVARCHAR(100), GenderId SMALLINT
			)

			INSERT INTO #TempParameterRange 
			SELECT 
				HIPM.StaticHealthIndexParameterId, HIPM.Title, HIPD.FromValue, HIPD.ToValue, HIPD.Points, HIPD.DiagnosisRemark,HIPD.GenderId
			FROM 
				[sExamination].[tHealthIndexParameterMaster] HIPM
			INNER JOIN
				[sExamination].[tHealthIndexParameterDetail] HIPD
			ON
				HIPD.HealthIndexParameterId = HIPM.Id
			WHERE 
				StaticHealthIndexParameterId IN (1,2,5,17,23)

			DECLARE @TotalRecord INT = 0;
			SET @TotalRecord = (SELECT COUNT(StaticHIPId) FROM #TempParameterRange)
			IF(@TotalRecord > 0)
			BEGIN
				UPDATE #TempParameterRange SET Score = CASE WHEN Score = 10 THEN 1 WHEN Score = 6 THEN 2 WHEN Score = 3 THEN 3 ELSE Score END WHERE Score IS NOT NULL  AND Score > 0;
			END

			DECLARE @DepartmentId INT, @GenderId SMALLINT,
					@BMICategory NVARCHAR(30) = NULL, @BMIScore SMALLINT,
					@HBA1CCategory NVARCHAR(30) = NULL, @HBA1CScore SMALLINT,
					@LDLCategory NVARCHAR(30) = NULL, @LDLScore SMALLINT,
					@SystolicCategory NVARCHAR(30) = NULL, @SystolicScore SMALLINT,
					@DiastolicCategory NVARCHAR(30) = NULL, @DiastolicScore SMALLINT,
					@BPCategory NVARCHAR(30) = NULL, @BPScore SMALLINT = NULL,
					@BiometricsCategory VARCHAR(30) = NULL, @BiometricsCategoryIndex SMALLINT = NULL,
					@LifeStyleCategory VARCHAR(30) = NULL, @LifeStyleIndex SMALLINT = NULL,
					@StressCategory VARCHAR(30) = NULL, @StressIndex SMALLINT = NULL,
					@SurveyCategory VARCHAR(30) = NULL, @SurveyIndex SMALLINT = NULL,
					@MHICategory VARCHAR(30) = NULL, @MHICategoryId SMALLINT = NULL,
					@TotalBiometrics INT = NULL, @BiometricScore DECIMAL(10,2) = NULL,
					@AssignedMHIIndicatorId INT = 0, @AssignedProgramId INT = 0

			SET @DepartmentId = (SELECT TOP 1 DepartmentId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);
			SET @GenderId = (SELECT TOP 1 GenderId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);

			-- Add OR UPDATE Biometric parameter not included biometric category & survey & mhi category
			
				-- BMI
			IF(@rBMI IS NOT NULL AND @rBMI > 0 )
			BEGIN
				SELECT TOP 1 @BMICategory = Category, @BMIScore = Score FROM #TempParameterRange WHERE StaticHIPId = 1 AND @rBMI >= MinimumRange AND @rBMI <= MaximumRange AND GenderId = @GenderId
			END

			-- HBA1C
			IF(@rHBA1C IS NOT NULL AND @rHBA1C > 0 )
			BEGIN
				SELECT TOP 1 @HBA1CCategory = Category, @HBA1CScore = Score FROM #TempParameterRange WHERE StaticHIPId = 2 AND @rHBA1C >= MinimumRange AND @rHBA1C <= MaximumRange AND GenderId = @GenderId
			END
			-- LDL
			IF(@rLDL IS NOT NULL AND @rLDL > 0 )
			BEGIN
				SELECT TOP 1 @LDLCategory = Category, @LDLScore = Score FROM #TempParameterRange WHERE StaticHIPId = 5 AND @rLDL >= MinimumRange AND @rLDL <= MaximumRange AND GenderId = @GenderId
			END

			-- Systolic
			IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 )
			BEGIN
				SELECT TOP 1 @SystolicCategory = Category, @SystolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 23 AND @rSystolicBP >= MinimumRange AND @rSystolicBP <= MaximumRange AND GenderId = @GenderId
			END

			-- Diastolic
			IF(@rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
			BEGIN
				SELECT TOP 1 @DiastolicCategory = Category, @DiastolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 17 AND @rDiastolicBP >= MinimumRange AND @rDiastolicBP <= MaximumRange AND GenderId = @GenderId
			END

			IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 AND @rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
			BEGIN
				SET @BPScore = CASE WHEN @SystolicScore > @DiastolicScore THEN @SystolicScore ELSE @DiastolicScore END
				SET @BPCategory = CASE @BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END
			END

			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
			BEGIN
					
				EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tMHIScore] 
				(
					Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
					HBA1C,HBA1CScore, HBA1CCategory, LDL, LDLScore, LDLCategory, BMI, BMIScore, BMICategory,
					BP, BPScore, BPCategory,
					CreatedUserId, CreatedDatetime
				) 
				VALUES
				(
					@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
					@rHBA1C, @HBA1CScore, @HBA1CCategory, @rLDL, @LDLScore, @LDLCategory, @rBMI, @BMIScore, @BMICategory,
					CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)), @BPScore, @BPCategory,
					@rUserId, sCommon.fGetDate()
				)
			END
			ELSE
			BEGIN
				UPDATE 
					[sWellness].[tMHIScore]
				SET
					HBA1C = @rHBA1C,
					HBA1CScore = @HBA1CScore,
					HBA1CCategory = @HBA1CCategory,
					LDL = @rLDL,
					LDLScore = @LDLScore,
					LDLCategory = @LDLCategory,
					BMI = @rBMI,
					BMIScore = @BMIScore,
					BMICategory = @BMICategory,
					BP = CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),
					BPScore = @BPScore,
					BPCategory = @BPCategory,
					UpdatedUserId = @rUserId,
					UpdatedDatetime = sCommon.fGetDate()
				WHERE
					EmployeeId = @rEmployeeId;

					SET @lNextNumber =@@ROWCOUNT;
			END
			
			-- Add OR UPDATE survey parameter not included bio metric category & biometric parameter & mhi category
			IF(@rStress IS NOT NULL AND @rStress > 0 )
			BEGIN
				--SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress <= 13 THEN 1 WHEN @rStress <= 26 THEN 2 ELSE 3 END;
				SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress >= 90 THEN 1 WHEN @rStress >= 75 THEN 2 ELSE 3 END;
				SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			IF(@rLifeStyle IS NOT NULL AND @rLifeStyle > 0 )
			BEGIN
				SET @LifestyleIndex = CASE WHEN @rLifeStyle IS NULL THEN NULL WHEN @rLifeStyle <= 49 THEN 3 WHEN @rLifeStyle <= 70 THEN 2 ELSE 1 END;
				SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END

			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
			BEGIN		
				
				EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tMHIScore] 
				(
					Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
					Stress, StressScore, StressCategory, Lifestyle, LifestyleScore, LifestyleCategory,
					CreatedUserId, CreatedDatetime
				) 
				VALUES
				(
					@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
					@rStress, @StressIndex, @StressCategory, @rLifeStyle, @LifestyleIndex, @LifeStyleCategory,
					@rUserId, sCommon.fGetDate()
				)
			END
			ELSE
			BEGIN
				UPDATE 
					[sWellness].[tMHIScore]
				SET
					Stress = @rStress,
					StressScore = @StressIndex,
					StressCategory = @StressCategory,
					Lifestyle = @rLifeStyle,
					LifestyleScore = @LifestyleIndex,
					LifestyleCategory = @LifeStyleCategory,
					UpdatedUserId = @rUserId,
					UpdatedDatetime = sCommon.fGetDate()
				WHERE
					EmployeeId = @rEmployeeId;

					SET @lNextNumber = @@ROWCOUNT;

			END

			-- Calculate Biometric Score,  Biometric Category, Survey Category, MHI Category Start
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND BMIScore IS NOT NULL AND HBA1CScore IS NOT NULL AND LDLScore IS NOT NULL AND  BPScore IS NOT NULL)
			BEGIN
				SELECT @TotalBiometrics = ISNULL(BMIScore, 0) + ISNULL(HBA1CScore, 0) + ISNULL(LDLScore, 0) + ISNULL(BPScore, 0) FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId
				SET @BiometricScore = (100.0 * @TotalBiometrics) / NULLIF(4, 0);			
				SET @BiometricsCategoryIndex = CASE WHEN @BiometricScore IS NULL THEN NULL WHEN @BiometricScore <= 100 THEN 1 WHEN @BiometricScore < 150 THEN 2 ELSE 3 END;
				SET @BiometricsCategory = CASE @BiometricsCategoryIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND StressScore IS NOT NULL AND LifestyleScore IS NOT NULL)
			BEGIN
				SELECT TOP 1 @SurveyCategory = CASE WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert' WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Optimal' END FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId;
			END
			IF(@BiometricsCategory IS NOT NULL AND @SurveyCategory IS NOT NULL)
			BEGIN
				SET @MHICategory =  CASE WHEN @BiometricsCategory = 'Alert' OR @SurveyCategory = 'Alert' THEN 'Alert' 
									WHEN @BiometricsCategory = 'SubOptimal' OR @SurveyCategory = 'SubOptimal' THEN 'SubOptimal' 
									ELSE 'Optimal' END;

				SET @MHICategoryId = CASE  WHEN @MHICategory = 'Alert' THEN 3  WHEN @MHICategory = 'SubOptimal' THEN 2 WHEN @MHICategory = 'Optimal' THEN 1 ELSE 0 END;

				IF(@MHICategoryId > 0)
				BEGIN
					SET @AssignedMHIIndicatorId = (SELECT TOP 1 Id FROM [sWellness].[tStaticMHICategoryIndicator] WHERE Id = @MHICategoryId)
					IF(@AssignedMHIIndicatorId > 0)
					BEGIN
						SET @AssignedProgramId = (SELECT TOP 1 Id FROM [sWellness].[tProgramMaster] WHERE MHIIndicatorId = @AssignedMHIIndicatorId AND CategoryId = 1 AND IsObsolete = 0)
					END
				END
			END
			ELSE
			BEGIN
				SET @MHICategory = 'NotApplicable';
				SET @MHICategoryId = 0;
				SET @AssignedProgramId = 0;
			END

			UPDATE 
				[sWellness].[tMHIScore]
			SET
				ProgramId = @AssignedProgramId,
				Biometrics = @BiometricScore,
				BiometricsCategory = @BiometricsCategory,
				SurveyCategory = @SurveyCategory,
				MHICategory =  @MHICategory,
				MHICategoryId =  @MHICategoryId,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()
			WHERE
				EmployeeId = @rEmployeeId;

			SET @lNextNumber = @@ROWCOUNT;

			IF (@lNextNumber > 0)
			BEGIN
				 EXEC sWellness.pInsertMHIScoreHistoryIfChanged
						@rEmployeeId = @rEmployeeId,
						@rUserId     = @rUserId;
			END
 
		COMMIT TRANSACTION
        SELECT CAST(@lNextNumber AS NVARCHAR(20)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[PEmpDashboardDetailGet]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[PEmpDashboardDetailGet]  
@rEmpId bigint,  
@rOrgId int = 0  
as  
begin    
declare @lLatestVitalDisplayConfigVal varchar(5) = 'False';          
IF (@rOrgId > 0)  
BEGIN   
select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);  
END   

Declare @lHeight int =0,
        @lWeight decimal(8,2)=0,
		@lBMI decimal(8,2)=0,
		@lBloodPressureSystolic int=0,
		@lBloodPressureDiastolic int=0,
        @lHBA1C nvarchar(10)='0', 
		@lLDL nvarchar(10)='0',
		@lBMIDate nvarchar(20)='', 
		@lBPDate nvarchar(20)='', 
		@lHBA1CDate nvarchar(20)='', 
		@lLDLDate nvarchar(20)='';     
		
IF (@rEmpId > 0)
BEGIN

Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103)   
from sExamination.tExamination E   
inner join sExamination.tVital V on V.SourceId=E.Id  
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId    
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId  
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  
and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0  
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))  
Order by E.ExaminationDate desc;    


Select Top 1 @lBloodPressureSystolic=BloodPressureSystolic,@lBloodPressureDiastolic=BloodPressureDiastolic,  @lBPDate=convert(varchar(20),ExaminationDate,103)  
from sExamination.tExamination E   
inner join sExamination.tVital V on V.SourceId=E.Id  
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId   
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId 
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  
and Isnull(V.BloodPressureSystolic,0)>0 and Isnull(V.BloodPressureDiastolic,0)>0   
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))  
Order by E.ExaminationDate desc;      


Select Top 1 @lHBA1C=TRD.ServiceValue,   @lHBA1CDate=convert(varchar(20),ExaminationDate,103)  
from sExamination.tTestRequestDetail TRD    
inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id        
inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id    
inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id    
inner join sExamination.tExamination E on TR.SourceId = E.Id  
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  and TP.StaticTestParameterId = 25 
and  Isnull(TRD.ServiceValue,'')<>''  
Order By E.ExaminationDate desc;      


Select Top 1 @lLDL=TRD.ServiceValue,  @lLDLDate=convert(varchar(20),ExaminationDate,103)  
from sExamination.tTestRequestDetail TRD    
inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id        
inner join sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id    
inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id    
inner join sExamination.tExamination E on TR.SourceId = E.Id  
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  
and TP.StaticTestParameterId = 34 and  Isnull(TRD.ServiceValue,'')<>''  
Order By E.ExaminationDate desc;    

END

SELECT    
     'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,   
	 'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,   
	 Isnull(@lHeight,0) as Height1,   
	 Isnull(@lWeight,0) as Weight1,   
	 Isnull(@lBMI,0) as BMI,   
	 convert(varchar(10),Isnull(@lBloodPressureSystolic,0)) + '/' + Convert(varchar(10),Isnull(@lBloodPressureDiastolic,0)) as BP,   
	 Isnull(@lHBA1C,'0') as HBA1C,   
	 Isnull(@lLDL,'0') as LDL,   
	 @lBMIDate as BMIDate,   
	 @lBPDate as BPDate,   
	 @lHBA1CDate as HBA1CDate,   
	 @lLDLDate as LDLDate;    
	 
EXEC [sWellness].[pGetEmployeeHealthIndex] @rEmpId , @lBMI ,@lBMIDate, @lBloodPressureSystolic , @lBloodPressureDiastolic ,@lBPDate, @lHBA1C ,@lHBA1CDate,  @lLDL, @lLDLDate;  
	 
END
GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportALLContractExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportALLContractExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptSmallCardMain]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptSmallCardMain]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindGeneralTemplates]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindGeneralTemplates]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptForm22]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptForm22]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindGeneralTemplateResultLists]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindGeneralTemplateResultLists]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportALLExaminationDataTableDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportALLExaminationDataTableDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationAllDetailListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationAllDetailListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationAllDetailListGet_n]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationAllDetailListGet_n]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationAllDetailListGetForExport_n]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationAllDetailListGetForExport_n]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportALLImportGeneralExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportALLImportGeneralExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sMro].[pExaminationGenerateReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pExaminationGenerateReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFullHealthCardGet_NEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFullHealthCardGet_NEW]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_GeneralTemplateSettings]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_GeneralTemplateSettings]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAllResultGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAllResultGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportALLExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportALLExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPreEmployeementFormWithDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPreEmployeementFormWithDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateGeneralTemplateExaminationDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateGeneralTemplateExaminationDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPeriodicForm]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPeriodicForm]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplatExaminationDetailModify]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplatExaminationDetailModify]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisGenerateAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisGenerateAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationFullViewGet_NEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationFullViewGet_NEW]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportGeneralExaminationALL_Latest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportGeneralExaminationALL_Latest]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFindAndUpdateExaminationsGeneralTemplates]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFindAndUpdateExaminationsGeneralTemplates]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptForm0]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptForm0]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCreateGeneralTemplateExaminationN]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCreateGeneralTemplateExaminationN]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_SettingsGeneralTemplateAndParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_SettingsGeneralTemplateAndParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[tBindDataEntryTemplateFromOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[tBindDataEntryTemplateFromOPD]';


GO
PRINT N'Refreshing Procedure [sTool].[pGeneralTemplatesSettings]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pGeneralTemplatesSettings]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDiminishHearing]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDiminishHearing]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAllResultGetPopup]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAllResultGetPopup]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptEmployeewiseClinicalValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptEmployeewiseClinicalValue]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptAbnormalEar]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptAbnormalEar]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDCustomSearchGenerateReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDCustomSearchGenerateReport]';


GO
PRINT N'Refreshing Procedure [sHostel].[pGeneralGet1]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHostel].[pGeneralGet1]';


GO
PRINT N'Refreshing Procedure [sMro].[pCustomOPDHistoryListGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pCustomOPDHistoryListGetWithPagination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindEyeTemplates]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindEyeTemplates]';


GO
PRINT N'Refreshing Procedure [sMro].[pMROFullViewArchiveGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pMROFullViewArchiveGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFullViewGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFullViewGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pNewlyDiagnosedforExport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pNewlyDiagnosedforExport]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_SettingForAbnormalParameteresGeneral]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_SettingForAbnormalParameteresGeneral]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindGeneralTemplatesNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindGeneralTemplatesNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGeneralTemplate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGeneralTemplate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBulkOperationDiagnosisGenerateAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBulkOperationDiagnosisGenerateAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationFullViewGet_NEWNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationFullViewGet_NEWNg]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_DeleteExaminationDataBySetup]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_DeleteExaminationDataBySetup]';


GO
PRINT N'Refreshing Procedure [sCommon].[prc_GetAiSuggestionForExaminationData]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[prc_GetAiSuggestionForExaminationData]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindGeneralTemplateResultLists_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindGeneralTemplateResultLists_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCreateGeneralTemplateExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCreateGeneralTemplateExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDefaulSaveNormalGeneralTemplateExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDefaulSaveNormalGeneralTemplateExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDeleteGeneralParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDeleteGeneralParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationRecordRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationRecordRemove]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExportAdaniExaminations_Export]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExportAdaniExaminations_Export]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExportAllExaminations_Export]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExportAllExaminations_Export]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExportExaminationBasedOnDate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExportExaminationBasedOnDate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateDetailUpdateById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateDetailUpdateById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateExamiantionDetailUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateExamiantionDetailUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateExaminationAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateExaminationAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateExaminationCriteriaGroupAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateExaminationCriteriaGroupAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateListingResultAllGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateListingResultAllGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateListingResultAllGetDB]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateListingResultAllGetDB]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllGeneralTemplateResults]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllGeneralTemplateResults]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportGeneralExaminationALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportGeneralExaminationALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCardGeneralExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCardGeneralExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationGeneralTestReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationGeneralTestReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptForm22MedicalHistory]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptForm22MedicalHistory]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetHealthCardSubGeneralParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetHealthCardSubGeneralParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveTestResultsFirst]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveTestResultsFirst]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateGeneralTemplateExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateGeneralTemplateExamination]';


GO
PRINT N'Refreshing Procedure [sTool].[pArchieveExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pArchieveExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sTool].[pEmployeeDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pEmployeeDelete]';


GO
PRINT N'Refreshing Procedure [sTool].[pEmployeeExaminationDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pEmployeeExaminationDelete]';


GO
PRINT N'Refreshing Procedure [sTool].[pRestoreExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pRestoreExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sTool].[pSubLocationExaminationDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pSubLocationExaminationDelete]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDeleteImportExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDeleteImportExamination]';


GO
PRINT N'Refreshing Procedure [sConfig].[pDeleteImportData]...';


GO
EXECUTE sp_refreshsqlmodule N'[sConfig].[pDeleteImportData]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptEmployeewiseAllTestValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptEmployeewiseAllTestValue]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisPartialValueAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisPartialValueAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestDetailUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestDetailUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestDetailModify]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestDetailModify]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdateOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerEmployeeUpdateOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptSmallCardMainCheck]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptSmallCardMainCheck]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTestResultsOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTestResultsOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisGet_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisGet_OLD]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_SettingsToUpdateTestsForMobile]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_SettingsToUpdateTestsForMobile]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetMissingParameterTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetMissingParameterTest]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_updateAllLDLHDLRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_updateAllLDLHDLRatio]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListSearchGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListSearchGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLSDTrackerEmployeeUpdateALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLSDTrackerEmployeeUpdateALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationEmployeeDetailGetForChart]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationEmployeeDetailGetForChart]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLSDTrackerEmployeeUpdateBulk]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLSDTrackerEmployeeUpdateBulk]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCreateTestResultsByIdN]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCreateTestResultsByIdN]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateUrineParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateUrineParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptEmployeewiseTestValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptEmployeewiseTestValue]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptWellEmployee_Check]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptWellEmployee_Check]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobExaminationEmployeeDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobExaminationEmployeeDetailGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptWellEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptWellEmployee]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptIndividualTestwiseCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptIndividualTestwiseCost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobExaminationGraphGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobExaminationGraphGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdateALLBySourceIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerEmployeeUpdateALLBySourceIds]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAllResultGet_old]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAllResultGet_old]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTestRequestDatasById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTestRequestDatasById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAllResultGet_dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAllResultGet_dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTestResultsExaminationAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTestResultsExaminationAll]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateLDLHDLANDRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateLDLHDLANDRatio]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetHealthCardSubTestsParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetHealthCardSubTestsParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLSDTrackerEmployeeUpdateALLBySourceIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLSDTrackerEmployeeUpdateALLBySourceIds]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateIsnormalcValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateIsnormalcValue]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptHealthCard]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptHealthCard]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationAnalysis]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationAnalysis]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationInvestigationALL_NEWLatest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationInvestigationALL_NEWLatest]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseTotalList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseTotalList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptIndividualPackagewiseCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptIndividualPackagewiseCost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestCriteriaGroupAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestCriteriaGroupAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPathology]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPathology]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerMetabolicSyndromeUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerMetabolicSyndromeUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCardTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCardTest]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestForResultGetNEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestForResultGetNEW]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerEmployeeUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisExportDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisExportDetailGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptEmployeewiseTestListValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptEmployeewiseTestListValue]';


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderHealthIndicator]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderHealthIndicator]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveAutocalculatedValues]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveAutocalculatedValues]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportTestExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportTestExamination]';


GO
PRINT N'Refreshing Procedure [sSupport].[pAHCCounsellingListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pAHCCounsellingListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestDetailUpdateImport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestDetailUpdateImport]';


GO
PRINT N'Refreshing Procedure [sSupport].[pAHCCounsellingReferDoctor]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pAHCCounsellingReferDoctor]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportTestAddUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportTestAddUpdate]';


GO
PRINT N'Refreshing Procedure [sSupport].[pCalculateHealthIndicator]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pCalculateHealthIndicator]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTestRequestDatasByIdNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTestRequestDatasByIdNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTestResultsOPDNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTestResultsOPDNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerCVDMajorRiskUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerCVDMajorRiskUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetEmployeeTestParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetEmployeeTestParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerCVDMinorRiskUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerCVDMinorRiskUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListSearchGetNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListSearchGetNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerNCDRiskUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerNCDRiskUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthIndexValueAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthIndexValueAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptEmployeewiseTestValueN]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptEmployeewiseTestValueN]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_SettingForAbnormalParameteres]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_SettingForAbnormalParameteres]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllExaminationDatasOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllExaminationDatasOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestReport_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestReport_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdateALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrackerEmployeeUpdateALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBulkOperationHealthIndexValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBulkOperationHealthIndexValue]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_LoadSettingsForLDLHDL]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_LoadSettingsForLDLHDL]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateASpecificValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateASpecificValue]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateDIABETICParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateDIABETICParameters]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateLDLHDLRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateLDLHDLRatio]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateLDLHDLRatioALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateLDLHDLRatioALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCompareParameterForAlert]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCompareParameterForAlert]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCompareParameterForAlertSend]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCompareParameterForAlertSend]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCompareParameterResultAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCompareParameterResultAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCompareParameterResultDepartmentwise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCompareParameterResultDepartmentwise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCreateTestResultsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCreateTestResultsById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDeleteTestParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDeleteTestParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAnalysisDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAnalysisDetailsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAnalysisEmployeeDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAnalysisEmployeeDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAnalysisEmployeeDataGet_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAnalysisEmployeeDataGet_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAnalysisGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAnalysisGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisAnalysisGet_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisAnalysisGet_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisRemarkGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisRemarkGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisRemarkSetupwiseGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisRemarkSetupwiseGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisRemarkSetupwiseGet_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisRemarkSetupwiseGet_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisSearchListBindWithValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisSearchListBindWithValue]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisSearchListGetWithValue]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisSearchListGetWithValue]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisSearchListGetWithValueWithMail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisSearchListGetWithValueWithMail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrakersDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrakersDetailsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisTrakersGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisTrakersGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDignosisRemarkWellEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDignosisRemarkWellEmployee]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDignosisRemarkWellEmployee_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDignosisRemarkWellEmployee_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pEmployeeExaminationListingGetDS]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pEmployeeExaminationListingGetDS]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFindAndUpdateExaminationsHDLCholesterolRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFindAndUpdateExaminationsHDLCholesterolRatio]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFindAndUpdateExaminationsLDLHDLRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFindAndUpdateExaminationsLDLHDLRatio]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFindAndUpdateExaminationsLipidProfile]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFindAndUpdateExaminationsLipidProfile]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllDetailsForOPDLog]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllDetailsForOPDLog]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllExaminationDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllExaminationDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeExaminationViewDatasNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeExaminationViewDatasNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationTests]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationTests]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTargetGroupWiseTestCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTargetGroupWiseTestCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisEmployeeParameterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisEmployeeParameterGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisEmployeeParameterGetWithMail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisEmployeeParameterGetWithMail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisEmployeeParameterGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisEmployeeParameterGetWithPagination]';


GO
PRINT N'Refreshing Procedure [sExamination].[PHelathIndexMissingParameter]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[PHelathIndexMissingParameter]';


GO
PRINT N'Refreshing Procedure [sExamination].[PHelathIndexMissingParameterNew]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[PHelathIndexMissingParameterNew]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHistoryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHistoryGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationInvestigationALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationInvestigationALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationInvestigationALL_NEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationInvestigationALL_NEW]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetEmployeeExaminationViewDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetEmployeeExaminationViewDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdQuickRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdQuickRemove]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdQuickRemoveByNumber]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdQuickRemoveByNumber]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDignosisRemark_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDignosisRemark_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationTestReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationTestReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestReportAcuity_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestReportAcuity_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSettingsForTestDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSettingsForTestDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempDiagnosisRemarkAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempDiagnosisRemarkAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempDiagnosisRemarkAdd_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempDiagnosisRemarkAdd_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisExportDetailGet_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisExportDetailGet_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestDetailUpdateById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestDetailUpdateById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestListParameterListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestListParameterListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestNumericParameterListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestNumericParameterListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestTextParameterListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestTextParameterListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateTestResultsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateTestResultsById]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pGetParameterFlag]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pGetParameterFlag]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestDetailGet]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestMasterAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestMasterAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pProviderCountGet_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pProviderCountGet_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALLTracker]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALLTracker]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALLTrackerBySourceIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALLTrackerBySourceIds]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALLHealthIndex]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALLHealthIndex]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempWellEmployeeAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempWellEmployeeAdd]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pMedicalReviewLogGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pMedicalReviewLogGet]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pSubmitRemark]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pSubmitRemark]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pHospitalizationReferDoctor]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pHospitalizationReferDoctor]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pDashboardDetailsGetAllDoctors]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pDashboardDetailsGetAllDoctors]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pIntimationDetailsListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pIntimationDetailsListGet]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateUrineParametersToText]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateUrineParametersToText]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterDetailGetByOrgId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterDetailGetByOrgId]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestRequestForResultGetWID]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestRequestForResultGetWID]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindParameterDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindParameterDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindTestParameterDetailRange]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindTestParameterDetailRange]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisRemarkDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisRemarkDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisRemarkGet_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisRemarkGet_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisRemarkNumericDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisRemarkNumericDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestListMinMaxRange]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestListMinMaxRange]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestSetupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestSetupGet]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pDeleteParamtersAccordingStaticTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pDeleteParamtersAccordingStaticTest]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pDeleteTestsAccordingStaticTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pDeleteTestsAccordingStaticTest]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pDeleteTestsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pDeleteTestsById]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pSaveTestParametersByTestIdNew]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pSaveTestParametersByTestIdNew]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterDetailGet]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterDetailModify]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterDetailModify]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetDiseasePrescriptionTests]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetDiseasePrescriptionTests]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterModify]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterModify]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestListTypeSetupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestListTypeSetupGet]';


GO
PRINT N'Refreshing Procedure [sOCR].[pFindStandardNameOfOCRTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOCR].[pFindStandardNameOfOCRTest]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterListGet]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFullViewArchieveGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFullViewArchieveGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pGetFormParameterListALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pGetFormParameterListALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindSetupAreas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindSetupAreas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindTemplateAreas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindTemplateAreas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCriteriaGroupAreaAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCriteriaGroupAreaAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCriteriaGroupSubAreaGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCriteriaGroupSubAreaGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDefaultAllSetupAreaGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDefaultAllSetupAreaGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiseaseTestDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiseaseTestDetailGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGeneralTemplateParameterAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGeneralTemplateParameterAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllParametersByTestId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllParametersByTestId]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetContractExaminationImportTemplate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetContractExaminationImportTemplate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationImportTemplate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationImportTemplate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationParameterListImport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationParameterListImport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetParameterValueTypeByTestId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetParameterValueTypeByTestId]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTestParameterByTestId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTestParameterByTestId]';


GO
PRINT N'Refreshing Procedure [sExamination].[pReturnValidateTestByName]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pReturnValidateTestByName]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestListwithNormalRange]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestListwithNormalRange]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTargetGroupTemplateGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTargetGroupTemplateGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestParameterListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestParameterListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pValidateTestByName]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pValidateTestByName]';


GO
PRINT N'Refreshing Procedure [sOCR].[pGetOCRTestParameterDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOCR].[pGetOCRTestParameterDetail]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pBindTestParameterGridImport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pBindTestParameterGridImport]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pGetParameterListALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pGetParameterListALL]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pImportantProcforTestUpdates]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pImportantProcforTestUpdates]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pServiceCostParameterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pServiceCostParameterGet]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParameterMasterGetById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParameterMasterGetById]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pTestParemeterOrderIndexGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pTestParemeterOrderIndexGet]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pUpdateTestParameterById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pUpdateTestParameterById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestParameterForHistoryMultipleGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestParameterForHistoryMultipleGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetProgramParticipants]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetProgramParticipants]';


GO
PRINT N'Refreshing Procedure [sSupport].[pHealthSurveyTemplateMasterCopy]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pHealthSurveyTemplateMasterCopy]';


GO
PRINT N'Refreshing Procedure [sSupport].[pHealthSurveyTemplateMasterSaveOrUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pHealthSurveyTemplateMasterSaveOrUpdate]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetCoachProgramsList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetCoachProgramsList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetProgramDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetProgramDetails]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetProgramsList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetProgramsList]';


GO
PRINT N'Refreshing Procedure [sTm].[pShiftRoasterAddBulk]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTm].[pShiftRoasterAddBulk]';

GO
PRINT N'Refreshing Procedure [sHrm].[pImportExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pImportExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationAnalysis_Check]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationAnalysis_Check]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveAllExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveAllExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pSaveTestParametersByTestId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pSaveTestParametersByTestId]';


GO
PRINT N'Refreshing Procedure [sOrderEntry].[pSaveTestsAccordingStaticTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOrderEntry].[pSaveTestsAccordingStaticTest]';


GO
PRINT N'Refreshing Procedure [sExamination].[pValidateExaminationDataTable]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pValidateExaminationDataTable]';